FunctionBody.cpp 369 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "RuntimeBasePch.h"
  6. #include "ByteCode/ByteCodeApi.h"
  7. #include "ByteCode/ByteCodeDumper.h"
  8. #include "Language/AsmJsTypes.h"
  9. #include "Language/AsmJsModule.h"
  10. #include "ByteCode/ByteCodeSerializer.h"
  11. #include "Language/FunctionCodeGenRuntimeData.h"
  12. #include "ByteCode/ScopeInfo.h"
  13. #include "Base/EtwTrace.h"
  14. #ifdef VTUNE_PROFILING
  15. #include "Base/VTuneChakraProfile.h"
  16. #endif
  17. #ifdef DYNAMIC_PROFILE_MUTATOR
  18. #include "Language/DynamicProfileMutator.h"
  19. #endif
  20. #include "Language/SourceDynamicProfileManager.h"
  21. #ifdef ENABLE_SCRIPT_DEBUGGING
  22. #include "Debug/ProbeContainer.h"
  23. #include "Debug/DebugContext.h"
  24. #endif
  25. #include "Parser.h"
  26. #include "RegexCommon.h"
  27. #include "RegexPattern.h"
  28. #include "Library/RegexHelper.h"
  29. #include "Language/InterpreterStackFrame.h"
  30. #include "Library/ModuleRoot.h"
  31. #include "Types/PathTypeHandler.h"
  32. #include "Common/MathUtil.h"
  33. namespace Js
  34. {
  35. // The VS2013 linker treats this as a redefinition of an already
  36. // defined constant and complains. So skip the declaration if we're compiling
  37. // with VS2013 or below.
  38. #if !defined(_MSC_VER) || _MSC_VER >= 1900
  39. uint const ScopeSlots::MaxEncodedSlotCount;
  40. #endif
  41. #ifdef FIELD_ACCESS_STATS
  42. void FieldAccessStats::Add(FieldAccessStats* other)
  43. {
  44. Assert(other != nullptr);
  45. this->totalInlineCacheCount += other->totalInlineCacheCount;
  46. this->noInfoInlineCacheCount += other->noInfoInlineCacheCount;
  47. this->monoInlineCacheCount += other->monoInlineCacheCount;
  48. this->emptyMonoInlineCacheCount += other->emptyMonoInlineCacheCount;
  49. this->polyInlineCacheCount += other->polyInlineCacheCount;
  50. this->nullPolyInlineCacheCount += other->nullPolyInlineCacheCount;
  51. this->emptyPolyInlineCacheCount += other->emptyPolyInlineCacheCount;
  52. this->ignoredPolyInlineCacheCount += other->ignoredPolyInlineCacheCount;
  53. this->highUtilPolyInlineCacheCount += other->highUtilPolyInlineCacheCount;
  54. this->lowUtilPolyInlineCacheCount += other->lowUtilPolyInlineCacheCount;
  55. this->equivPolyInlineCacheCount += other->equivPolyInlineCacheCount;
  56. this->nonEquivPolyInlineCacheCount += other->nonEquivPolyInlineCacheCount;
  57. this->disabledPolyInlineCacheCount += other->disabledPolyInlineCacheCount;
  58. this->clonedMonoInlineCacheCount += other->clonedMonoInlineCacheCount;
  59. this->clonedPolyInlineCacheCount += other->clonedPolyInlineCacheCount;
  60. }
  61. #endif
  62. // FunctionProxy methods
  63. FunctionProxy::FunctionProxy(ScriptContext* scriptContext, Utf8SourceInfo* utf8SourceInfo, uint functionNumber):
  64. m_isTopLevel(false),
  65. m_isPublicLibraryCode(false),
  66. m_scriptContext(scriptContext),
  67. m_utf8SourceInfo(utf8SourceInfo),
  68. m_functionNumber(functionNumber),
  69. m_defaultEntryPointInfo(nullptr),
  70. m_displayNameIsRecyclerAllocated(false),
  71. m_tag11(true),
  72. m_isJsBuiltInCode(false)
  73. {
  74. #if DBG
  75. m_isJsBuiltInInitCode = false;
  76. #endif
  77. PERF_COUNTER_INC(Code, TotalFunction);
  78. }
  79. bool FunctionProxy::IsWasmFunction() const
  80. {
  81. return GetFunctionInfo()->HasParseableInfo() &&
  82. GetFunctionInfo()->GetFunctionBody()->IsWasmFunction();
  83. }
  84. Recycler* FunctionProxy::GetRecycler() const
  85. {
  86. return m_scriptContext->GetRecycler();
  87. }
  88. void* FunctionProxy::GetAuxPtr(AuxPointerType e) const
  89. {
  90. if (this->auxPtrs == nullptr)
  91. {
  92. return nullptr;
  93. }
  94. // On process detach this can be called from another thread but the ThreadContext should be locked
  95. Assert(ThreadContext::GetContextForCurrentThread() || ThreadContext::GetCriticalSection()->IsLocked());
  96. return AuxPtrsT::GetAuxPtr(this, e);
  97. }
  98. void* FunctionProxy::GetAuxPtrWithLock(AuxPointerType e) const
  99. {
  100. if (this->auxPtrs == nullptr)
  101. {
  102. return nullptr;
  103. }
  104. #if DBG && ENABLE_NATIVE_CODEGEN && defined(_WIN32)
  105. // the lock for work item queue should not be locked while accessing AuxPtrs in background thread
  106. auto jobProcessor = this->GetScriptContext()->GetThreadContext()->GetJobProcessor();
  107. auto jobProcessorCS = jobProcessor->GetCriticalSection();
  108. // ->IsLocked is not supported on xplat
  109. Assert(!jobProcessorCS || !jobProcessor->ProcessesInBackground() || !jobProcessorCS->IsLocked());
  110. #endif
  111. AutoCriticalSection autoCS(this->GetScriptContext()->GetThreadContext()->GetFunctionBodyLock());
  112. return AuxPtrsT::GetAuxPtr(this, e);
  113. }
  114. void FunctionProxy::SetAuxPtr(AuxPointerType e, void* ptr)
  115. {
  116. // On process detach this can be called from another thread but the ThreadContext should be locked
  117. Assert(ThreadContext::GetContextForCurrentThread() || ThreadContext::GetCriticalSection()->IsLocked());
  118. if (ptr == nullptr && GetAuxPtr(e) == nullptr)
  119. {
  120. return;
  121. }
  122. // when setting ptr to null we never need to promote
  123. AutoCriticalSection autoCS(this->GetScriptContext()->GetThreadContext()->GetFunctionBodyLock());
  124. AuxPtrsT::SetAuxPtr(this, e, ptr);
  125. }
  126. uint FunctionProxy::GetSourceContextId() const
  127. {
  128. return this->GetUtf8SourceInfo()->GetSrcInfo()->sourceContextInfo->sourceContextId;
  129. }
  130. char16* FunctionProxy::GetDebugNumberSet(wchar(&bufferToWriteTo)[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE]) const
  131. {
  132. // (#%u.%u), #%u --> (source file Id . function Id) , function Number
  133. int len = swprintf_s(bufferToWriteTo, MAX_FUNCTION_BODY_DEBUG_STRING_SIZE, _u(" (#%d.%u), #%u"),
  134. (int)this->GetSourceContextId(), this->GetLocalFunctionId(), this->GetFunctionNumber());
  135. Assert(len > 8);
  136. return bufferToWriteTo;
  137. }
  138. bool
  139. FunctionProxy::IsFunctionBody() const
  140. {
  141. return !IsDeferredDeserializeFunction() && GetParseableFunctionInfo()->IsFunctionParsed();
  142. }
  143. uint
  144. ParseableFunctionInfo::GetSourceIndex() const
  145. {
  146. return this->m_sourceIndex;
  147. }
  148. LPCUTF8
  149. ParseableFunctionInfo::GetSource(const char16* reason) const
  150. {
  151. return this->GetUtf8SourceInfo()->GetSource(reason == nullptr ? _u("ParseableFunctionInfo::GetSource") : reason) + this->StartOffset();
  152. }
  153. LPCUTF8
  154. ParseableFunctionInfo::GetStartOfDocument(const char16* reason) const
  155. {
  156. return this->GetUtf8SourceInfo()->GetSource(reason == nullptr ? _u("ParseableFunctionInfo::GetStartOfDocument") : reason);
  157. }
  158. bool
  159. ParseableFunctionInfo::IsDynamicFunction() const
  160. {
  161. return this->m_isDynamicFunction;
  162. }
  163. bool
  164. ParseableFunctionInfo::IsDynamicScript() const
  165. {
  166. return this->GetSourceContextInfo()->IsDynamic();
  167. }
  168. charcount_t
  169. ParseableFunctionInfo::StartInDocument() const
  170. {
  171. return this->m_cchStartOffset;
  172. }
  173. uint
  174. ParseableFunctionInfo::StartOffset() const
  175. {
  176. return this->m_cbStartOffset;
  177. }
  178. void ParseableFunctionInfo::RegisterFuncToDiag(ScriptContext * scriptContext, char16 const * pszTitle)
  179. {
  180. #ifdef ENABLE_SCRIPT_DEBUGGING
  181. // Register the function to the PDM as eval code (the debugger app will show file as 'eval code')
  182. scriptContext->GetDebugContext()->RegisterFunction(this, pszTitle);
  183. #endif
  184. }
  185. bool ParseableFunctionInfo::IsES6ModuleCode() const
  186. {
  187. return (GetGrfscr() & fscrIsModuleCode) == fscrIsModuleCode;
  188. }
  189. // Given an offset into the source buffer, determine if the end of this SourceInfo
  190. // lies after the given offset.
  191. bool
  192. ParseableFunctionInfo::EndsAfter(size_t offset) const
  193. {
  194. return offset < this->StartOffset() + this->LengthInBytes();
  195. }
  196. uint32 FunctionBody::GetCountField(FunctionBody::CounterFields fieldEnum) const
  197. {
  198. #if DBG
  199. Assert(ThreadContext::GetContextForCurrentThread() || counters.isLockedDown
  200. || (ThreadContext::GetCriticalSection()->IsLocked() && this->m_scriptContext->GetThreadContext()->GetFunctionBodyLock()->IsLocked())); // etw rundown
  201. #endif
  202. return counters.Get(fieldEnum);
  203. }
  204. uint32 FunctionBody::SetCountField(FunctionBody::CounterFields fieldEnum, uint32 val)
  205. {
  206. Assert(!counters.isLockedDown);
  207. return counters.Set(fieldEnum, val, this);
  208. }
  209. uint32 FunctionBody::IncreaseCountField(FunctionBody::CounterFields fieldEnum)
  210. {
  211. Assert(!counters.isLockedDown);
  212. return counters.Increase(fieldEnum, this);
  213. }
  214. void
  215. FunctionBody::RecordStatementMap(StatementMap* pStatementMap)
  216. {
  217. Assert(!this->m_sourceInfo.pSpanSequence);
  218. Recycler* recycler = this->m_scriptContext->GetRecycler();
  219. StatementMapList * statementMaps = this->GetStatementMaps();
  220. if (!statementMaps)
  221. {
  222. statementMaps = RecyclerNew(recycler, StatementMapList, recycler);
  223. this->SetStatementMaps(statementMaps);
  224. }
  225. statementMaps->Add(pStatementMap);
  226. }
  227. void
  228. FunctionBody::RecordStatementMap(SmallSpanSequenceIter &iter, StatementData * data)
  229. {
  230. Assert(!this->GetStatementMaps());
  231. if (!this->m_sourceInfo.pSpanSequence)
  232. {
  233. this->m_sourceInfo.pSpanSequence = HeapNew(SmallSpanSequence);
  234. }
  235. this->m_sourceInfo.pSpanSequence->RecordARange(iter, data);
  236. }
  237. void
  238. FunctionBody::RecordStatementAdjustment(uint offset, StatementAdjustmentType adjType)
  239. {
  240. this->EnsureAuxStatementData();
  241. Recycler* recycler = this->m_scriptContext->GetRecycler();
  242. if (this->GetStatementAdjustmentRecords() == nullptr)
  243. {
  244. m_sourceInfo.m_auxStatementData->m_statementAdjustmentRecords = RecyclerNew(recycler, StatementAdjustmentRecordList, recycler);
  245. }
  246. StatementAdjustmentRecord record(adjType, offset);
  247. this->GetStatementAdjustmentRecords()->Add(record); // Will copy stack value and put the copy into the container.
  248. }
  249. BOOL
  250. FunctionBody::GetBranchOffsetWithin(uint start, uint end, StatementAdjustmentRecord* record)
  251. {
  252. Assert(start < end);
  253. if (!this->GetStatementAdjustmentRecords())
  254. {
  255. // No Offset
  256. return FALSE;
  257. }
  258. int count = this->GetStatementAdjustmentRecords()->Count();
  259. for (int i = 0; i < count; i++)
  260. {
  261. StatementAdjustmentRecord item = this->GetStatementAdjustmentRecords()->Item(i);
  262. if (item.GetByteCodeOffset() > start && item.GetByteCodeOffset() < end)
  263. {
  264. *record = item;
  265. return TRUE;
  266. }
  267. }
  268. // No offset found in the range.
  269. return FALSE;
  270. }
  271. ScriptContext* EntryPointInfo::GetScriptContext()
  272. {
  273. Assert(!IsCleanedUp());
  274. return this->library->GetScriptContext();
  275. }
  276. #if DBG_DUMP | defined(VTUNE_PROFILING)
  277. void
  278. EntryPointInfo::RecordNativeMap(uint32 nativeOffset, uint32 statementIndex)
  279. {
  280. int count = nativeOffsetMaps.Count();
  281. if (count)
  282. {
  283. NativeOffsetMap* previous = &nativeOffsetMaps.Item(count-1);
  284. // Check if the range is still not finished.
  285. if (previous->nativeOffsetSpan.begin == previous->nativeOffsetSpan.end)
  286. {
  287. if (previous->statementIndex == statementIndex)
  288. {
  289. // If the statement index is the same, we can continue with the previous range
  290. return;
  291. }
  292. // If the range is empty, replace the previous range.
  293. if ((uint32)previous->nativeOffsetSpan.begin == nativeOffset)
  294. {
  295. if (statementIndex == Js::Constants::NoStatementIndex)
  296. {
  297. nativeOffsetMaps.RemoveAtEnd();
  298. }
  299. else
  300. {
  301. previous->statementIndex = statementIndex;
  302. }
  303. return;
  304. }
  305. // Close the previous range
  306. previous->nativeOffsetSpan.end = nativeOffset;
  307. }
  308. }
  309. if (statementIndex == Js::Constants::NoStatementIndex)
  310. {
  311. // We do not explicitly record the offsets that do not map to user code.
  312. return;
  313. }
  314. NativeOffsetMap map;
  315. map.statementIndex = statementIndex;
  316. map.nativeOffsetSpan.begin = nativeOffset;
  317. map.nativeOffsetSpan.end = nativeOffset;
  318. nativeOffsetMaps.Add(map);
  319. }
  320. #endif
  321. void
  322. FunctionBody::CopySourceInfo(ParseableFunctionInfo* originalFunctionInfo)
  323. {
  324. this->FinishSourceInfo();
  325. }
  326. // When sourceInfo is complete, register this functionBody to utf8SourceInfo. This ensures we never
  327. // put incomplete functionBody into utf8SourceInfo map. (Previously we do it in FunctionBody constructor.
  328. // If an error occurs thereafter before SetSourceInfo, e.g. OOM, we'll have an incomplete functionBody
  329. // in utf8SourceInfo map whose source range is unknown and can't be reparsed.)
  330. void FunctionBody::FinishSourceInfo()
  331. {
  332. this->GetUtf8SourceInfo()->SetFunctionBody(this);
  333. }
  334. RegSlot FunctionBody::GetFrameDisplayRegister() const
  335. {
  336. return this->m_sourceInfo.frameDisplayRegister;
  337. }
  338. void FunctionBody::SetFrameDisplayRegister(RegSlot frameDisplayRegister)
  339. {
  340. this->m_sourceInfo.frameDisplayRegister = frameDisplayRegister;
  341. }
  342. RegSlot FunctionBody::GetObjectRegister() const
  343. {
  344. return this->m_sourceInfo.objectRegister;
  345. }
  346. void FunctionBody::SetObjectRegister(RegSlot objectRegister)
  347. {
  348. this->m_sourceInfo.objectRegister = objectRegister;
  349. }
  350. ScopeObjectChain *FunctionBody::GetScopeObjectChain() const
  351. {
  352. return this->m_sourceInfo.pScopeObjectChain;
  353. }
  354. void FunctionBody::SetScopeObjectChain(ScopeObjectChain *pScopeObjectChain)
  355. {
  356. this->m_sourceInfo.pScopeObjectChain = pScopeObjectChain;
  357. }
  358. ByteBlock *FunctionBody::GetProbeBackingBlock()
  359. {
  360. return this->m_sourceInfo.m_probeBackingBlock;
  361. }
  362. void FunctionBody::SetProbeBackingBlock(ByteBlock* probeBackingBlock)
  363. {
  364. this->m_sourceInfo.m_probeBackingBlock = probeBackingBlock;
  365. }
  366. FunctionBody * FunctionBody::NewFromRecycler(ScriptContext * scriptContext, const char16 * displayName, uint displayNameLength, uint displayShortNameOffset, uint nestedCount,
  367. Utf8SourceInfo* sourceInfo, uint uScriptId, Js::LocalFunctionId functionId, Js::PropertyRecordList* boundPropertyRecords, FunctionInfo::Attributes attributes, FunctionBodyFlags flags
  368. #ifdef PERF_COUNTERS
  369. , bool isDeserializedFunction
  370. #endif
  371. )
  372. {
  373. return FunctionBody::NewFromRecycler(scriptContext, displayName, displayNameLength, displayShortNameOffset, nestedCount, sourceInfo,
  374. scriptContext->GetThreadContext()->NewFunctionNumber(), uScriptId, functionId, boundPropertyRecords, attributes, flags
  375. #ifdef PERF_COUNTERS
  376. , isDeserializedFunction
  377. #endif
  378. );
  379. }
  380. FunctionBody * FunctionBody::NewFromRecycler(ScriptContext * scriptContext, const char16 * displayName, uint displayNameLength, uint displayShortNameOffset, uint nestedCount,
  381. Utf8SourceInfo* sourceInfo, uint uFunctionNumber, uint uScriptId, Js::LocalFunctionId functionId, Js::PropertyRecordList* boundPropertyRecords, FunctionInfo::Attributes attributes, FunctionBodyFlags flags
  382. #ifdef PERF_COUNTERS
  383. , bool isDeserializedFunction
  384. #endif
  385. )
  386. {
  387. #ifdef PERF_COUNTERS
  388. return RecyclerNewWithBarrierFinalized(scriptContext->GetRecycler(), FunctionBody, scriptContext, displayName, displayNameLength, displayShortNameOffset, nestedCount, sourceInfo, uFunctionNumber, uScriptId, functionId, boundPropertyRecords, attributes, flags, isDeserializedFunction);
  389. #else
  390. return RecyclerNewWithBarrierFinalized(scriptContext->GetRecycler(), FunctionBody, scriptContext, displayName, displayNameLength, displayShortNameOffset, nestedCount, sourceInfo, uFunctionNumber, uScriptId, functionId, boundPropertyRecords, attributes, flags);
  391. #endif
  392. }
  393. FunctionBody *
  394. FunctionBody::NewFromParseableFunctionInfo(ParseableFunctionInfo * parseableFunctionInfo, PropertyRecordList * boundPropertyRecords)
  395. {
  396. ScriptContext * scriptContext = parseableFunctionInfo->GetScriptContext();
  397. uint nestedCount = parseableFunctionInfo->GetNestedCount();
  398. FunctionBody * functionBody = RecyclerNewWithBarrierFinalized(scriptContext->GetRecycler(),
  399. FunctionBody,
  400. parseableFunctionInfo);
  401. if (!functionBody->GetBoundPropertyRecords())
  402. {
  403. functionBody->SetBoundPropertyRecords(boundPropertyRecords);
  404. }
  405. // Initialize nested function array, update back pointers
  406. for (uint i = 0; i < nestedCount; i++)
  407. {
  408. FunctionInfo * nestedInfo = parseableFunctionInfo->GetNestedFunc(i);
  409. functionBody->SetNestedFunc(nestedInfo, i, 0);
  410. }
  411. return functionBody;
  412. }
  413. FunctionBody::FunctionBody(ScriptContext* scriptContext, const char16* displayName, uint displayNameLength, uint displayShortNameOffset, uint nestedCount,
  414. Utf8SourceInfo* utf8SourceInfo, uint uFunctionNumber, uint uScriptId,
  415. Js::LocalFunctionId functionId, Js::PropertyRecordList* boundPropertyRecords, FunctionInfo::Attributes attributes, FunctionBodyFlags flags
  416. #ifdef PERF_COUNTERS
  417. , bool isDeserializedFunction
  418. #endif
  419. ) :
  420. ParseableFunctionInfo(scriptContext->CurrentThunk, nestedCount, functionId, utf8SourceInfo, scriptContext, uFunctionNumber, displayName, displayNameLength, displayShortNameOffset, attributes, boundPropertyRecords, flags),
  421. counters(this),
  422. m_uScriptId(uScriptId),
  423. cleanedUp(false),
  424. sourceInfoCleanedUp(false),
  425. profiledLdElemCount(0),
  426. profiledStElemCount(0),
  427. profiledCallSiteCount(0),
  428. profiledArrayCallSiteCount(0),
  429. profiledDivOrRemCount(0),
  430. profiledSwitchCount(0),
  431. profiledReturnTypeCount(0),
  432. profiledSlotCount(0),
  433. m_isFuncRegistered(false),
  434. m_isFuncRegisteredToDiag(false),
  435. m_hasBailoutInstrInJittedCode(false),
  436. m_depth(0),
  437. inlineDepth(0),
  438. m_pendingLoopHeaderRelease(false),
  439. hasCachedScopePropIds(false),
  440. m_argUsedForBranch(0),
  441. m_envDepth((uint16)-1),
  442. loopInterpreterLimit(CONFIG_FLAG(LoopInterpretCount)),
  443. savedPolymorphicCacheState(0),
  444. debuggerScopeIndex(0),
  445. m_hasFinally(false),
  446. #if ENABLE_PROFILE_INFO
  447. dynamicProfileInfo(nullptr),
  448. #endif
  449. savedInlinerVersion(0),
  450. #if ENABLE_NATIVE_CODEGEN
  451. savedImplicitCallsFlags(ImplicitCall_HasNoInfo),
  452. #endif
  453. hasExecutionDynamicProfileInfo(false),
  454. m_hasAllNonLocalReferenced(false),
  455. m_hasSetIsObject(false),
  456. m_hasFunExprNameReference(false),
  457. m_CallsEval(false),
  458. m_ChildCallsEval(false),
  459. m_hasReferenceableBuiltInArguments(false),
  460. m_isParamAndBodyScopeMerged(true),
  461. m_firstFunctionObject(true),
  462. m_inlineCachesOnFunctionObject(false),
  463. m_hasDoneAllNonLocalReferenced(false),
  464. m_hasFunctionCompiledSent(false),
  465. byteCodeCache(nullptr),
  466. m_hasLocalClosureRegister(false),
  467. m_hasParamClosureRegister(false),
  468. m_hasLocalFrameDisplayRegister(false),
  469. m_hasEnvRegister(false),
  470. m_hasThisRegisterForEventHandler(false),
  471. m_hasFirstInnerScopeRegister(false),
  472. m_hasFuncExprScopeRegister(false),
  473. m_hasFirstTmpRegister(false),
  474. m_hasActiveReference(false),
  475. m_tag31(true),
  476. m_tag32(true),
  477. m_tag33(true),
  478. m_nativeEntryPointUsed(false),
  479. hasDoneLoopBodyCodeGen(false),
  480. bailOnMisingProfileCount(0),
  481. bailOnMisingProfileRejitCount(0),
  482. byteCodeBlock(nullptr),
  483. entryPoints(nullptr),
  484. m_constTable(nullptr),
  485. inlineCaches(nullptr),
  486. cacheIdToPropertyIdMap(nullptr),
  487. wasCalledFromLoop(false),
  488. hasScopeObject(false),
  489. hasNestedLoop(false),
  490. recentlyBailedOutOfJittedLoopBody(false),
  491. m_isAsmJsScheduledForFullJIT(false),
  492. m_asmJsTotalLoopCount(0)
  493. //
  494. // Even if the function does not require any locals, we must always have "R0" to propagate
  495. // a return value. By enabling this here, we avoid unnecessary conditionals during execution.
  496. //
  497. #ifdef IR_VIEWER
  498. ,m_isIRDumpEnabled(false)
  499. ,m_irDumpBaseObject(nullptr)
  500. #endif /* IR_VIEWER */
  501. , m_isFromNativeCodeModule(false)
  502. , hasHotLoop(false)
  503. , m_isPartialDeserializedFunction(false)
  504. #if DBG
  505. , m_isSerialized(false)
  506. #endif
  507. #ifdef PERF_COUNTERS
  508. , m_isDeserializedFunction(isDeserializedFunction)
  509. #endif
  510. #if DBG
  511. , m_DEBUG_executionCount(0)
  512. , m_nativeEntryPointIsInterpreterThunk(false)
  513. , m_canDoStackNestedFunc(false)
  514. , m_inlineCacheTypes(nullptr)
  515. , m_iProfileSession(-1)
  516. #endif
  517. #if ENABLE_DEBUG_CONFIG_OPTIONS
  518. , regAllocLoadCount(0)
  519. , regAllocStoreCount(0)
  520. , callCountStats(0)
  521. #endif
  522. {
  523. SetCountField(CounterFields::ConstantCount, 1);
  524. this->SetDefaultFunctionEntryPointInfo((FunctionEntryPointInfo*) this->GetDefaultEntryPointInfo(), DefaultEntryThunk);
  525. this->m_hasBeenParsed = true;
  526. #ifdef PERF_COUNTERS
  527. if (isDeserializedFunction)
  528. {
  529. PERF_COUNTER_INC(Code, DeserializedFunctionBody);
  530. }
  531. #endif
  532. Assert(!utf8SourceInfo || m_uScriptId == utf8SourceInfo->GetSrcInfo()->sourceContextInfo->sourceContextId);
  533. // Sync entryPoints changes to etw rundown lock
  534. CriticalSection* syncObj = scriptContext->GetThreadContext()->GetFunctionBodyLock();
  535. this->entryPoints = RecyclerNew(this->m_scriptContext->GetRecycler(), FunctionEntryPointList, this->m_scriptContext->GetRecycler(), syncObj);
  536. this->AddEntryPointToEntryPointList(this->GetDefaultFunctionEntryPointInfo());
  537. Assert(this->GetDefaultEntryPointInfo()->jsMethod != nullptr);
  538. InitDisableInlineApply();
  539. InitDisableInlineSpread();
  540. }
  541. FunctionBody::FunctionBody(ParseableFunctionInfo * proxy) :
  542. ParseableFunctionInfo(proxy),
  543. counters(this),
  544. m_uScriptId(proxy->GetUtf8SourceInfo()->GetSrcInfo()->sourceContextInfo->sourceContextId),
  545. cleanedUp(false),
  546. sourceInfoCleanedUp(false),
  547. profiledLdElemCount(0),
  548. profiledStElemCount(0),
  549. profiledCallSiteCount(0),
  550. profiledArrayCallSiteCount(0),
  551. profiledDivOrRemCount(0),
  552. profiledSwitchCount(0),
  553. profiledReturnTypeCount(0),
  554. profiledSlotCount(0),
  555. m_isFuncRegistered(false),
  556. m_isFuncRegisteredToDiag(false),
  557. m_hasBailoutInstrInJittedCode(false),
  558. m_depth(0),
  559. inlineDepth(0),
  560. m_pendingLoopHeaderRelease(false),
  561. hasCachedScopePropIds(false),
  562. m_argUsedForBranch(0),
  563. m_envDepth((uint16)-1),
  564. loopInterpreterLimit(CONFIG_FLAG(LoopInterpretCount)),
  565. savedPolymorphicCacheState(0),
  566. debuggerScopeIndex(0),
  567. m_hasFinally(false),
  568. #if ENABLE_PROFILE_INFO
  569. dynamicProfileInfo(nullptr),
  570. #endif
  571. savedInlinerVersion(0),
  572. #if ENABLE_NATIVE_CODEGEN
  573. savedImplicitCallsFlags(ImplicitCall_HasNoInfo),
  574. #endif
  575. hasExecutionDynamicProfileInfo(false),
  576. m_hasAllNonLocalReferenced(false),
  577. m_hasSetIsObject(false),
  578. m_hasFunExprNameReference(false),
  579. m_CallsEval(false),
  580. m_ChildCallsEval(false),
  581. m_hasReferenceableBuiltInArguments(false),
  582. m_isParamAndBodyScopeMerged(true),
  583. m_firstFunctionObject(true),
  584. m_inlineCachesOnFunctionObject(false),
  585. m_hasDoneAllNonLocalReferenced(false),
  586. m_hasFunctionCompiledSent(false),
  587. byteCodeCache(nullptr),
  588. m_hasLocalClosureRegister(false),
  589. m_hasParamClosureRegister(false),
  590. m_hasLocalFrameDisplayRegister(false),
  591. m_hasEnvRegister(false),
  592. m_hasThisRegisterForEventHandler(false),
  593. m_hasFirstInnerScopeRegister(false),
  594. m_hasFuncExprScopeRegister(false),
  595. m_hasFirstTmpRegister(false),
  596. m_hasActiveReference(false),
  597. m_tag31(true),
  598. m_tag32(true),
  599. m_tag33(true),
  600. m_nativeEntryPointUsed(false),
  601. hasDoneLoopBodyCodeGen(false),
  602. bailOnMisingProfileCount(0),
  603. bailOnMisingProfileRejitCount(0),
  604. byteCodeBlock(nullptr),
  605. entryPoints(nullptr),
  606. m_constTable(nullptr),
  607. inlineCaches(nullptr),
  608. cacheIdToPropertyIdMap(nullptr),
  609. wasCalledFromLoop(false),
  610. hasScopeObject(false),
  611. hasNestedLoop(false),
  612. recentlyBailedOutOfJittedLoopBody(false),
  613. m_isAsmJsScheduledForFullJIT(false),
  614. m_asmJsTotalLoopCount(0)
  615. //
  616. // Even if the function does not require any locals, we must always have "R0" to propagate
  617. // a return value. By enabling this here, we avoid unnecessary conditionals during execution.
  618. //
  619. #ifdef IR_VIEWER
  620. ,m_isIRDumpEnabled(false)
  621. ,m_irDumpBaseObject(nullptr)
  622. #endif /* IR_VIEWER */
  623. , m_isFromNativeCodeModule(false)
  624. , hasHotLoop(false)
  625. , m_isPartialDeserializedFunction(false)
  626. #if DBG
  627. , m_isSerialized(false)
  628. #endif
  629. #ifdef PERF_COUNTERS
  630. , m_isDeserializedFunction(false)
  631. #endif
  632. #if DBG
  633. , m_DEBUG_executionCount(0)
  634. , m_nativeEntryPointIsInterpreterThunk(false)
  635. , m_canDoStackNestedFunc(false)
  636. , m_inlineCacheTypes(nullptr)
  637. , m_iProfileSession(-1)
  638. #endif
  639. #if ENABLE_DEBUG_CONFIG_OPTIONS
  640. , regAllocLoadCount(0)
  641. , regAllocStoreCount(0)
  642. , callCountStats(0)
  643. #endif
  644. {
  645. ScriptContext * scriptContext = proxy->GetScriptContext();
  646. SetCountField(CounterFields::ConstantCount, 1);
  647. proxy->UpdateFunctionBodyImpl(this);
  648. this->SetDeferredStubs(proxy->GetDeferredStubs());
  649. void* validationCookie = nullptr;
  650. #if ENABLE_NATIVE_CODEGEN
  651. validationCookie = (void*)scriptContext->GetNativeCodeGenerator();
  652. #endif
  653. this->m_defaultEntryPointInfo = RecyclerNewFinalized(scriptContext->GetRecycler(),
  654. FunctionEntryPointInfo, this, scriptContext->CurrentThunk, scriptContext->GetThreadContext(), validationCookie);
  655. this->SetDefaultFunctionEntryPointInfo((FunctionEntryPointInfo*) this->GetDefaultEntryPointInfo(), DefaultEntryThunk);
  656. this->m_hasBeenParsed = true;
  657. Assert(!proxy->GetUtf8SourceInfo() || m_uScriptId == proxy->GetUtf8SourceInfo()->GetSrcInfo()->sourceContextInfo->sourceContextId);
  658. // Sync entryPoints changes to etw rundown lock
  659. CriticalSection* syncObj = scriptContext->GetThreadContext()->GetFunctionBodyLock();
  660. this->entryPoints = RecyclerNew(scriptContext->GetRecycler(), FunctionEntryPointList, scriptContext->GetRecycler(), syncObj);
  661. this->AddEntryPointToEntryPointList(this->GetDefaultFunctionEntryPointInfo());
  662. Assert(this->GetDefaultEntryPointInfo()->jsMethod != nullptr);
  663. InitDisableInlineApply();
  664. InitDisableInlineSpread();
  665. }
  666. bool FunctionBody::InterpretedSinceCallCountCollection() const
  667. {
  668. return executionState.InterpretedSinceCallCountCollection();
  669. }
  670. void FunctionBody::CollectInterpretedCounts()
  671. {
  672. executionState.CollectInterpretedCounts();
  673. }
  674. void FunctionBody::IncrInactiveCount(uint increment)
  675. {
  676. this->inactiveCount = UInt32Math::Add(this->inactiveCount, increment);
  677. }
  678. bool FunctionBody::IsActiveFunction(ActiveFunctionSet * pActiveFuncs) const
  679. {
  680. return !!pActiveFuncs->Test(this->GetFunctionNumber());
  681. }
  682. bool FunctionBody::TestAndUpdateActiveFunctions(ActiveFunctionSet * pActiveFuncs) const
  683. {
  684. return !!pActiveFuncs->TestAndSet(this->GetFunctionNumber());
  685. }
  686. void FunctionBody::UpdateActiveFunctionsForOneDataSet(ActiveFunctionSet *pActiveFuncs, FunctionCodeGenRuntimeData *parentData, Field(FunctionCodeGenRuntimeData*)* dataSet, uint count) const
  687. {
  688. FunctionCodeGenRuntimeData *inlineeData;
  689. for (uint i = 0; i < count; i++)
  690. {
  691. for (inlineeData = dataSet[i]; inlineeData; inlineeData = inlineeData->GetNext())
  692. {
  693. // inlineeData == parentData indicates a cycle in the structure. We've already processed parentData, so don't descend.
  694. if (inlineeData != parentData)
  695. {
  696. inlineeData->GetFunctionBody()->UpdateActiveFunctionSet(pActiveFuncs, inlineeData);
  697. }
  698. }
  699. }
  700. }
  701. void FunctionBody::UpdateActiveFunctionSet(ActiveFunctionSet *pActiveFuncs, FunctionCodeGenRuntimeData *callSiteData) const
  702. {
  703. // Always walk the inlinee and ldFldInlinee data (if we have them), as they are different at each call site.
  704. if (callSiteData)
  705. {
  706. if (callSiteData->GetInlinees())
  707. {
  708. this->UpdateActiveFunctionsForOneDataSet(pActiveFuncs, callSiteData, callSiteData->GetInlinees(), this->GetProfiledCallSiteCount());
  709. }
  710. if (callSiteData->GetLdFldInlinees())
  711. {
  712. this->UpdateActiveFunctionsForOneDataSet(pActiveFuncs, callSiteData, callSiteData->GetLdFldInlinees(), this->GetInlineCacheCount());
  713. }
  714. }
  715. // Now walk the top-level data, but only do it once, since it's always the same.
  716. if (this->TestAndUpdateActiveFunctions(pActiveFuncs))
  717. {
  718. return;
  719. }
  720. {
  721. Field(FunctionCodeGenRuntimeData*)* data = this->GetCodeGenRuntimeData();
  722. if (data != nullptr)
  723. {
  724. this->UpdateActiveFunctionsForOneDataSet(pActiveFuncs, nullptr, data, this->GetProfiledCallSiteCount());
  725. }
  726. }
  727. {
  728. Field(FunctionCodeGenRuntimeData*)* data = this->GetCodeGenGetSetRuntimeData();
  729. if (data != nullptr)
  730. {
  731. this->UpdateActiveFunctionsForOneDataSet(pActiveFuncs, nullptr, data, this->GetInlineCacheCount());
  732. }
  733. }
  734. }
  735. bool FunctionBody::DoRedeferFunction(uint inactiveThreshold) const
  736. {
  737. if (!(this->GetFunctionInfo()->GetFunctionProxy() == this &&
  738. this->CanBeDeferred() &&
  739. this->GetByteCode() &&
  740. this->GetCanDefer()))
  741. {
  742. return false;
  743. }
  744. if (!PHASE_FORCE(Js::RedeferralPhase, this) && !PHASE_STRESS(Js::RedeferralPhase, this))
  745. {
  746. uint compileCount = this->GetCompileCount();
  747. if (compileCount >= (uint)CONFIG_FLAG(RedeferralCap))
  748. {
  749. return false;
  750. }
  751. // Redeferral threshold is k^x, where x is the number of previous compiles.
  752. bool overflow = false;
  753. uint currentThreshold = inactiveThreshold;
  754. if (compileCount > 1)
  755. {
  756. currentThreshold = JavascriptNumber::DirectPowIntInt(&overflow, inactiveThreshold, compileCount);
  757. }
  758. if (overflow)
  759. {
  760. currentThreshold = 0xFFFFFFFF;
  761. }
  762. if (this->GetInactiveCount() < currentThreshold)
  763. {
  764. return false;
  765. }
  766. }
  767. // Make sure the function won't be jitted
  768. bool isJitModeFunction = !this->IsInterpreterExecutionMode();
  769. bool isJitCandidate = false;
  770. isJitCandidate = MapEntryPointsUntil([=](int index, FunctionEntryPointInfo *entryPointInfo)
  771. {
  772. if ((entryPointInfo->IsCodeGenPending() && isJitModeFunction) || entryPointInfo->IsCodeGenQueued() || entryPointInfo->IsCodeGenRecorded() || (entryPointInfo->IsCodeGenDone() && !entryPointInfo->nativeEntryPointProcessed))
  773. {
  774. return true;
  775. }
  776. return false;
  777. });
  778. if (!isJitCandidate)
  779. {
  780. // Now check loop body entry points
  781. isJitCandidate = MapLoopHeadersUntil([=](uint loopNumber, LoopHeader* header)
  782. {
  783. return header->MapEntryPointsUntil([&](int index, LoopEntryPointInfo* entryPointInfo)
  784. {
  785. if (entryPointInfo->IsCodeGenPending() || entryPointInfo->IsCodeGenQueued() || entryPointInfo->IsCodeGenRecorded() || (entryPointInfo->IsCodeGenDone() && !entryPointInfo->nativeEntryPointProcessed))
  786. {
  787. return true;
  788. }
  789. return false;
  790. });
  791. });
  792. }
  793. return !isJitCandidate;
  794. }
  795. void FunctionBody::RedeferFunction()
  796. {
  797. Assert(this->CanBeDeferred());
  798. #if DBG
  799. if (PHASE_STATS(RedeferralPhase, this))
  800. {
  801. ThreadContext * threadContext = this->GetScriptContext()->GetThreadContext();
  802. threadContext->redeferredFunctions++;
  803. threadContext->recoveredBytes += sizeof(*this) + this->GetInlineCacheCount() * sizeof(InlineCache);
  804. if (this->byteCodeBlock)
  805. {
  806. threadContext->recoveredBytes += this->byteCodeBlock->GetLength();
  807. if (this->GetAuxiliaryData())
  808. {
  809. threadContext->recoveredBytes += this->GetAuxiliaryData()->GetLength();
  810. }
  811. }
  812. this->MapEntryPoints([&](int index, FunctionEntryPointInfo * info) {
  813. threadContext->recoveredBytes += sizeof(info);
  814. });
  815. // TODO: Get size of polymorphic caches, jitted code, etc.
  816. }
  817. // We can't get here if the function is being jitted. Jitting was either completed or not begun.
  818. this->UnlockCounters();
  819. #endif
  820. PHASE_PRINT_TRACE(Js::RedeferralPhase, this, _u("Redeferring function %d.%d: %s\n"),
  821. GetSourceContextId(), GetLocalFunctionId(),
  822. GetDisplayName() ? GetDisplayName() : _u("Anonymous function)"));
  823. ParseableFunctionInfo * parseableFunctionInfo =
  824. Js::ParseableFunctionInfo::NewDeferredFunctionFromFunctionBody(this);
  825. FunctionInfo * functionInfo = this->GetFunctionInfo();
  826. this->RedeferFunctionObjectTypes();
  827. this->Cleanup(false);
  828. if (GetIsFuncRegistered())
  829. {
  830. this->GetUtf8SourceInfo()->RemoveFunctionBody(this);
  831. }
  832. // New allocation is done at this point, so update existing structures
  833. // Adjust functionInfo attributes, point to new proxy
  834. functionInfo->SetAttributes((FunctionInfo::Attributes)(functionInfo->GetAttributes() | FunctionInfo::Attributes::DeferredParse));
  835. functionInfo->SetFunctionProxy(parseableFunctionInfo);
  836. functionInfo->SetOriginalEntryPoint(DefaultEntryThunk);
  837. }
  838. void FunctionBody::RedeferFunctionObjectTypes()
  839. {
  840. this->MapFunctionObjectTypes([&](ScriptFunctionType* functionType)
  841. {
  842. Assert(functionType->GetTypeId() == TypeIds_Function);
  843. if (!CrossSite::IsThunk(functionType->GetEntryPoint()))
  844. {
  845. functionType->SetEntryPoint(GetScriptContext()->DeferredParsingThunk);
  846. }
  847. if (!CrossSite::IsThunk(functionType->GetEntryPointInfo()->jsMethod))
  848. {
  849. functionType->GetEntryPointInfo()->jsMethod = GetScriptContext()->DeferredParsingThunk;
  850. }
  851. });
  852. }
  853. void FunctionBody::SetDefaultFunctionEntryPointInfo(FunctionEntryPointInfo* entryPointInfo, const JavascriptMethod originalEntryPoint)
  854. {
  855. Assert(entryPointInfo);
  856. // Need to set twice since ProxyEntryPointInfo cast points to an interior pointer
  857. this->m_defaultEntryPointInfo = (ProxyEntryPointInfo*) entryPointInfo;
  858. this->defaultFunctionEntryPointInfo = entryPointInfo;
  859. SetOriginalEntryPoint(originalEntryPoint);
  860. }
  861. Var
  862. FunctionBody::GetFormalsPropIdArrayOrNullObj()
  863. {
  864. Var formalsPropIdArray = this->GetAuxPtrWithLock(AuxPointerType::FormalsPropIdArray);
  865. if (formalsPropIdArray == nullptr)
  866. {
  867. return GetScriptContext()->GetLibrary()->GetNull();
  868. }
  869. return formalsPropIdArray;
  870. }
  871. PropertyIdArray*
  872. FunctionBody::GetFormalsPropIdArray(bool checkForNull)
  873. {
  874. if (checkForNull)
  875. {
  876. Assert(this->GetAuxPtrWithLock(AuxPointerType::FormalsPropIdArray));
  877. }
  878. return static_cast<PropertyIdArray*>(this->GetAuxPtrWithLock(AuxPointerType::FormalsPropIdArray));
  879. }
  880. void
  881. FunctionBody::SetFormalsPropIdArray(PropertyIdArray * propIdArray)
  882. {
  883. AssertMsg(propIdArray == nullptr || this->GetAuxPtrWithLock(AuxPointerType::FormalsPropIdArray) == nullptr, "Already set?");
  884. this->SetAuxPtr(AuxPointerType::FormalsPropIdArray, propIdArray);
  885. }
  886. ByteBlock*
  887. FunctionBody::GetByteCode() const
  888. {
  889. return this->byteCodeBlock;
  890. }
  891. // Returns original bytecode without probes (such as BPs).
  892. ByteBlock*
  893. FunctionBody::GetOriginalByteCode()
  894. {
  895. if (m_sourceInfo.m_probeBackingBlock)
  896. {
  897. return m_sourceInfo.m_probeBackingBlock;
  898. }
  899. else
  900. {
  901. return this->GetByteCode();
  902. }
  903. }
  904. const char16* ParseableFunctionInfo::GetExternalDisplayName() const
  905. {
  906. return GetExternalDisplayName(this);
  907. }
  908. RegSlot
  909. FunctionBody::GetLocalsCount()
  910. {
  911. return GetConstantCount() + GetVarCount();
  912. }
  913. RegSlot
  914. FunctionBody::GetVarCount()
  915. {
  916. return this->GetCountField(CounterFields::VarCount);
  917. }
  918. // Returns the number of non-temp local vars.
  919. uint32
  920. FunctionBody::GetNonTempLocalVarCount()
  921. {
  922. Assert(this->GetEndNonTempLocalIndex() >= this->GetFirstNonTempLocalIndex());
  923. return this->GetEndNonTempLocalIndex() - this->GetFirstNonTempLocalIndex();
  924. }
  925. uint32
  926. FunctionBody::GetFirstNonTempLocalIndex()
  927. {
  928. // First local var starts when the const vars end.
  929. return GetConstantCount();
  930. }
  931. uint32
  932. FunctionBody::GetEndNonTempLocalIndex()
  933. {
  934. // It will give the index on which current non temp locals ends, which is a first temp reg.
  935. RegSlot firstTmpReg = GetFirstTmpRegister();
  936. return firstTmpReg != Constants::NoRegister ? firstTmpReg : GetLocalsCount();
  937. }
  938. bool
  939. FunctionBody::IsNonTempLocalVar(uint32 varIndex)
  940. {
  941. return GetFirstNonTempLocalIndex() <= varIndex && varIndex < GetEndNonTempLocalIndex();
  942. }
  943. bool
  944. FunctionBody::GetSlotOffset(RegSlot slotId, int32 * slotOffset, bool allowTemp)
  945. {
  946. if (IsNonTempLocalVar(slotId) || allowTemp)
  947. {
  948. *slotOffset = (slotId - GetFirstNonTempLocalIndex()) * DIAGLOCALSLOTSIZE;
  949. return true;
  950. }
  951. return false;
  952. }
  953. void
  954. FunctionBody::CheckAndSetConstantCount(RegSlot cNewConstants) // New register count
  955. {
  956. CheckNotExecuting();
  957. AssertMsg(GetConstantCount() <= cNewConstants, "Cannot shrink register usage");
  958. this->SetConstantCount(cNewConstants);
  959. }
  960. void
  961. FunctionBody::SetConstantCount(RegSlot cNewConstants) // New register count
  962. {
  963. this->SetCountField(CounterFields::ConstantCount, cNewConstants);
  964. }
  965. void
  966. FunctionBody::CheckAndSetVarCount(RegSlot cNewVars)
  967. {
  968. CheckNotExecuting();
  969. AssertMsg(this->GetVarCount() <= cNewVars, "Cannot shrink register usage");
  970. this->SetVarCount(cNewVars);
  971. }
  972. void
  973. FunctionBody::SetVarCount(RegSlot cNewVars) // New register count
  974. {
  975. this->SetCountField(FunctionBody::CounterFields::VarCount, cNewVars);
  976. }
  977. RegSlot
  978. FunctionBody::GetYieldRegister()
  979. {
  980. return GetEndNonTempLocalIndex() - 1;
  981. }
  982. RegSlot
  983. FunctionBody::GetFirstTmpReg()
  984. {
  985. AssertMsg(GetFirstTmpRegister() != Constants::NoRegister, "First temp hasn't been set yet");
  986. return GetFirstTmpRegister();
  987. }
  988. void
  989. FunctionBody::SetFirstTmpReg(
  990. RegSlot firstTmpReg)
  991. {
  992. CheckNotExecuting();
  993. AssertMsg(GetFirstTmpRegister() == Constants::NoRegister, "Should not be resetting the first temp");
  994. SetFirstTmpRegister(firstTmpReg);
  995. }
  996. RegSlot
  997. FunctionBody::GetTempCount()
  998. {
  999. return GetLocalsCount() - GetFirstTmpRegister();
  1000. }
  1001. void
  1002. FunctionBody::SetOutParamMaxDepth(RegSlot cOutParamsDepth)
  1003. {
  1004. #if _M_X64
  1005. const RegSlot minAsmJsOutParams = MinAsmJsOutParams();
  1006. if (GetIsAsmJsFunction() && cOutParamsDepth < minAsmJsOutParams)
  1007. {
  1008. cOutParamsDepth = minAsmJsOutParams;
  1009. }
  1010. #endif
  1011. SetCountField(CounterFields::OutParamMaxDepth, cOutParamsDepth);
  1012. }
  1013. void
  1014. FunctionBody::CheckAndSetOutParamMaxDepth(RegSlot cOutParamsDepth)
  1015. {
  1016. CheckNotExecuting();
  1017. SetOutParamMaxDepth(cOutParamsDepth);
  1018. }
  1019. RegSlot
  1020. FunctionBody::GetOutParamMaxDepth()
  1021. {
  1022. return GetCountField(CounterFields::OutParamMaxDepth);
  1023. }
  1024. ModuleID
  1025. FunctionBody::GetModuleID() const
  1026. {
  1027. return this->GetHostSrcInfo()->moduleID;
  1028. }
  1029. ///----------------------------------------------------------------------------
  1030. ///
  1031. /// FunctionBody::BeginExecution
  1032. ///
  1033. /// BeginExecution() is called by InterpreterStackFrame when a function begins execution.
  1034. /// - Once started execution, the function may not be modified, as it would
  1035. /// change the stack-frame layout:
  1036. /// - This is a debug-only check because of the runtime cost. At release time,
  1037. /// a stack-walk will be performed by GC to determine which functions are
  1038. /// executing.
  1039. ///
  1040. ///----------------------------------------------------------------------------
  1041. void
  1042. FunctionBody::BeginExecution()
  1043. {
  1044. #if DBG
  1045. m_DEBUG_executionCount++;
  1046. this->LockDownCounters();
  1047. #endif
  1048. // Don't allow loop headers to be released while the function is executing
  1049. ::InterlockedIncrement(&this->m_depth);
  1050. }
  1051. ///----------------------------------------------------------------------------
  1052. ///
  1053. /// FunctionBody::CheckEmpty
  1054. ///
  1055. /// CheckEmpty() validates that the given instance has not been given an
  1056. /// implementation yet.
  1057. ///
  1058. ///----------------------------------------------------------------------------
  1059. void
  1060. FunctionBody::CheckEmpty()
  1061. {
  1062. AssertMsg((this->byteCodeBlock == nullptr) && (this->GetAuxiliaryData() == nullptr) && (this->GetAuxiliaryContextData() == nullptr), "Function body may only be set once");
  1063. }
  1064. ///----------------------------------------------------------------------------
  1065. ///
  1066. /// FunctionBody::CheckNotExecuting
  1067. ///
  1068. /// CheckNotExecuting() checks that function is not currently executing when it
  1069. /// is being modified. See BeginExecution() for details.
  1070. ///
  1071. ///----------------------------------------------------------------------------
  1072. void
  1073. FunctionBody::CheckNotExecuting()
  1074. {
  1075. AssertMsg(m_DEBUG_executionCount == 0, "Function cannot be executing when modified");
  1076. }
  1077. ///----------------------------------------------------------------------------
  1078. ///
  1079. /// FunctionBody::EndExecution
  1080. ///
  1081. /// EndExecution() is called by InterpreterStackFrame when a function ends execution.
  1082. /// See BeginExecution() for details.
  1083. ///
  1084. ///----------------------------------------------------------------------------
  1085. void
  1086. FunctionBody::EndExecution()
  1087. {
  1088. #if DBG
  1089. AssertMsg(m_DEBUG_executionCount > 0, "Must have a previous execution to end");
  1090. m_DEBUG_executionCount--;
  1091. #endif
  1092. uint depth = ::InterlockedDecrement(&this->m_depth);
  1093. // If loop headers were determined to be no longer needed
  1094. // during the execution of the function, we release them now
  1095. if (depth == 0 && this->m_pendingLoopHeaderRelease)
  1096. {
  1097. this->m_pendingLoopHeaderRelease = false;
  1098. ReleaseLoopHeaders();
  1099. }
  1100. }
  1101. void FunctionBody::AddEntryPointToEntryPointList(FunctionEntryPointInfo* entryPointInfo)
  1102. {
  1103. ThreadContext::AutoDisableExpiration disableExpiration(this->m_scriptContext->GetThreadContext());
  1104. Recycler* recycler = this->m_scriptContext->GetRecycler();
  1105. entryPointInfo->entryPointIndex = this->entryPoints->Add(recycler->CreateWeakReferenceHandle(entryPointInfo));
  1106. }
  1107. #if DBG
  1108. BOOL FunctionBody::IsInterpreterThunk() const
  1109. {
  1110. bool isInterpreterThunk = this->GetOriginalEntryPoint_Unchecked() == DefaultEntryThunk;
  1111. #if DYNAMIC_INTERPRETER_THUNK
  1112. bool isStaticInterpreterThunk = this->GetOriginalEntryPoint_Unchecked() == InterpreterStackFrame::StaticInterpreterThunk;
  1113. isInterpreterThunk = isInterpreterThunk || isStaticInterpreterThunk || IsDynamicInterpreterThunk();
  1114. #endif
  1115. return isInterpreterThunk;
  1116. }
  1117. BOOL FunctionBody::IsDynamicInterpreterThunk() const
  1118. {
  1119. #if DYNAMIC_INTERPRETER_THUNK
  1120. return this->GetScriptContext()->IsDynamicInterpreterThunk(this->GetOriginalEntryPoint_Unchecked());
  1121. #else
  1122. return FALSE;
  1123. #endif
  1124. }
  1125. #endif
  1126. FunctionEntryPointInfo * FunctionBody::TryGetEntryPointInfo(int index) const
  1127. {
  1128. // If we've already freed the recyclable data, we're shutting down the script context so skip clean up
  1129. if (this->entryPoints == nullptr) return 0;
  1130. Assert(index < this->entryPoints->Count());
  1131. FunctionEntryPointInfo* entryPoint = this->entryPoints->Item(index)->Get();
  1132. return entryPoint;
  1133. }
  1134. FunctionEntryPointInfo * FunctionBody::GetEntryPointInfo(int index) const
  1135. {
  1136. FunctionEntryPointInfo* entryPoint = TryGetEntryPointInfo(index);
  1137. Assert(entryPoint);
  1138. return entryPoint;
  1139. }
  1140. uint32 FunctionBody::GetFrameHeight(EntryPointInfo* entryPointInfo) const
  1141. {
  1142. return entryPointInfo->frameHeight;
  1143. }
  1144. void FunctionBody::SetFrameHeight(EntryPointInfo* entryPointInfo, uint32 frameHeight)
  1145. {
  1146. entryPointInfo->frameHeight = frameHeight;
  1147. }
  1148. #if ENABLE_NATIVE_CODEGEN
  1149. void
  1150. FunctionBody::SetNativeThrowSpanSequence(SmallSpanSequence *seq, uint loopNum, LoopEntryPointInfo* entryPoint)
  1151. {
  1152. Assert(loopNum != LoopHeader::NoLoop);
  1153. LoopHeader *loopHeader = this->GetLoopHeaderWithLock(loopNum);
  1154. Assert(loopHeader);
  1155. Assert(entryPoint->loopHeader == loopHeader);
  1156. entryPoint->SetNativeThrowSpanSequence(seq);
  1157. }
  1158. void
  1159. FunctionBody::RecordNativeThrowMap(SmallSpanSequenceIter& iter, uint32 nativeOffset, uint32 statementIndex, EntryPointInfo* entryPoint, uint loopNum)
  1160. {
  1161. SmallSpanSequence *pSpanSequence;
  1162. pSpanSequence = entryPoint->GetNativeThrowSpanSequence();
  1163. if (!pSpanSequence)
  1164. {
  1165. if (statementIndex == -1)
  1166. {
  1167. return; // No need to initialize native throw map for non-user code
  1168. }
  1169. pSpanSequence = HeapNew(SmallSpanSequence);
  1170. if (loopNum == LoopHeader::NoLoop)
  1171. {
  1172. ((FunctionEntryPointInfo*) entryPoint)->SetNativeThrowSpanSequence(pSpanSequence);
  1173. }
  1174. else
  1175. {
  1176. this->SetNativeThrowSpanSequence(pSpanSequence, loopNum, (LoopEntryPointInfo*) entryPoint);
  1177. }
  1178. }
  1179. else if (iter.accumulatedSourceBegin == static_cast<int>(statementIndex))
  1180. {
  1181. return; // Compress adjacent spans which share the same statementIndex
  1182. }
  1183. StatementData data;
  1184. data.sourceBegin = static_cast<int>(statementIndex); // sourceBegin represents statementIndex here
  1185. data.bytecodeBegin = static_cast<int>(nativeOffset); // bytecodeBegin represents nativeOffset here
  1186. pSpanSequence->RecordARange(iter, &data);
  1187. }
  1188. #endif
  1189. bool
  1190. ParseableFunctionInfo::IsTrackedPropertyId(PropertyId pid)
  1191. {
  1192. Assert(this->GetBoundPropertyRecords() != nullptr);
  1193. PropertyRecordList* trackedProperties = this->GetBoundPropertyRecords();
  1194. const PropertyRecord* prop = nullptr;
  1195. if (trackedProperties->TryGetValue(pid, &prop))
  1196. {
  1197. Assert(prop != nullptr);
  1198. return true;
  1199. }
  1200. return this->m_scriptContext->IsTrackedPropertyId(pid);
  1201. }
  1202. PropertyId
  1203. ParseableFunctionInfo::GetOrAddPropertyIdTracked(JsUtil::CharacterBuffer<WCHAR> const& propName)
  1204. {
  1205. Assert(this->GetBoundPropertyRecords() != nullptr);
  1206. const Js::PropertyRecord* propRecord = nullptr;
  1207. this->m_scriptContext->GetOrAddPropertyRecord(propName, &propRecord);
  1208. PropertyId pid = propRecord->GetPropertyId();
  1209. this->GetBoundPropertyRecords()->Item(pid, propRecord);
  1210. return pid;
  1211. }
  1212. SmallSpanSequence::SmallSpanSequence()
  1213. : pStatementBuffer(nullptr),
  1214. pActualOffsetList(nullptr),
  1215. baseValue(0)
  1216. {
  1217. }
  1218. BOOL SmallSpanSequence::RecordARange(SmallSpanSequenceIter &iter, StatementData * data)
  1219. {
  1220. Assert(data);
  1221. if (!this->pStatementBuffer)
  1222. {
  1223. this->pStatementBuffer = JsUtil::GrowingUint32HeapArray::Create(4);
  1224. baseValue = data->sourceBegin;
  1225. Reset(iter);
  1226. }
  1227. SmallSpan span(0);
  1228. span.sourceBegin = GetDiff(data->sourceBegin, iter.accumulatedSourceBegin);
  1229. span.bytecodeBegin = GetDiff(data->bytecodeBegin, iter.accumulatedBytecodeBegin);
  1230. this->pStatementBuffer->Add((uint32)span);
  1231. // Update iterator for the next set
  1232. iter.accumulatedSourceBegin = data->sourceBegin;
  1233. iter.accumulatedBytecodeBegin = data->bytecodeBegin;
  1234. return TRUE;
  1235. }
  1236. // FunctionProxy methods
  1237. ScriptContext*
  1238. FunctionProxy::GetScriptContext() const
  1239. {
  1240. return m_scriptContext;
  1241. }
  1242. void FunctionProxy::Copy(FunctionProxy* other)
  1243. {
  1244. Assert(other);
  1245. other->SetIsTopLevel(this->m_isTopLevel);
  1246. if (this->IsPublicLibraryCode())
  1247. {
  1248. other->SetIsPublicLibraryCode();
  1249. }
  1250. }
  1251. void ParseableFunctionInfo::Copy(ParseableFunctionInfo * other)
  1252. {
  1253. #define CopyDeferParseField(field) other->field = this->field;
  1254. CopyDeferParseField(flags);
  1255. CopyDeferParseField(m_isDeclaration);
  1256. CopyDeferParseField(m_isAccessor);
  1257. CopyDeferParseField(m_isStrictMode);
  1258. CopyDeferParseField(m_isGlobalFunc);
  1259. CopyDeferParseField(m_doBackendArgumentsOptimization);
  1260. CopyDeferParseField(m_doScopeObjectCreation);
  1261. CopyDeferParseField(m_usesArgumentsObject);
  1262. CopyDeferParseField(m_isEval);
  1263. CopyDeferParseField(m_isDynamicFunction);
  1264. CopyDeferParseField(m_hasImplicitArgIns);
  1265. CopyDeferParseField(m_dontInline);
  1266. CopyDeferParseField(m_inParamCount);
  1267. CopyDeferParseField(m_grfscr);
  1268. other->SetScopeInfo(this->GetScopeInfo());
  1269. CopyDeferParseField(m_utf8SourceHasBeenSet);
  1270. #if DBG
  1271. CopyDeferParseField(deferredParseNextFunctionId);
  1272. CopyDeferParseField(scopeObjectSize);
  1273. #endif
  1274. CopyDeferParseField(scopeSlotArraySize);
  1275. CopyDeferParseField(paramScopeSlotArraySize);
  1276. other->SetCachedSourceString(this->GetCachedSourceString());
  1277. CopyDeferParseField(m_isAsmjsMode);
  1278. CopyDeferParseField(m_isAsmJsFunction);
  1279. other->SetFunctionObjectTypeList(this->GetFunctionObjectTypeList());
  1280. PropertyId * propertyIds = this->GetPropertyIdsForScopeSlotArray();
  1281. if (propertyIds != nullptr)
  1282. {
  1283. other->SetPropertyIdsForScopeSlotArray(propertyIds, this->scopeSlotArraySize, this->paramScopeSlotArraySize);
  1284. }
  1285. CopyDeferParseField(m_sourceIndex);
  1286. CopyDeferParseField(m_cchStartOffset);
  1287. CopyDeferParseField(m_cchLength);
  1288. CopyDeferParseField(m_lineNumber);
  1289. CopyDeferParseField(m_columnNumber);
  1290. CopyDeferParseField(m_cbStartOffset);
  1291. CopyDeferParseField(m_cbLength);
  1292. this->CopyNestedArray(other);
  1293. #undef CopyDeferParseField
  1294. }
  1295. void ParseableFunctionInfo::Copy(FunctionBody* other)
  1296. {
  1297. this->Copy(static_cast<ParseableFunctionInfo*>(other));
  1298. other->CopySourceInfo(this);
  1299. }
  1300. void ParseableFunctionInfo::CopyNestedArray(ParseableFunctionInfo * other)
  1301. {
  1302. NestedArray * thisNestedArray = this->GetNestedArray();
  1303. NestedArray * otherNestedArray = other->GetNestedArray();
  1304. if (thisNestedArray == nullptr)
  1305. {
  1306. Assert(otherNestedArray == nullptr);
  1307. return;
  1308. }
  1309. Assert(otherNestedArray->nestedCount == thisNestedArray->nestedCount);
  1310. for (uint i = 0; i < thisNestedArray->nestedCount; i++)
  1311. {
  1312. otherNestedArray->functionInfoArray[i] = thisNestedArray->functionInfoArray[i];
  1313. }
  1314. }
  1315. // DeferDeserializeFunctionInfo methods
  1316. DeferDeserializeFunctionInfo::DeferDeserializeFunctionInfo(int nestedCount, LocalFunctionId functionId, ByteCodeCache* byteCodeCache, const byte* serializedFunction, Utf8SourceInfo* sourceInfo, ScriptContext* scriptContext, uint functionNumber, const char16* displayName, uint displayNameLength, uint displayShortNameOffset, NativeModule *nativeModule, FunctionInfo::Attributes attributes) :
  1317. FunctionProxy(scriptContext, sourceInfo, functionNumber),
  1318. m_cache(byteCodeCache),
  1319. m_functionBytes(serializedFunction),
  1320. m_displayName(nullptr),
  1321. m_displayNameLength(0),
  1322. m_nativeModule(nativeModule)
  1323. {
  1324. this->functionInfo = RecyclerNew(scriptContext->GetRecycler(), FunctionInfo, DefaultDeferredDeserializeThunk, (FunctionInfo::Attributes)(attributes | FunctionInfo::Attributes::DeferredDeserialize), functionId, this);
  1325. this->m_defaultEntryPointInfo = RecyclerNew(scriptContext->GetRecycler(), ProxyEntryPointInfo, DefaultDeferredDeserializeThunk);
  1326. PERF_COUNTER_INC(Code, DeferDeserializeFunctionProxy);
  1327. SetDisplayName(displayName, displayNameLength, displayShortNameOffset, FunctionProxy::SetDisplayNameFlagsDontCopy);
  1328. }
  1329. DeferDeserializeFunctionInfo* DeferDeserializeFunctionInfo::New(ScriptContext* scriptContext, int nestedCount, LocalFunctionId functionId, ByteCodeCache* byteCodeCache, const byte* serializedFunction, Utf8SourceInfo* sourceInfo, const char16* displayName, uint displayNameLength, uint displayShortNameOffset, NativeModule *nativeModule, FunctionInfo::Attributes attributes)
  1330. {
  1331. return RecyclerNewFinalized(scriptContext->GetRecycler(),
  1332. DeferDeserializeFunctionInfo,
  1333. nestedCount,
  1334. functionId,
  1335. byteCodeCache,
  1336. serializedFunction,
  1337. sourceInfo,
  1338. scriptContext,
  1339. scriptContext->GetThreadContext()->NewFunctionNumber(),
  1340. displayName,
  1341. displayNameLength,
  1342. displayShortNameOffset,
  1343. nativeModule,
  1344. attributes);
  1345. }
  1346. const char16*
  1347. DeferDeserializeFunctionInfo::GetDisplayName() const
  1348. {
  1349. return this->m_displayName;
  1350. }
  1351. // ParseableFunctionInfo methods
  1352. ParseableFunctionInfo::ParseableFunctionInfo(JavascriptMethod entryPoint, int nestedCount,
  1353. LocalFunctionId functionId, Utf8SourceInfo* sourceInfo, ScriptContext* scriptContext, uint functionNumber,
  1354. const char16* displayName, uint displayNameLength, uint displayShortNameOffset, FunctionInfo::Attributes attributes, Js::PropertyRecordList* propertyRecords, FunctionBodyFlags flags) :
  1355. FunctionProxy(scriptContext, sourceInfo, functionNumber),
  1356. #if DYNAMIC_INTERPRETER_THUNK
  1357. m_dynamicInterpreterThunk(nullptr),
  1358. #endif
  1359. flags(flags),
  1360. m_hasBeenParsed(false),
  1361. m_isGlobalFunc(false),
  1362. m_isDeclaration(false),
  1363. m_isNamedFunctionExpression(false),
  1364. m_isNameIdentifierRef (true),
  1365. m_isStaticNameFunction(false),
  1366. m_doBackendArgumentsOptimization(true),
  1367. m_doScopeObjectCreation(true),
  1368. m_usesArgumentsObject(false),
  1369. m_isStrictMode(false),
  1370. m_isAsmjsMode(false),
  1371. m_dontInline(false),
  1372. m_hasImplicitArgIns(true),
  1373. m_grfscr(0),
  1374. m_inParamCount(0),
  1375. m_reportedInParamCount(0),
  1376. m_sourceIndex(Js::Constants::InvalidSourceIndex),
  1377. m_utf8SourceHasBeenSet(false),
  1378. m_cchLength(0),
  1379. m_cbLength(0),
  1380. m_cchStartOffset(0),
  1381. m_cbStartOffset(0),
  1382. m_lineNumber(0),
  1383. m_columnNumber(0),
  1384. m_isEval(false),
  1385. m_isDynamicFunction(false),
  1386. m_displayName(nullptr),
  1387. m_displayNameLength(0),
  1388. m_displayShortNameOffset(0),
  1389. scopeSlotArraySize(0),
  1390. paramScopeSlotArraySize(0),
  1391. m_reparsed(false),
  1392. m_isAsmJsFunction(false),
  1393. m_tag21(true),
  1394. m_isMethod(false)
  1395. #if DBG
  1396. ,m_wasEverAsmjsMode(false)
  1397. ,scopeObjectSize(0)
  1398. #endif
  1399. {
  1400. this->functionInfo = RecyclerNew(scriptContext->GetRecycler(), FunctionInfo, entryPoint, attributes, functionId, this);
  1401. if (nestedCount > 0)
  1402. {
  1403. nestedArray = RecyclerNewPlusZ(m_scriptContext->GetRecycler(),
  1404. nestedCount*sizeof(FunctionProxy*), NestedArray, nestedCount);
  1405. }
  1406. else
  1407. {
  1408. nestedArray = nullptr;
  1409. }
  1410. SetBoundPropertyRecords(propertyRecords);
  1411. if ((attributes & Js::FunctionInfo::DeferredParse) == 0)
  1412. {
  1413. void* validationCookie = nullptr;
  1414. #if ENABLE_NATIVE_CODEGEN
  1415. validationCookie = (void*)scriptContext->GetNativeCodeGenerator();
  1416. #endif
  1417. this->m_defaultEntryPointInfo = RecyclerNewFinalized(scriptContext->GetRecycler(),
  1418. FunctionEntryPointInfo, this, entryPoint, scriptContext->GetThreadContext(), validationCookie);
  1419. }
  1420. else
  1421. {
  1422. this->m_defaultEntryPointInfo = RecyclerNew(scriptContext->GetRecycler(), ProxyEntryPointInfo, entryPoint);
  1423. }
  1424. SetDisplayName(displayName, displayNameLength, displayShortNameOffset);
  1425. this->SetOriginalEntryPoint(DefaultEntryThunk);
  1426. }
  1427. ParseableFunctionInfo::ParseableFunctionInfo(ParseableFunctionInfo * proxy) :
  1428. FunctionProxy(proxy->GetScriptContext(), proxy->GetUtf8SourceInfo(), proxy->GetFunctionNumber()),
  1429. #if DYNAMIC_INTERPRETER_THUNK
  1430. m_dynamicInterpreterThunk(nullptr),
  1431. #endif
  1432. m_hasBeenParsed(false),
  1433. m_isNamedFunctionExpression(proxy->GetIsNamedFunctionExpression()),
  1434. m_isNameIdentifierRef (proxy->GetIsNameIdentifierRef()),
  1435. m_isStaticNameFunction(proxy->GetIsStaticNameFunction()),
  1436. m_reportedInParamCount(proxy->GetReportedInParamsCount()),
  1437. m_reparsed(proxy->IsReparsed()),
  1438. m_isMethod(proxy->IsMethod()),
  1439. m_tag21(true)
  1440. #if DBG
  1441. , m_wasEverAsmjsMode(proxy->m_wasEverAsmjsMode)
  1442. #endif
  1443. {
  1444. FunctionInfo * functionInfo = proxy->GetFunctionInfo();
  1445. this->functionInfo = functionInfo;
  1446. uint nestedCount = proxy->GetNestedCount();
  1447. if (nestedCount > 0)
  1448. {
  1449. nestedArray = RecyclerNewPlusZ(m_scriptContext->GetRecycler(),
  1450. nestedCount*sizeof(FunctionProxy*), NestedArray, nestedCount);
  1451. }
  1452. else
  1453. {
  1454. nestedArray = nullptr;
  1455. }
  1456. proxy->Copy(this);
  1457. SetBoundPropertyRecords(proxy->GetBoundPropertyRecords());
  1458. SetDisplayName(proxy->GetDisplayName(), proxy->GetDisplayNameLength(), proxy->GetShortDisplayNameOffset());
  1459. }
  1460. ParseableFunctionInfo* ParseableFunctionInfo::New(ScriptContext* scriptContext, int nestedCount,
  1461. LocalFunctionId functionId, Utf8SourceInfo* sourceInfo, const char16* displayName, uint displayNameLength, uint displayShortNameOffset, Js::PropertyRecordList* propertyRecords, FunctionInfo::Attributes attributes, FunctionBodyFlags flags)
  1462. {
  1463. #if defined(ENABLE_SCRIPT_PROFILING) || defined(ENABLE_SCRIPT_DEBUGGING)
  1464. Assert(
  1465. scriptContext->DeferredParsingThunk == ProfileDeferredParsingThunk ||
  1466. scriptContext->DeferredParsingThunk == DefaultDeferredParsingThunk);
  1467. #else
  1468. Assert(scriptContext->DeferredParsingThunk == DefaultDeferredParsingThunk);
  1469. #endif
  1470. #ifdef PERF_COUNTERS
  1471. PERF_COUNTER_INC(Code, DeferredFunction);
  1472. #endif
  1473. uint newFunctionNumber = scriptContext->GetThreadContext()->NewFunctionNumber();
  1474. if (!sourceInfo->GetSourceContextInfo()->IsDynamic())
  1475. {
  1476. PHASE_PRINT_TESTTRACE1(Js::DeferParsePhase, _u("Function was deferred from parsing - ID: %d; Display Name: %s; Utf8SourceInfo ID: %d; Source Length: %d; Source Url:%s\n"), newFunctionNumber, displayName, sourceInfo->GetSourceInfoId(), sourceInfo->GetCchLength(), sourceInfo->GetSourceContextInfo()->url);
  1477. }
  1478. else
  1479. {
  1480. PHASE_PRINT_TESTTRACE1(Js::DeferParsePhase, _u("Function was deferred from parsing - ID: %d; Display Name: %s; Utf8SourceInfo ID: %d; Source Length: %d;\n"), newFunctionNumber, displayName, sourceInfo->GetSourceInfoId(), sourceInfo->GetCchLength());
  1481. }
  1482. // When generating a new defer parse function, we always use a new function number
  1483. return RecyclerNewWithBarrierFinalized(scriptContext->GetRecycler(),
  1484. ParseableFunctionInfo,
  1485. scriptContext->DeferredParsingThunk,
  1486. nestedCount,
  1487. functionId,
  1488. sourceInfo,
  1489. scriptContext,
  1490. newFunctionNumber,
  1491. displayName,
  1492. displayNameLength,
  1493. displayShortNameOffset,
  1494. (FunctionInfo::Attributes)(attributes | FunctionInfo::Attributes::DeferredParse),
  1495. propertyRecords,
  1496. flags);
  1497. }
  1498. ParseableFunctionInfo *
  1499. ParseableFunctionInfo::NewDeferredFunctionFromFunctionBody(FunctionBody * functionBody)
  1500. {
  1501. ScriptContext * scriptContext = functionBody->GetScriptContext();
  1502. uint nestedCount = functionBody->GetNestedCount();
  1503. ParseableFunctionInfo * info = RecyclerNewWithBarrierFinalized(scriptContext->GetRecycler(),
  1504. ParseableFunctionInfo,
  1505. functionBody);
  1506. // Create new entry point info
  1507. info->m_defaultEntryPointInfo = RecyclerNew(scriptContext->GetRecycler(), ProxyEntryPointInfo, scriptContext->DeferredParsingThunk);
  1508. // Initialize nested function array, update back pointers
  1509. for (uint i = 0; i < nestedCount; i++)
  1510. {
  1511. FunctionInfo * nestedInfo = functionBody->GetNestedFunc(i);
  1512. info->SetNestedFunc(nestedInfo, i, 0);
  1513. }
  1514. // Update function objects
  1515. return info;
  1516. }
  1517. DWORD_PTR FunctionProxy::GetSecondaryHostSourceContext() const
  1518. {
  1519. return this->GetUtf8SourceInfo()->GetSecondaryHostSourceContext();
  1520. }
  1521. DWORD_PTR FunctionProxy::GetHostSourceContext() const
  1522. {
  1523. return this->GetSourceContextInfo()->dwHostSourceContext;
  1524. }
  1525. SourceContextInfo * FunctionProxy::GetSourceContextInfo() const
  1526. {
  1527. return this->GetHostSrcInfo()->sourceContextInfo;
  1528. }
  1529. SRCINFO const * FunctionProxy::GetHostSrcInfo() const
  1530. {
  1531. return this->GetUtf8SourceInfo()->GetSrcInfo();
  1532. }
  1533. //
  1534. // Returns the start line for the script buffer (code buffer for the entire script tag) of this current function.
  1535. // We subtract the lnMinHost because it is the number of lines we have added to augment scriptlets passed through
  1536. // ParseProcedureText to have a function name.
  1537. //
  1538. ULONG FunctionProxy::GetHostStartLine() const
  1539. {
  1540. return this->GetHostSrcInfo()->dlnHost - this->GetHostSrcInfo()->lnMinHost;
  1541. }
  1542. //
  1543. // Returns the start column of the first line for the script buffer of this current function.
  1544. //
  1545. ULONG FunctionProxy::GetHostStartColumn() const
  1546. {
  1547. return this->GetHostSrcInfo()->ulColumnHost;
  1548. }
  1549. //
  1550. // Returns line number in unmodified host buffer (i.e. without extra scriptlet code added by ParseProcedureText --
  1551. // when e.g. we add extra code for event handlers, such as "function onclick(event)\n{\n").
  1552. //
  1553. ULONG FunctionProxy::GetLineNumberInHostBuffer(ULONG relativeLineNumber) const
  1554. {
  1555. ULONG lineNumber = relativeLineNumber;
  1556. if (lineNumber >= this->GetHostSrcInfo()->lnMinHost)
  1557. {
  1558. lineNumber -= this->GetHostSrcInfo()->lnMinHost;
  1559. }
  1560. // Note that '<' is still a valid case -- that would be the case for onclick scriptlet function itself (lineNumber == 0).
  1561. return lineNumber;
  1562. }
  1563. ULONG FunctionProxy::ComputeAbsoluteLineNumber(ULONG relativeLineNumber) const
  1564. {
  1565. // We add 1 because the line numbers start from 0.
  1566. return this->GetHostSrcInfo()->dlnHost + GetLineNumberInHostBuffer(relativeLineNumber) + 1;
  1567. }
  1568. ULONG FunctionProxy::ComputeAbsoluteColumnNumber(ULONG relativeLineNumber, ULONG relativeColumnNumber) const
  1569. {
  1570. if (this->GetLineNumberInHostBuffer(relativeLineNumber) == 0)
  1571. {
  1572. // The host column matters only for the first line.
  1573. return this->GetHostStartColumn() + relativeColumnNumber + 1;
  1574. }
  1575. // We add 1 because the column numbers start from 0.
  1576. return relativeColumnNumber + 1;
  1577. }
  1578. //
  1579. // Returns the line number of the function declaration in the source file.
  1580. //
  1581. ULONG
  1582. ParseableFunctionInfo::GetLineNumber() const
  1583. {
  1584. return this->ComputeAbsoluteLineNumber(this->m_lineNumber);
  1585. }
  1586. //
  1587. // Returns the column number of the function declaration in the source file.
  1588. //
  1589. ULONG
  1590. ParseableFunctionInfo::GetColumnNumber() const
  1591. {
  1592. return ComputeAbsoluteColumnNumber(this->m_lineNumber, m_columnNumber);
  1593. }
  1594. LPCWSTR
  1595. ParseableFunctionInfo::GetSourceName() const
  1596. {
  1597. return GetSourceName(this->GetSourceContextInfo());
  1598. }
  1599. void
  1600. ParseableFunctionInfo::SetGrfscr(uint32 grfscr)
  1601. {
  1602. this->m_grfscr = grfscr;
  1603. }
  1604. uint32
  1605. ParseableFunctionInfo::GetGrfscr() const
  1606. {
  1607. return this->m_grfscr;
  1608. }
  1609. ProxyEntryPointInfo*
  1610. FunctionProxy::GetDefaultEntryPointInfo() const
  1611. {
  1612. return this->m_defaultEntryPointInfo;
  1613. }
  1614. FunctionEntryPointInfo*
  1615. FunctionBody::GetDefaultFunctionEntryPointInfo() const
  1616. {
  1617. Assert(((ProxyEntryPointInfo*) this->defaultFunctionEntryPointInfo) == this->m_defaultEntryPointInfo);
  1618. return this->defaultFunctionEntryPointInfo;
  1619. }
  1620. void
  1621. ParseableFunctionInfo::SetInParamsCount(ArgSlot newInParamCount)
  1622. {
  1623. AssertMsg(m_inParamCount <= newInParamCount, "Cannot shrink register usage");
  1624. m_inParamCount = newInParamCount;
  1625. if (newInParamCount <= 1)
  1626. {
  1627. SetHasImplicitArgIns(false);
  1628. }
  1629. }
  1630. ArgSlot
  1631. ParseableFunctionInfo::GetReportedInParamsCount() const
  1632. {
  1633. return m_reportedInParamCount;
  1634. }
  1635. void
  1636. ParseableFunctionInfo::SetReportedInParamsCount(ArgSlot newInParamCount)
  1637. {
  1638. AssertMsg(m_reportedInParamCount <= newInParamCount, "Cannot shrink register usage");
  1639. m_reportedInParamCount = newInParamCount;
  1640. }
  1641. void
  1642. ParseableFunctionInfo::ResetInParams()
  1643. {
  1644. m_inParamCount = 0;
  1645. m_reportedInParamCount = 0;
  1646. }
  1647. const char16*
  1648. ParseableFunctionInfo::GetDisplayName() const
  1649. {
  1650. return this->m_displayName;
  1651. }
  1652. void ParseableFunctionInfo::BuildDeferredStubs(ParseNode *pnodeFnc)
  1653. {
  1654. Assert(pnodeFnc->nop == knopFncDecl);
  1655. // TODO: Disabling the creation of deferred stubs for now. We need to rethink the design again as the current behavior
  1656. // is not usable with precise capturing.
  1657. this->SetDeferredStubs(nullptr);
  1658. }
  1659. FunctionInfoArray ParseableFunctionInfo::GetNestedFuncArray()
  1660. {
  1661. Assert(GetNestedArray() != nullptr);
  1662. return GetNestedArray()->functionInfoArray;
  1663. }
  1664. void ParseableFunctionInfo::SetNestedFunc(FunctionInfo* nestedFunc, uint index, uint32 flags)
  1665. {
  1666. AssertMsg(index < this->GetNestedCount(), "Trying to write past the nested func array");
  1667. FunctionInfoArray nested = this->GetNestedFuncArray();
  1668. nested[index] = nestedFunc;
  1669. }
  1670. FunctionInfo* ParseableFunctionInfo::GetNestedFunc(uint index)
  1671. {
  1672. return *(GetNestedFuncReference(index));
  1673. }
  1674. FunctionProxy* ParseableFunctionInfo::GetNestedFunctionProxy(uint index)
  1675. {
  1676. FunctionInfo *info = GetNestedFunc(index);
  1677. return info ? info->GetFunctionProxy() : nullptr;
  1678. }
  1679. FunctionInfoPtrPtr ParseableFunctionInfo::GetNestedFuncReference(uint index)
  1680. {
  1681. AssertMsg(index < this->GetNestedCount(), "Trying to write past the nested func array");
  1682. FunctionInfoArray nested = this->GetNestedFuncArray();
  1683. return &nested[index];
  1684. }
  1685. ParseableFunctionInfo* ParseableFunctionInfo::GetNestedFunctionForExecution(uint index)
  1686. {
  1687. FunctionInfo* currentNestedFunction = this->GetNestedFunc(index);
  1688. Assert(currentNestedFunction);
  1689. if (currentNestedFunction->IsDeferredDeserializeFunction())
  1690. {
  1691. currentNestedFunction->GetFunctionProxy()->EnsureDeserialized();
  1692. }
  1693. return currentNestedFunction->GetParseableFunctionInfo();
  1694. }
  1695. void
  1696. FunctionProxy::UpdateFunctionBodyImpl(FunctionBody * body)
  1697. {
  1698. FunctionInfo *functionInfo = this->GetFunctionInfo();
  1699. Assert(functionInfo->GetFunctionProxy() == this);
  1700. Assert(!this->IsFunctionBody() || body == this);
  1701. functionInfo->SetFunctionProxy(body);
  1702. body->SetFunctionInfo(functionInfo);
  1703. body->SetAttributes((FunctionInfo::Attributes)(functionInfo->GetAttributes() & ~(FunctionInfo::Attributes::DeferredParse | FunctionInfo::Attributes::DeferredDeserialize)));
  1704. }
  1705. //
  1706. // This method gets a function body for the purposes of execution
  1707. // It has an if within it to avoid making it a virtual- it's called from the interpreter
  1708. // It will cause the function info to get deserialized if it hasn't been deserialized
  1709. // already
  1710. //
  1711. ParseableFunctionInfo * FunctionProxy::EnsureDeserialized()
  1712. {
  1713. Assert(this == this->GetFunctionInfo()->GetFunctionProxy());
  1714. FunctionProxy * executionFunctionBody = this;
  1715. if (IsDeferredDeserializeFunction())
  1716. {
  1717. // No need to deserialize function body if scriptContext closed because we can't execute it.
  1718. // Bigger problem is the script engine might have released bytecode file mapping and we can't deserialize.
  1719. Assert(!m_scriptContext->IsClosed());
  1720. executionFunctionBody = ((DeferDeserializeFunctionInfo*) this)->Deserialize();
  1721. this->GetFunctionInfo()->SetFunctionProxy(executionFunctionBody);
  1722. Assert(executionFunctionBody->GetFunctionInfo()->HasBody());
  1723. Assert(executionFunctionBody != this);
  1724. }
  1725. return (ParseableFunctionInfo *)executionFunctionBody;
  1726. }
  1727. ScriptFunctionType * FunctionProxy::GetDeferredPrototypeType() const
  1728. {
  1729. return deferredPrototypeType;
  1730. }
  1731. ScriptFunctionType * FunctionProxy::EnsureDeferredPrototypeType()
  1732. {
  1733. Assert(this->GetFunctionInfo()->GetFunctionProxy() == this);
  1734. return deferredPrototypeType != nullptr ?
  1735. static_cast<ScriptFunctionType*>(deferredPrototypeType) : AllocDeferredPrototypeType();
  1736. }
  1737. ScriptFunctionType * FunctionProxy::AllocDeferredPrototypeType()
  1738. {
  1739. Assert(deferredPrototypeType == nullptr);
  1740. ScriptFunctionType * type = ScriptFunctionType::New(this, true);
  1741. deferredPrototypeType = type;
  1742. return type;
  1743. }
  1744. JavascriptMethod FunctionProxy::GetDirectEntryPoint(ProxyEntryPointInfo* entryPoint) const
  1745. {
  1746. Assert(entryPoint->jsMethod != nullptr);
  1747. return entryPoint->jsMethod;
  1748. }
  1749. // Function object type list methods
  1750. FunctionProxy::FunctionTypeWeakRefList* FunctionProxy::GetFunctionObjectTypeList() const
  1751. {
  1752. return static_cast<FunctionTypeWeakRefList*>(this->GetAuxPtr(AuxPointerType::FunctionObjectTypeList));
  1753. }
  1754. void FunctionProxy::SetFunctionObjectTypeList(FunctionProxy::FunctionTypeWeakRefList* list)
  1755. {
  1756. this->SetAuxPtr(AuxPointerType::FunctionObjectTypeList, list);
  1757. }
  1758. template <typename Fn>
  1759. void FunctionProxy::MapFunctionObjectTypes(Fn func)
  1760. {
  1761. FunctionTypeWeakRefList* functionObjectTypeList = this->GetFunctionObjectTypeList();
  1762. if (functionObjectTypeList != nullptr)
  1763. {
  1764. functionObjectTypeList->Map([&](int, FunctionTypeWeakRef* typeWeakRef)
  1765. {
  1766. if (typeWeakRef)
  1767. {
  1768. ScriptFunctionType* type = typeWeakRef->Get();
  1769. if (type)
  1770. {
  1771. func(type);
  1772. }
  1773. }
  1774. });
  1775. }
  1776. if (this->deferredPrototypeType)
  1777. {
  1778. func(this->deferredPrototypeType);
  1779. }
  1780. }
  1781. FunctionProxy::FunctionTypeWeakRefList* FunctionProxy::EnsureFunctionObjectTypeList()
  1782. {
  1783. FunctionTypeWeakRefList* functionObjectTypeList = this->GetFunctionObjectTypeList();
  1784. if (functionObjectTypeList == nullptr)
  1785. {
  1786. Recycler* recycler = this->GetScriptContext()->GetRecycler();
  1787. functionObjectTypeList = RecyclerNew(recycler, FunctionTypeWeakRefList, recycler);
  1788. this->SetFunctionObjectTypeList(functionObjectTypeList);
  1789. }
  1790. return functionObjectTypeList;
  1791. }
  1792. void FunctionProxy::RegisterFunctionObjectType(ScriptFunctionType* functionType)
  1793. {
  1794. FunctionTypeWeakRefList* typeList = EnsureFunctionObjectTypeList();
  1795. Assert(functionType != deferredPrototypeType);
  1796. Recycler * recycler = this->GetScriptContext()->GetRecycler();
  1797. FunctionTypeWeakRef* weakRef = recycler->CreateWeakReferenceHandle(functionType);
  1798. typeList->SetAtFirstFreeSpot(weakRef);
  1799. OUTPUT_TRACE(Js::ExpirableCollectPhase, _u("Registered type 0x%p on function body %p, count = %d\n"), functionType, this, typeList->Count());
  1800. }
  1801. void DeferDeserializeFunctionInfo::SetDisplayName(const char16* displayName)
  1802. {
  1803. size_t len = wcslen(displayName);
  1804. if (len > UINT_MAX)
  1805. {
  1806. // Can't support display name that big
  1807. Js::Throw::OutOfMemory();
  1808. }
  1809. SetDisplayName(displayName, (uint)len, 0);
  1810. }
  1811. void DeferDeserializeFunctionInfo::SetDisplayName(const char16* pszDisplayName, uint displayNameLength, uint displayShortNameOffset, SetDisplayNameFlags flags /* default to None */)
  1812. {
  1813. this->m_displayNameLength = displayNameLength;
  1814. this->m_displayShortNameOffset = displayShortNameOffset;
  1815. this->m_displayNameIsRecyclerAllocated = FunctionProxy::SetDisplayName(pszDisplayName, &this->m_displayName, displayNameLength, m_scriptContext, flags);
  1816. }
  1817. LPCWSTR DeferDeserializeFunctionInfo::GetSourceInfo(int& lineNumber, int& columnNumber) const
  1818. {
  1819. // Read all the necessary information from the serialized byte code
  1820. int lineNumberField, columnNumberField;
  1821. bool m_isEval, m_isDynamicFunction;
  1822. ByteCodeSerializer::ReadSourceInfo(this, lineNumberField, columnNumberField, m_isEval, m_isDynamicFunction);
  1823. // Decode them
  1824. lineNumber = ComputeAbsoluteLineNumber(lineNumberField);
  1825. columnNumber = ComputeAbsoluteColumnNumber(lineNumberField, columnNumberField);
  1826. return Js::ParseableFunctionInfo::GetSourceName<SourceContextInfo*>(this->GetSourceContextInfo(), m_isEval, m_isDynamicFunction);
  1827. }
  1828. void DeferDeserializeFunctionInfo::Finalize(bool isShutdown)
  1829. {
  1830. __super::Finalize(isShutdown);
  1831. PERF_COUNTER_DEC(Code, DeferDeserializeFunctionProxy);
  1832. }
  1833. FunctionBody* DeferDeserializeFunctionInfo::Deserialize()
  1834. {
  1835. Assert(this->GetFunctionInfo()->GetFunctionProxy() == this);
  1836. FunctionBody * body = ByteCodeSerializer::DeserializeFunction(this->m_scriptContext, this);
  1837. this->SetLocalFunctionId(body->GetLocalFunctionId());
  1838. this->SetOriginalEntryPoint(body->GetOriginalEntryPoint());
  1839. this->Copy(body);
  1840. this->UpdateFunctionBodyImpl(body);
  1841. Assert(body->GetFunctionBody() == body);
  1842. return body;
  1843. }
  1844. //
  1845. // hrParse can be one of the following from deferred re-parse (check CompileScriptException::ProcessError):
  1846. // E_OUTOFMEMORY
  1847. // E_UNEXPECTED
  1848. // SCRIPT_E_RECORDED,
  1849. // with ei.scode: ERRnoMemory, VBSERR_OutOfStack, E_OUTOFMEMORY, E_FAIL, E_ABORT
  1850. // Any other ei.scode shouldn't appear in deferred re-parse.
  1851. //
  1852. // Map errors like OOM/SOE, return it and clean hrParse. Any other error remaining in hrParse is an internal error.
  1853. //
  1854. HRESULT ParseableFunctionInfo::MapDeferredReparseError(HRESULT& hrParse, const CompileScriptException& se)
  1855. {
  1856. HRESULT hrMapped = NO_ERROR;
  1857. switch (hrParse)
  1858. {
  1859. case E_OUTOFMEMORY:
  1860. hrMapped = E_OUTOFMEMORY;
  1861. break;
  1862. case SCRIPT_E_RECORDED:
  1863. switch (se.ei.scode)
  1864. {
  1865. case ERRnoMemory:
  1866. case E_OUTOFMEMORY:
  1867. case VBSERR_OutOfMemory:
  1868. hrMapped = E_OUTOFMEMORY;
  1869. break;
  1870. case VBSERR_OutOfStack:
  1871. hrMapped = VBSERR_OutOfStack;
  1872. break;
  1873. case JSERR_AsmJsCompileError:
  1874. hrMapped = JSERR_AsmJsCompileError;
  1875. break;
  1876. case E_ABORT:
  1877. hrMapped = E_ABORT;
  1878. break;
  1879. }
  1880. }
  1881. if (FAILED(hrMapped))
  1882. {
  1883. // If we have mapped error, clear hrParse. We'll throw error from hrMapped.
  1884. hrParse = NO_ERROR;
  1885. }
  1886. return hrMapped;
  1887. }
  1888. FunctionBody* ParseableFunctionInfo::Parse(ScriptFunction ** functionRef, bool isByteCodeDeserialization)
  1889. {
  1890. Assert(this == this->GetFunctionInfo()->GetFunctionProxy());
  1891. if (!IsDeferredParseFunction())
  1892. {
  1893. // If not deferredparsed, the functionBodyImpl and this will be the same, just return the current functionBody.
  1894. Assert(GetFunctionBody()->IsFunctionParsed());
  1895. return GetFunctionBody();
  1896. }
  1897. bool asmjsParseFailed = false;
  1898. BOOL fParsed = FALSE;
  1899. FunctionBody* returnFunctionBody = nullptr;
  1900. ENTER_PINNED_SCOPE(Js::PropertyRecordList, propertyRecordList);
  1901. Recycler* recycler = this->m_scriptContext->GetRecycler();
  1902. propertyRecordList = RecyclerNew(recycler, Js::PropertyRecordList, recycler);
  1903. bool isDebugOrAsmJsReparse = false;
  1904. FunctionBody* funcBody = nullptr;
  1905. {
  1906. AutoRestoreFunctionInfo autoRestoreFunctionInfo(this, DefaultEntryThunk);
  1907. // If m_hasBeenParsed = true, one of the following things happened things happened:
  1908. // - We had multiple function objects which were all defer-parsed, but with the same function body and one of them
  1909. // got the body to be parsed before another was called
  1910. // - We are in debug mode and had our thunks switched to DeferParseThunk
  1911. // - This is an already parsed asm.js module, which has been invalidated at link time and must be reparsed as a non-asm.js function
  1912. if (!this->m_hasBeenParsed)
  1913. {
  1914. this->GetUtf8SourceInfo()->StopTrackingDeferredFunction(this->GetLocalFunctionId());
  1915. funcBody = FunctionBody::NewFromParseableFunctionInfo(this, propertyRecordList);
  1916. autoRestoreFunctionInfo.funcBody = funcBody;
  1917. PERF_COUNTER_DEC(Code, DeferredFunction);
  1918. if (!this->GetSourceContextInfo()->IsDynamic())
  1919. {
  1920. PHASE_PRINT_TESTTRACE1(Js::DeferParsePhase, _u("TestTrace: Deferred function parsed - ID: %d; Display Name: %s; Length: %d; Nested Function Count: %d; Utf8SourceInfo: %d; Source Length: %d; Is Top Level: %s; Source Url: %s\n"), m_functionNumber, this->GetDisplayName(), this->m_cchLength, this->GetNestedCount(), this->m_utf8SourceInfo->GetSourceInfoId(), this->m_utf8SourceInfo->GetCchLength(), this->GetIsTopLevel() ? _u("True") : _u("False"), this->GetSourceContextInfo()->url);
  1921. }
  1922. else
  1923. {
  1924. PHASE_PRINT_TESTTRACE1(Js::DeferParsePhase, _u("TestTrace: Deferred function parsed - ID: %d; Display Name: %s; Length: %d; Nested Function Count: %d; Utf8SourceInfo: %d; Source Length: %d\n; Is Top Level: %s;"), m_functionNumber, this->GetDisplayName(), this->m_cchLength, this->GetNestedCount(), this->m_utf8SourceInfo->GetSourceInfoId(), this->m_utf8SourceInfo->GetCchLength(), this->GetIsTopLevel() ? _u("True") : _u("False"));
  1925. }
  1926. if (!this->GetIsTopLevel() &&
  1927. !this->GetSourceContextInfo()->IsDynamic() &&
  1928. this->m_scriptContext->DoUndeferGlobalFunctions())
  1929. {
  1930. this->GetUtf8SourceInfo()->UndeferGlobalFunctions([this](const Utf8SourceInfo::DeferredFunctionsDictionary::EntryType& func)
  1931. {
  1932. Js::ParseableFunctionInfo *nextFunc = func.Value();
  1933. JavascriptExceptionObject* pExceptionObject = nullptr;
  1934. if (nextFunc != nullptr && this != nextFunc)
  1935. {
  1936. try
  1937. {
  1938. nextFunc->Parse();
  1939. }
  1940. catch (OutOfMemoryException) {}
  1941. catch (StackOverflowException) {}
  1942. catch (const Js::JavascriptException& err)
  1943. {
  1944. pExceptionObject = err.GetAndClear();
  1945. }
  1946. // Do not do anything with an OOM or SOE, returning true is fine, it will then be undeferred (or attempted to again when called)
  1947. if (pExceptionObject)
  1948. {
  1949. if (pExceptionObject != ThreadContext::GetContextForCurrentThread()->GetPendingOOMErrorObject() &&
  1950. pExceptionObject != ThreadContext::GetContextForCurrentThread()->GetPendingSOErrorObject())
  1951. {
  1952. JavascriptExceptionOperators::DoThrow(pExceptionObject, /*scriptContext*/nullptr);
  1953. }
  1954. }
  1955. }
  1956. return true;
  1957. });
  1958. }
  1959. }
  1960. else
  1961. {
  1962. bool isDebugReparse = m_scriptContext->IsScriptContextInSourceRundownOrDebugMode() && !this->GetUtf8SourceInfo()->GetIsLibraryCode();
  1963. bool isAsmJsReparse = m_isAsmjsMode && !isDebugReparse;
  1964. isDebugOrAsmJsReparse = isAsmJsReparse || isDebugReparse;
  1965. funcBody = this->GetFunctionBody();
  1966. // As we have a valid function body already clear the restore data
  1967. autoRestoreFunctionInfo.Clear();
  1968. if (isDebugOrAsmJsReparse)
  1969. {
  1970. #if ENABLE_DEBUG_CONFIG_OPTIONS
  1971. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  1972. #endif
  1973. #if DBG
  1974. Assert(
  1975. funcBody->IsReparsed()
  1976. || m_scriptContext->IsScriptContextInSourceRundownOrDebugMode()
  1977. || m_isAsmjsMode);
  1978. #endif
  1979. OUTPUT_TRACE(Js::DebuggerPhase, _u("Full nested reparse of function: %s (%s)\n"), funcBody->GetDisplayName(), funcBody->GetDebugNumberSet(debugStringBuffer));
  1980. if (funcBody->GetByteCode())
  1981. {
  1982. // The current function needs to be cleaned up before getting generated in the debug mode.
  1983. funcBody->CleanupToReparse();
  1984. }
  1985. }
  1986. }
  1987. // Note that we may be trying to re-gen an already-completed function. (This can happen, for instance,
  1988. // in the case of named function expressions inside "with" statements in compat mode.)
  1989. // In such a case, there's no work to do.
  1990. if (funcBody->GetByteCode() == nullptr)
  1991. {
  1992. #if ENABLE_PROFILE_INFO
  1993. Assert(!funcBody->HasExecutionDynamicProfileInfo());
  1994. #endif
  1995. // In debug or asm.js mode, the scriptlet will be asked to recompile again.
  1996. AssertMsg(isDebugOrAsmJsReparse || funcBody->GetGrfscr() & fscrGlobalCode || CONFIG_FLAG(DeferNested), "Deferred parsing of non-global procedure?");
  1997. HRESULT hr = NO_ERROR;
  1998. HRESULT hrParser = NO_ERROR;
  1999. HRESULT hrParseCodeGen = NO_ERROR;
  2000. BEGIN_LEAVE_SCRIPT_INTERNAL(m_scriptContext)
  2001. {
  2002. bool isCesu8 = m_scriptContext->GetSource(funcBody->GetSourceIndex())->IsCesu8();
  2003. size_t offset = this->StartOffset();
  2004. charcount_t charOffset = this->StartInDocument();
  2005. size_t length = this->LengthInBytes();
  2006. LPCUTF8 pszStart = this->GetStartOfDocument();
  2007. uint32 grfscr = funcBody->GetGrfscr() | fscrDeferredFnc;
  2008. // For the global function we want to re-use the glo functionbody which is already created in the non-debug mode
  2009. if (!funcBody->GetIsGlobalFunc())
  2010. {
  2011. grfscr &= ~fscrGlobalCode;
  2012. }
  2013. if (!funcBody->GetIsDeclaration() && !funcBody->GetIsGlobalFunc()) // No refresh may reparse global function (e.g. eval code)
  2014. {
  2015. // Notify the parser that the top-level function was defined in an expression,
  2016. // (not a function declaration statement).
  2017. grfscr |= fscrDeferredFncExpression;
  2018. }
  2019. if (funcBody->IsMethod())
  2020. {
  2021. grfscr |= fscrDeferredFncIsMethod;
  2022. }
  2023. else
  2024. {
  2025. grfscr &= ~fscrDeferredFncIsMethod;
  2026. }
  2027. if (!CONFIG_FLAG(DeferNested) || isDebugOrAsmJsReparse)
  2028. {
  2029. grfscr &= ~fscrDeferFncParse; // Disable deferred parsing if not DeferNested, or doing a debug/asm.js re-parse
  2030. }
  2031. if (isDebugOrAsmJsReparse)
  2032. {
  2033. grfscr |= fscrNoAsmJs; // Disable asm.js when debugging or if linking failed
  2034. }
  2035. BEGIN_TRANSLATE_EXCEPTION_TO_HRESULT
  2036. {
  2037. CompileScriptException se;
  2038. Parser ps(m_scriptContext, funcBody->GetIsStrictMode() ? TRUE : FALSE);
  2039. ParseNodePtr parseTree = nullptr;
  2040. uint nextFunctionId = funcBody->GetLocalFunctionId();
  2041. hrParser = ps.ParseSourceWithOffset(&parseTree, pszStart, offset, length, charOffset, isCesu8, grfscr, &se,
  2042. &nextFunctionId, funcBody->GetRelativeLineNumber(), funcBody->GetSourceContextInfo(),
  2043. funcBody);
  2044. // Assert(FAILED(hrParser) || nextFunctionId == funcBody->deferredParseNextFunctionId || isDebugOrAsmJsReparse || isByteCodeDeserialization);
  2045. if (FAILED(hrParser))
  2046. {
  2047. hrParseCodeGen = MapDeferredReparseError(hrParser, se); // Map certain errors like OOM/SOE
  2048. AssertMsg(hrParseCodeGen == JSERR_AsmJsCompileError // AsmJsCompileError is not a syntax error
  2049. || (FAILED(hrParseCodeGen) && SUCCEEDED(hrParser)), "Syntax errors should never be detected on deferred re-parse");
  2050. }
  2051. else
  2052. {
  2053. TRACE_BYTECODE(_u("\nDeferred parse %s\n"), funcBody->GetDisplayName());
  2054. Js::AutoDynamicCodeReference dynamicFunctionReference(m_scriptContext);
  2055. bool forceNoNative = isDebugOrAsmJsReparse ? this->GetScriptContext()->IsInterpreted() : false;
  2056. ParseableFunctionInfo* rootFunc = funcBody->GetParseableFunctionInfo();
  2057. hrParseCodeGen = GenerateByteCode(parseTree, grfscr, m_scriptContext,
  2058. &rootFunc, funcBody->GetSourceIndex(),
  2059. forceNoNative, &ps, &se, funcBody->GetScopeInfo(), functionRef);
  2060. funcBody->SetParseableFunctionInfo(rootFunc);
  2061. if (SUCCEEDED(hrParseCodeGen))
  2062. {
  2063. fParsed = TRUE;
  2064. }
  2065. else
  2066. {
  2067. Assert(hrParseCodeGen == SCRIPT_E_RECORDED);
  2068. hrParseCodeGen = se.ei.scode;
  2069. }
  2070. }
  2071. }
  2072. END_TRANSLATE_EXCEPTION_TO_HRESULT(hr);
  2073. }
  2074. END_LEAVE_SCRIPT_INTERNAL(m_scriptContext);
  2075. THROW_KNOWN_HRESULT_EXCEPTIONS(hr, m_scriptContext);
  2076. Assert(hr == NO_ERROR);
  2077. if (!SUCCEEDED(hrParser))
  2078. {
  2079. JavascriptError::ThrowError(m_scriptContext, VBSERR_InternalError);
  2080. }
  2081. else if (!SUCCEEDED(hrParseCodeGen))
  2082. {
  2083. /*
  2084. * VBSERR_OutOfStack is of type kjstError but we throw a (more specific) StackOverflowError when a hard stack
  2085. * overflow occurs. To keep the behavior consistent I'm special casing it here.
  2086. */
  2087. if (hrParseCodeGen == VBSERR_OutOfStack)
  2088. {
  2089. JavascriptError::ThrowStackOverflowError(m_scriptContext);
  2090. }
  2091. else if (hrParseCodeGen == JSERR_AsmJsCompileError)
  2092. {
  2093. asmjsParseFailed = true;
  2094. }
  2095. else
  2096. {
  2097. JavascriptError::MapAndThrowError(m_scriptContext, hrParseCodeGen);
  2098. }
  2099. }
  2100. }
  2101. else
  2102. {
  2103. fParsed = FALSE;
  2104. }
  2105. if (!asmjsParseFailed)
  2106. {
  2107. autoRestoreFunctionInfo.Clear();
  2108. }
  2109. }
  2110. if (fParsed == TRUE)
  2111. {
  2112. // Restore if the function has nameIdentifier reference, as that name on the left side will not be parsed again while deferparse.
  2113. funcBody->SetIsNameIdentifierRef(this->GetIsNameIdentifierRef());
  2114. this->m_hasBeenParsed = true;
  2115. returnFunctionBody = funcBody;
  2116. }
  2117. else if(!asmjsParseFailed)
  2118. {
  2119. returnFunctionBody = this->GetFunctionBody();
  2120. }
  2121. LEAVE_PINNED_SCOPE();
  2122. if (asmjsParseFailed)
  2123. {
  2124. // disable asm.js and reparse on failure
  2125. m_grfscr |= fscrNoAsmJs;
  2126. return Parse(functionRef, isByteCodeDeserialization);
  2127. }
  2128. return returnFunctionBody;
  2129. }
  2130. #ifdef ASMJS_PLAT
  2131. FunctionBody* ParseableFunctionInfo::ParseAsmJs(Parser * ps, __out CompileScriptException * se, __out ParseNodePtr * parseTree)
  2132. {
  2133. Assert(IsDeferredParseFunction());
  2134. Assert(m_isAsmjsMode);
  2135. FunctionBody* returnFunctionBody = nullptr;
  2136. ENTER_PINNED_SCOPE(Js::PropertyRecordList, propertyRecordList);
  2137. Recycler* recycler = this->m_scriptContext->GetRecycler();
  2138. propertyRecordList = RecyclerNew(recycler, Js::PropertyRecordList, recycler);
  2139. FunctionBody* funcBody = nullptr;
  2140. funcBody = FunctionBody::NewFromRecycler(
  2141. this->m_scriptContext,
  2142. this->m_displayName,
  2143. this->m_displayNameLength,
  2144. this->m_displayShortNameOffset,
  2145. this->GetNestedCount(),
  2146. this->GetUtf8SourceInfo(),
  2147. this->m_functionNumber,
  2148. this->GetUtf8SourceInfo()->GetSrcInfo()->sourceContextInfo->sourceContextId,
  2149. this->GetLocalFunctionId(),
  2150. propertyRecordList,
  2151. (FunctionInfo::Attributes)(this->GetAttributes() & ~(FunctionInfo::Attributes::DeferredDeserialize | FunctionInfo::Attributes::DeferredParse)),
  2152. Js::FunctionBody::FunctionBodyFlags::Flags_HasNoExplicitReturnValue
  2153. #ifdef PERF_COUNTERS
  2154. , false /* is function from deferred deserialized proxy */
  2155. #endif
  2156. );
  2157. this->Copy(funcBody);
  2158. PERF_COUNTER_DEC(Code, DeferredFunction);
  2159. if (!this->GetSourceContextInfo()->IsDynamic())
  2160. {
  2161. PHASE_PRINT_TESTTRACE1(Js::DeferParsePhase, _u("TestTrace: Deferred function parsed - ID: %d; Display Name: %s; Length: %d; Nested Function Count: %d; Utf8SourceInfo: %d; Source Length: %d; Is Top Level: %s; Source Url: %s\n"), m_functionNumber, this->GetDisplayName(), this->m_cchLength, this->GetNestedCount(), this->m_utf8SourceInfo->GetSourceInfoId(), this->m_utf8SourceInfo->GetCchLength(), this->GetIsTopLevel() ? _u("True") : _u("False"), this->GetSourceContextInfo()->url);
  2162. }
  2163. else
  2164. {
  2165. PHASE_PRINT_TESTTRACE1(Js::DeferParsePhase, _u("TestTrace: Deferred function parsed - ID: %d; Display Name: %s; Length: %d; Nested Function Count: %d; Utf8SourceInfo: %d; Source Length: %d\n; Is Top Level: %s;"), m_functionNumber, this->GetDisplayName(), this->m_cchLength, this->GetNestedCount(), this->m_utf8SourceInfo->GetSourceInfoId(), this->m_utf8SourceInfo->GetCchLength(), this->GetIsTopLevel() ? _u("True") : _u("False"));
  2166. }
  2167. #if ENABLE_PROFILE_INFO
  2168. Assert(!funcBody->HasExecutionDynamicProfileInfo());
  2169. #endif
  2170. HRESULT hrParser = NO_ERROR;
  2171. HRESULT hrParseCodeGen = NO_ERROR;
  2172. bool isCesu8 = m_scriptContext->GetSource(funcBody->GetSourceIndex())->IsCesu8();
  2173. size_t offset = this->StartOffset();
  2174. charcount_t charOffset = this->StartInDocument();
  2175. size_t length = this->LengthInBytes();
  2176. LPCUTF8 pszStart = this->GetStartOfDocument();
  2177. uint32 grfscr = funcBody->GetGrfscr() | fscrDeferredFnc | fscrDeferredFncExpression;
  2178. uint nextFunctionId = funcBody->GetLocalFunctionId();
  2179. // if parser throws, it will be caught by function trying to bytecode gen the asm.js module, so don't need to catch/rethrow here
  2180. hrParser = ps->ParseSourceWithOffset(parseTree, pszStart, offset, length, charOffset, isCesu8, grfscr, se,
  2181. &nextFunctionId, funcBody->GetRelativeLineNumber(), funcBody->GetSourceContextInfo(),
  2182. funcBody);
  2183. Assert(FAILED(hrParser) || funcBody->deferredParseNextFunctionId == nextFunctionId);
  2184. if (FAILED(hrParser))
  2185. {
  2186. hrParseCodeGen = MapDeferredReparseError(hrParser, *se); // Map certain errors like OOM/SOE
  2187. AssertMsg(FAILED(hrParseCodeGen) && SUCCEEDED(hrParser), "Syntax errors should never be detected on deferred re-parse");
  2188. }
  2189. if (!SUCCEEDED(hrParser))
  2190. {
  2191. Throw::InternalError();
  2192. }
  2193. else if (!SUCCEEDED(hrParseCodeGen))
  2194. {
  2195. if (hrParseCodeGen == VBSERR_OutOfStack)
  2196. {
  2197. Throw::StackOverflow(m_scriptContext, nullptr);
  2198. }
  2199. else
  2200. {
  2201. Assert(hrParseCodeGen == E_OUTOFMEMORY);
  2202. Throw::OutOfMemory();
  2203. }
  2204. }
  2205. UpdateFunctionBodyImpl(funcBody);
  2206. m_hasBeenParsed = true;
  2207. Assert(funcBody->GetFunctionBody() == funcBody);
  2208. returnFunctionBody = funcBody;
  2209. LEAVE_PINNED_SCOPE();
  2210. return returnFunctionBody;
  2211. }
  2212. #endif
  2213. void ParseableFunctionInfo::Finalize(bool isShutdown)
  2214. {
  2215. __super::Finalize(isShutdown);
  2216. if (this->GetFunctionInfo())
  2217. {
  2218. // (If function info was never set, then initialization didn't finish, so there's nothing to remove from the dictionary.)
  2219. this->GetUtf8SourceInfo()->StopTrackingDeferredFunction(this->GetLocalFunctionId());
  2220. }
  2221. if (!this->m_hasBeenParsed)
  2222. {
  2223. PERF_COUNTER_DEC(Code, DeferredFunction);
  2224. }
  2225. }
  2226. bool ParseableFunctionInfo::IsFakeGlobalFunc(uint32 flags) const
  2227. {
  2228. return GetIsGlobalFunc() && !(flags & fscrGlobalCode);
  2229. }
  2230. #ifdef NTBUILD
  2231. bool ParseableFunctionInfo::GetExternalDisplaySourceName(BSTR* sourceName)
  2232. {
  2233. Assert(sourceName);
  2234. if (IsDynamicScript() && GetUtf8SourceInfo()->GetDebugDocumentName(sourceName))
  2235. {
  2236. return true;
  2237. }
  2238. *sourceName = ::SysAllocString(GetSourceName());
  2239. return *sourceName != nullptr;
  2240. }
  2241. #endif
  2242. const char16* FunctionProxy::WrapWithBrackets(const char16* name, charcount_t sz, ScriptContext* scriptContext)
  2243. {
  2244. char16 * wrappedName = RecyclerNewArrayLeaf(scriptContext->GetRecycler(), char16, sz + 3); //[]\0
  2245. wrappedName[0] = _u('[');
  2246. char16 *next = wrappedName;
  2247. js_wmemcpy_s(++next, sz, name, sz);
  2248. wrappedName[sz + 1] = _u(']');
  2249. wrappedName[sz + 2] = _u('\0');
  2250. return wrappedName;
  2251. }
  2252. const char16* FunctionProxy::GetShortDisplayName(charcount_t * shortNameLength)
  2253. {
  2254. const char16* name = this->GetDisplayName();
  2255. uint nameLength = this->GetDisplayNameLength();
  2256. if (name == nullptr)
  2257. {
  2258. *shortNameLength = 0;
  2259. return Constants::Empty;
  2260. }
  2261. if (IsConstantFunctionName(name))
  2262. {
  2263. *shortNameLength = nameLength;
  2264. return name;
  2265. }
  2266. uint shortNameOffset = this->GetShortDisplayNameOffset();
  2267. const char16 * shortName = name + shortNameOffset;
  2268. bool isBracketCase = shortNameOffset != 0 && name[shortNameOffset-1] == '[';
  2269. Assert(nameLength >= shortNameOffset);
  2270. *shortNameLength = nameLength - shortNameOffset;
  2271. if (!isBracketCase)
  2272. {
  2273. return shortName;
  2274. }
  2275. Assert(name[nameLength - 1] == ']');
  2276. char16 * finalshorterName = RecyclerNewArrayLeaf(this->GetScriptContext()->GetRecycler(), char16, *shortNameLength);
  2277. js_wmemcpy_s(finalshorterName, *shortNameLength, shortName, *shortNameLength - 1); // we don't want the last character in shorterName
  2278. finalshorterName[*shortNameLength - 1] = _u('\0');
  2279. *shortNameLength = *shortNameLength - 1;
  2280. return finalshorterName;
  2281. }
  2282. /*static*/
  2283. bool FunctionProxy::IsConstantFunctionName(const char16* srcName)
  2284. {
  2285. if (srcName == Js::Constants::GlobalFunction ||
  2286. srcName == Js::Constants::AnonymousFunction ||
  2287. srcName == Js::Constants::GlobalCode ||
  2288. srcName == Js::Constants::Anonymous ||
  2289. srcName == Js::Constants::UnknownScriptCode ||
  2290. srcName == Js::Constants::FunctionCode)
  2291. {
  2292. return true;
  2293. }
  2294. return false;
  2295. }
  2296. /*static */
  2297. /*Return value: Whether the target value is a recycler pointer or not*/
  2298. bool FunctionProxy::SetDisplayName(const char16* srcName, const char16** destName, uint displayNameLength, ScriptContext * scriptContext, SetDisplayNameFlags flags /* default to None */)
  2299. {
  2300. Assert(destName);
  2301. Assert(scriptContext);
  2302. if (srcName == nullptr)
  2303. {
  2304. *destName = (_u(""));
  2305. return false;
  2306. }
  2307. else if (IsConstantFunctionName(srcName) || (flags & SetDisplayNameFlagsDontCopy) != 0)
  2308. {
  2309. *destName = srcName;
  2310. return (flags & SetDisplayNameFlagsRecyclerAllocated) != 0; // Return true if array is recycler allocated
  2311. }
  2312. else
  2313. {
  2314. uint numCharacters = displayNameLength + 1;
  2315. Assert((flags & SetDisplayNameFlagsDontCopy) == 0);
  2316. *destName = RecyclerNewArrayLeaf(scriptContext->GetRecycler(), char16, numCharacters);
  2317. js_wmemcpy_s((char16 *)*destName, numCharacters, srcName, numCharacters);
  2318. ((char16 *)(*destName))[numCharacters - 1] = _u('\0');
  2319. return true;
  2320. }
  2321. }
  2322. bool FunctionProxy::SetDisplayName(const char16* srcName, WriteBarrierPtr<const char16>* destName, uint displayNameLength, ScriptContext * scriptContext, SetDisplayNameFlags flags /* default to None */)
  2323. {
  2324. const char16* dest = nullptr;
  2325. bool targetIsRecyclerMemory = SetDisplayName(srcName, &dest, displayNameLength, scriptContext, flags);
  2326. if (targetIsRecyclerMemory)
  2327. {
  2328. *destName = dest;
  2329. }
  2330. else
  2331. {
  2332. destName->NoWriteBarrierSet(dest);
  2333. }
  2334. return targetIsRecyclerMemory;
  2335. }
  2336. void ParseableFunctionInfo::SetDisplayName(const char16* pszDisplayName)
  2337. {
  2338. size_t len = wcslen(pszDisplayName);
  2339. if (len > UINT_MAX)
  2340. {
  2341. // Can't support display name that big
  2342. Js::Throw::OutOfMemory();
  2343. }
  2344. SetDisplayName(pszDisplayName, (uint)len, 0);
  2345. }
  2346. void ParseableFunctionInfo::SetDisplayName(const char16* pszDisplayName, uint displayNameLength, uint displayShortNameOffset, SetDisplayNameFlags flags /* default to None */)
  2347. {
  2348. this->m_displayNameLength = displayNameLength;
  2349. this->m_displayShortNameOffset = displayShortNameOffset;
  2350. this->m_displayNameIsRecyclerAllocated = FunctionProxy::SetDisplayName(pszDisplayName, &this->m_displayName, displayNameLength, m_scriptContext, flags);
  2351. }
  2352. // SourceInfo methods
  2353. /* static */
  2354. template <typename TStatementMapList>
  2355. FunctionBody::StatementMap * FunctionBody::GetNextNonSubexpressionStatementMap(TStatementMapList *statementMapList, int & startingAtIndex)
  2356. {
  2357. AssertMsg(statementMapList != nullptr, "Must have valid statementMapList to execute");
  2358. FunctionBody::StatementMap *map = statementMapList->Item(startingAtIndex);
  2359. while (map->isSubexpression && startingAtIndex < statementMapList->Count() - 1)
  2360. {
  2361. map = statementMapList->Item(++startingAtIndex);
  2362. }
  2363. if (map->isSubexpression) // Didn't find any non inner maps
  2364. {
  2365. return nullptr;
  2366. }
  2367. return map;
  2368. }
  2369. // explicitly instantiate template
  2370. template FunctionBody::StatementMap *
  2371. FunctionBody::GetNextNonSubexpressionStatementMap<FunctionBody::ArenaStatementMapList>(FunctionBody::ArenaStatementMapList *statementMapList, int & startingAtIndex);
  2372. template FunctionBody::StatementMap *
  2373. FunctionBody::GetNextNonSubexpressionStatementMap<FunctionBody::StatementMapList>(FunctionBody::StatementMapList *statementMapList, int & startingAtIndex);
  2374. /* static */ FunctionBody::StatementMap * FunctionBody::GetPrevNonSubexpressionStatementMap(StatementMapList *statementMapList, int & startingAtIndex)
  2375. {
  2376. AssertMsg(statementMapList != nullptr, "Must have valid statementMapList to execute");
  2377. StatementMap *map = statementMapList->Item(startingAtIndex);
  2378. while (startingAtIndex && map->isSubexpression)
  2379. {
  2380. map = statementMapList->Item(--startingAtIndex);
  2381. }
  2382. if (map->isSubexpression) // Didn't find any non inner maps
  2383. {
  2384. return nullptr;
  2385. }
  2386. return map;
  2387. }
  2388. void ParseableFunctionInfo::SetSourceInfo(uint sourceIndex, ParseNodePtr node, bool isEval, bool isDynamicFunction)
  2389. {
  2390. if (!m_utf8SourceHasBeenSet)
  2391. {
  2392. this->m_sourceIndex = sourceIndex;
  2393. this->m_cchStartOffset = node->ichMin;
  2394. this->m_cchLength = node->LengthInCodepoints();
  2395. this->m_lineNumber = node->sxFnc.lineNumber;
  2396. this->m_columnNumber = node->sxFnc.columnNumber;
  2397. this->m_isEval = isEval;
  2398. this->m_isDynamicFunction = isDynamicFunction;
  2399. // It would have been better if we detect and reject large source buffer earlier before parsing
  2400. size_t cbMin = node->sxFnc.cbMin;
  2401. size_t lengthInBytes = node->sxFnc.LengthInBytes();
  2402. if (cbMin > UINT_MAX || lengthInBytes > UINT_MAX)
  2403. {
  2404. Js::Throw::OutOfMemory();
  2405. }
  2406. this->m_cbStartOffset = (uint)cbMin;
  2407. this->m_cbLength = (uint)lengthInBytes;
  2408. Assert(this->m_utf8SourceInfo != nullptr);
  2409. this->m_utf8SourceHasBeenSet = true;
  2410. if (this->IsFunctionBody())
  2411. {
  2412. this->GetFunctionBody()->FinishSourceInfo();
  2413. }
  2414. }
  2415. #if DBG
  2416. else
  2417. {
  2418. AssertMsg(this->m_sourceIndex == sourceIndex, "Mismatched source index");
  2419. if (!this->GetIsGlobalFunc())
  2420. {
  2421. // In the global function case with a @cc_on, we modify some of these values so it might
  2422. // not match on reparse (see ParseableFunctionInfo::Parse()).
  2423. AssertMsg(this->StartOffset() == node->sxFnc.cbMin, "Mismatched source start offset");
  2424. AssertMsg(this->m_cchStartOffset == node->ichMin, "Mismatched source character start offset");
  2425. AssertMsg(this->m_cchLength == node->LengthInCodepoints(), "Mismatched source length");
  2426. AssertMsg(this->LengthInBytes() == node->sxFnc.LengthInBytes(), "Mismatched source encoded byte length");
  2427. }
  2428. AssertMsg(this->m_isEval == isEval, "Mismatched source type");
  2429. AssertMsg(this->m_isDynamicFunction == isDynamicFunction, "Mismatch source type");
  2430. }
  2431. #endif
  2432. #if DBG_DUMP
  2433. if (PHASE_TRACE1(Js::FunctionSourceInfoParsePhase))
  2434. {
  2435. Assert(this->GetFunctionInfo()->HasBody());
  2436. if (this->IsFunctionBody())
  2437. {
  2438. FunctionBody* functionBody = this->GetFunctionBody();
  2439. Assert( functionBody != nullptr );
  2440. functionBody->PrintStatementSourceLineFromStartOffset(functionBody->StartInDocument());
  2441. Output::Flush();
  2442. }
  2443. }
  2444. #endif
  2445. }
  2446. void ParseableFunctionInfo::SetSourceInfo(uint sourceIndex)
  2447. {
  2448. // TODO (michhol): how do we want to handle wasm source?
  2449. if (!m_utf8SourceHasBeenSet)
  2450. {
  2451. this->m_sourceIndex = sourceIndex;
  2452. this->m_cchStartOffset = 0;
  2453. this->m_cchLength = 0;
  2454. this->m_lineNumber = 0;
  2455. this->m_columnNumber = 0;
  2456. this->m_cbStartOffset = 0;
  2457. this->m_cbLength = 0;
  2458. this->m_utf8SourceHasBeenSet = true;
  2459. if (this->IsFunctionBody())
  2460. {
  2461. this->GetFunctionBody()->FinishSourceInfo();
  2462. }
  2463. }
  2464. #if DBG
  2465. else
  2466. {
  2467. AssertMsg(this->m_sourceIndex == sourceIndex, "Mismatched source index");
  2468. }
  2469. #endif
  2470. }
  2471. bool FunctionBody::Is(void* ptr)
  2472. {
  2473. if(!ptr)
  2474. {
  2475. return false;
  2476. }
  2477. return VirtualTableInfo<FunctionBody>::HasVirtualTable(ptr);
  2478. }
  2479. bool FunctionBody::HasLineBreak() const
  2480. {
  2481. return this->HasLineBreak(this->StartOffset(), this->m_cchStartOffset + this->m_cchLength);
  2482. }
  2483. bool FunctionBody::HasLineBreak(charcount_t start, charcount_t end) const
  2484. {
  2485. if (start > end) return false;
  2486. charcount_t cchLength = end - start;
  2487. if (start < this->m_cchStartOffset || cchLength > this->m_cchLength) return false;
  2488. LPCUTF8 src = this->GetSource(_u("FunctionBody::HasLineBreak"));
  2489. LPCUTF8 last = src + this->LengthInBytes();
  2490. size_t offset = this->LengthInBytes() == this->m_cchLength ?
  2491. start - this->m_cchStartOffset :
  2492. utf8::CharacterIndexToByteIndex(src, this->LengthInBytes(), start - this->m_cchStartOffset, utf8::doAllowThreeByteSurrogates);
  2493. src = src + offset;
  2494. utf8::DecodeOptions options = utf8::doAllowThreeByteSurrogates;
  2495. for (charcount_t cch = cchLength; cch > 0; --cch)
  2496. {
  2497. switch (utf8::Decode(src, last, options))
  2498. {
  2499. case '\r':
  2500. case '\n':
  2501. case 0x2028:
  2502. case 0x2029:
  2503. return true;
  2504. }
  2505. }
  2506. return false;
  2507. }
  2508. FunctionBody::StatementMap* FunctionBody::GetMatchingStatementMapFromByteCode(int byteCodeOffset, bool ignoreSubexpressions /* = false */)
  2509. {
  2510. StatementMapList * pStatementMaps = this->GetStatementMaps();
  2511. if (pStatementMaps)
  2512. {
  2513. Assert(m_sourceInfo.pSpanSequence == nullptr);
  2514. for (int index = 0; index < pStatementMaps->Count(); index++)
  2515. {
  2516. FunctionBody::StatementMap* pStatementMap = pStatementMaps->Item(index);
  2517. if (!(ignoreSubexpressions && pStatementMap->isSubexpression) && pStatementMap->byteCodeSpan.Includes(byteCodeOffset))
  2518. {
  2519. return pStatementMap;
  2520. }
  2521. }
  2522. }
  2523. return nullptr;
  2524. }
  2525. // Returns the StatementMap for the offset.
  2526. // 1. Current statementMap if bytecodeoffset falls within bytecode's span
  2527. // 2. Previous if the bytecodeoffset is in between previous's end to current's begin
  2528. FunctionBody::StatementMap* FunctionBody::GetEnclosingStatementMapFromByteCode(int byteCodeOffset, bool ignoreSubexpressions /* = false */)
  2529. {
  2530. int index = GetEnclosingStatementIndexFromByteCode(byteCodeOffset, ignoreSubexpressions);
  2531. if (index != -1)
  2532. {
  2533. return this->GetStatementMaps()->Item(index);
  2534. }
  2535. return nullptr;
  2536. }
  2537. // Returns the index of StatementMap for
  2538. // 1. Current statementMap if bytecodeoffset falls within bytecode's span
  2539. // 2. Previous if the bytecodeoffset is in between previous's end to current's begin
  2540. // 3. -1 of the failures.
  2541. int FunctionBody::GetEnclosingStatementIndexFromByteCode(int byteCodeOffset, bool ignoreSubexpressions /* = false */)
  2542. {
  2543. StatementMapList * pStatementMaps = this->GetStatementMaps();
  2544. if (pStatementMaps == nullptr)
  2545. {
  2546. // e.g. internal library.
  2547. return -1;
  2548. }
  2549. Assert(m_sourceInfo.pSpanSequence == nullptr);
  2550. for (int index = 0; index < pStatementMaps->Count(); index++)
  2551. {
  2552. FunctionBody::StatementMap* pStatementMap = pStatementMaps->Item(index);
  2553. if (!(ignoreSubexpressions && pStatementMap->isSubexpression) && pStatementMap->byteCodeSpan.Includes(byteCodeOffset))
  2554. {
  2555. return index;
  2556. }
  2557. else if (!pStatementMap->isSubexpression && byteCodeOffset < pStatementMap->byteCodeSpan.begin) // We always ignore sub expressions when checking if we went too far
  2558. {
  2559. return index > 0 ? index - 1 : 0;
  2560. }
  2561. }
  2562. return pStatementMaps->Count() - 1;
  2563. }
  2564. // In some cases in legacy mode, due to the state scriptContext->windowIdList, the parser might not detect an eval call in the first parse but do so in the reparse
  2565. // This fixes up the state at the start of reparse
  2566. void FunctionBody::SaveState(ParseNodePtr pnode)
  2567. {
  2568. Assert(!this->IsReparsed());
  2569. this->SetChildCallsEval(!!pnode->sxFnc.ChildCallsEval());
  2570. this->SetCallsEval(!!pnode->sxFnc.CallsEval());
  2571. this->SetHasReferenceableBuiltInArguments(!!pnode->sxFnc.HasReferenceableBuiltInArguments());
  2572. }
  2573. void FunctionBody::RestoreState(ParseNodePtr pnode)
  2574. {
  2575. Assert(this->IsReparsed());
  2576. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2577. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2578. #endif
  2579. if(!!pnode->sxFnc.ChildCallsEval() != this->GetChildCallsEval())
  2580. {
  2581. OUTPUT_VERBOSE_TRACE(Js::DebuggerPhase, _u("Child calls eval is different on debug reparse: %s(%s)\n"), this->GetExternalDisplayName(), this->GetDebugNumberSet(debugStringBuffer));
  2582. }
  2583. if(!!pnode->sxFnc.CallsEval() != this->GetCallsEval())
  2584. {
  2585. OUTPUT_VERBOSE_TRACE(Js::DebuggerPhase, _u("Calls eval is different on debug reparse: %s(%s)\n"), this->GetExternalDisplayName(), this->GetDebugNumberSet(debugStringBuffer));
  2586. }
  2587. if(!!pnode->sxFnc.HasReferenceableBuiltInArguments() != this->HasReferenceableBuiltInArguments())
  2588. {
  2589. OUTPUT_VERBOSE_TRACE(Js::DebuggerPhase, _u("Referenceable Built in args is different on debug reparse: %s(%s)\n"), this->GetExternalDisplayName(), this->GetDebugNumberSet(debugStringBuffer));
  2590. }
  2591. pnode->sxFnc.SetChildCallsEval(this->GetChildCallsEval());
  2592. pnode->sxFnc.SetCallsEval(this->GetCallsEval());
  2593. pnode->sxFnc.SetHasReferenceableBuiltInArguments(this->HasReferenceableBuiltInArguments());
  2594. }
  2595. // Retrieves statement map for given byte code offset.
  2596. // Parameters:
  2597. // - sourceOffset: byte code offset to get map for.
  2598. // - mapIndex: if not NULL, receives the index of found map.
  2599. FunctionBody::StatementMap* FunctionBody::GetMatchingStatementMapFromSource(int sourceOffset, int* pMapIndex /* = nullptr */)
  2600. {
  2601. StatementMapList * pStatementMaps = this->GetStatementMaps();
  2602. if (pStatementMaps && pStatementMaps->Count() > 0)
  2603. {
  2604. Assert(m_sourceInfo.pSpanSequence == nullptr);
  2605. for (int index = pStatementMaps->Count() - 1; index >= 0; index--)
  2606. {
  2607. FunctionBody::StatementMap* pStatementMap = pStatementMaps->Item(index);
  2608. if (!pStatementMap->isSubexpression && pStatementMap->sourceSpan.Includes(sourceOffset))
  2609. {
  2610. if (pMapIndex)
  2611. {
  2612. *pMapIndex = index;
  2613. }
  2614. return pStatementMap;
  2615. }
  2616. }
  2617. }
  2618. if (pMapIndex)
  2619. {
  2620. *pMapIndex = 0;
  2621. }
  2622. return nullptr;
  2623. }
  2624. //
  2625. // The function determine the line and column for a bytecode offset within the current script buffer.
  2626. //
  2627. bool FunctionBody::GetLineCharOffset(int byteCodeOffset, ULONG* _line, LONG* _charOffset, bool canAllocateLineCache /*= true*/)
  2628. {
  2629. Assert(!this->GetUtf8SourceInfo()->GetIsLibraryCode());
  2630. int startCharOfStatement = this->m_cchStartOffset; // Default to the start of this function
  2631. if (m_sourceInfo.pSpanSequence)
  2632. {
  2633. SmallSpanSequenceIter iter;
  2634. m_sourceInfo.pSpanSequence->Reset(iter);
  2635. StatementData data;
  2636. if (m_sourceInfo.pSpanSequence->GetMatchingStatementFromBytecode(byteCodeOffset, iter, data)
  2637. && EndsAfter(data.sourceBegin))
  2638. {
  2639. startCharOfStatement = data.sourceBegin;
  2640. }
  2641. }
  2642. else
  2643. {
  2644. Js::FunctionBody::StatementMap* map = this->GetEnclosingStatementMapFromByteCode(byteCodeOffset, false);
  2645. if (map && EndsAfter(map->sourceSpan.begin))
  2646. {
  2647. startCharOfStatement = map->sourceSpan.begin;
  2648. }
  2649. }
  2650. return this->GetLineCharOffsetFromStartChar(startCharOfStatement, _line, _charOffset, canAllocateLineCache);
  2651. }
  2652. bool FunctionBody::GetLineCharOffsetFromStartChar(int startCharOfStatement, ULONG* _line, LONG* _charOffset, bool canAllocateLineCache /*= true*/)
  2653. {
  2654. Assert(!this->GetUtf8SourceInfo()->GetIsLibraryCode() || this->IsJsBuiltInCode());
  2655. // The following adjusts for where the script is within the document
  2656. ULONG line = this->GetHostStartLine();
  2657. charcount_t column = 0;
  2658. ULONG lineCharOffset = 0;
  2659. charcount_t lineByteOffset = 0;
  2660. if (startCharOfStatement > 0)
  2661. {
  2662. bool doSlowLookup = !canAllocateLineCache;
  2663. if (canAllocateLineCache)
  2664. {
  2665. HRESULT hr = this->GetUtf8SourceInfo()->EnsureLineOffsetCacheNoThrow();
  2666. if (FAILED(hr))
  2667. {
  2668. if (hr != E_OUTOFMEMORY)
  2669. {
  2670. Assert(hr == E_ABORT); // The only other possible error we know about is ScriptAbort from QueryContinue.
  2671. return false;
  2672. }
  2673. // Clear the cache so it is not used.
  2674. this->GetUtf8SourceInfo()->DeleteLineOffsetCache();
  2675. // We can try and do the slow lookup below
  2676. doSlowLookup = true;
  2677. }
  2678. }
  2679. charcount_t cacheLine = 0;
  2680. this->GetUtf8SourceInfo()->GetLineInfoForCharPosition(startCharOfStatement, &cacheLine, &column, &lineByteOffset, doSlowLookup);
  2681. // Update the tracking variables to jump to the line position (only need to jump if not on the first line).
  2682. if (cacheLine > 0)
  2683. {
  2684. line += cacheLine;
  2685. lineCharOffset = startCharOfStatement - column;
  2686. }
  2687. }
  2688. if (this->GetSourceContextInfo()->IsDynamic() && this->m_isDynamicFunction)
  2689. {
  2690. line -= JavascriptFunction::numberLinesPrependedToAnonymousFunction;
  2691. }
  2692. if(_line)
  2693. {
  2694. *_line = line;
  2695. }
  2696. if(_charOffset)
  2697. {
  2698. *_charOffset = column;
  2699. // If we are at the beginning of the host code, adjust the offset based on the host provided offset
  2700. if (this->GetHostSrcInfo()->dlnHost == line)
  2701. {
  2702. *_charOffset += (LONG)this->GetHostStartColumn();
  2703. }
  2704. }
  2705. return true;
  2706. }
  2707. bool FunctionBody::GetStatementIndexAndLengthAt(int byteCodeOffset, UINT32* statementIndex, UINT32* statementLength)
  2708. {
  2709. Assert(statementIndex != nullptr);
  2710. Assert(statementLength != nullptr);
  2711. Assert(this->IsInDebugMode());
  2712. StatementMap * statement = GetEnclosingStatementMapFromByteCode(byteCodeOffset, false);
  2713. Assert(statement != nullptr);
  2714. // Bailout if we are unable to find a statement.
  2715. // We shouldn't be missing these when a debugger is attached but we don't want to AV on retail builds.
  2716. if (statement == nullptr)
  2717. {
  2718. return false;
  2719. }
  2720. Assert(m_utf8SourceInfo);
  2721. const SRCINFO * srcInfo = GetUtf8SourceInfo()->GetSrcInfo();
  2722. // Offset from the beginning of the document minus any host-supplied source characters.
  2723. // Host supplied characters are inserted (for example) around onload:
  2724. // onload="foo('somestring', 0)" -> function onload(event).{.foo('somestring', 0).}
  2725. ULONG offsetFromDocumentBegin = srcInfo ? srcInfo->ulCharOffset - srcInfo->ichMinHost : 0;
  2726. *statementIndex = statement->sourceSpan.Begin() + offsetFromDocumentBegin;
  2727. *statementLength = statement->sourceSpan.End() - statement->sourceSpan.Begin();
  2728. return true;
  2729. }
  2730. void FunctionBody::RecordFrameDisplayRegister(RegSlot slot)
  2731. {
  2732. AssertMsg(slot != 0, "The assumption that the Frame Display Register cannot be at the 0 slot is wrong.");
  2733. SetFrameDisplayRegister(slot);
  2734. }
  2735. void FunctionBody::RecordObjectRegister(RegSlot slot)
  2736. {
  2737. AssertMsg(slot != 0, "The assumption that the Object Register cannot be at the 0 slot is wrong.");
  2738. SetObjectRegister(slot);
  2739. }
  2740. Js::RootObjectBase * FunctionBody::GetRootObject() const
  2741. {
  2742. // Safe to be used by the JIT thread
  2743. Assert(this->GetConstTable() != nullptr);
  2744. return (Js::RootObjectBase *)PointerValue(this->GetConstTable()[Js::FunctionBody::RootObjectRegSlot - FunctionBody::FirstRegSlot]);
  2745. }
  2746. Js::RootObjectBase * FunctionBody::LoadRootObject() const
  2747. {
  2748. if (this->IsES6ModuleCode() || this->GetModuleID() == kmodGlobal)
  2749. {
  2750. return JavascriptOperators::OP_LdRoot(this->GetScriptContext());
  2751. }
  2752. return JavascriptOperators::GetModuleRoot(this->GetModuleID(), this->GetScriptContext());
  2753. }
  2754. #if ENABLE_NATIVE_CODEGEN
  2755. FunctionEntryPointInfo * FunctionBody::GetEntryPointFromNativeAddress(DWORD_PTR codeAddress)
  2756. {
  2757. FunctionEntryPointInfo * entryPoint = nullptr;
  2758. this->MapEntryPoints([&entryPoint, &codeAddress](int index, FunctionEntryPointInfo * currentEntryPoint)
  2759. {
  2760. // We need to do a second check for IsNativeCode because the entry point could be in the process of
  2761. // being recorded on the background thread
  2762. if (currentEntryPoint->IsInNativeAddressRange(codeAddress))
  2763. {
  2764. entryPoint = currentEntryPoint;
  2765. }
  2766. });
  2767. return entryPoint;
  2768. }
  2769. LoopEntryPointInfo * FunctionBody::GetLoopEntryPointInfoFromNativeAddress(DWORD_PTR codeAddress, uint loopNum) const
  2770. {
  2771. LoopEntryPointInfo * entryPoint = nullptr;
  2772. LoopHeader * loopHeader = this->GetLoopHeader(loopNum);
  2773. Assert(loopHeader);
  2774. loopHeader->MapEntryPoints([&](int index, LoopEntryPointInfo * currentEntryPoint)
  2775. {
  2776. if (currentEntryPoint->IsCodeGenDone() &&
  2777. codeAddress >= currentEntryPoint->GetNativeAddress() &&
  2778. codeAddress < currentEntryPoint->GetNativeAddress() + currentEntryPoint->GetCodeSize())
  2779. {
  2780. entryPoint = currentEntryPoint;
  2781. }
  2782. });
  2783. return entryPoint;
  2784. }
  2785. int FunctionBody::GetStatementIndexFromNativeOffset(SmallSpanSequence *pThrowSpanSequence, uint32 nativeOffset)
  2786. {
  2787. int statementIndex = -1;
  2788. if (pThrowSpanSequence)
  2789. {
  2790. SmallSpanSequenceIter iter;
  2791. StatementData tmpData;
  2792. if (pThrowSpanSequence->GetMatchingStatementFromBytecode(nativeOffset, iter, tmpData))
  2793. {
  2794. statementIndex = tmpData.sourceBegin; // sourceBegin represents statementIndex here
  2795. }
  2796. else
  2797. {
  2798. // If nativeOffset falls on the last span, GetMatchingStatement would miss it because SmallSpanSequence
  2799. // does not know about the last span end. Since we checked that codeAddress is within our range,
  2800. // we can safely consider it matches the last span.
  2801. statementIndex = iter.accumulatedSourceBegin;
  2802. }
  2803. }
  2804. return statementIndex;
  2805. }
  2806. int FunctionBody::GetStatementIndexFromNativeAddress(SmallSpanSequence *pThrowSpanSequence, DWORD_PTR codeAddress, DWORD_PTR nativeBaseAddress)
  2807. {
  2808. uint32 nativeOffset = (uint32)(codeAddress - nativeBaseAddress);
  2809. return GetStatementIndexFromNativeOffset(pThrowSpanSequence, nativeOffset);
  2810. }
  2811. #endif
  2812. BOOL FunctionBody::GetMatchingStatementMap(StatementData &data, int statementIndex, FunctionBody *inlinee)
  2813. {
  2814. SourceInfo *si = &this->m_sourceInfo;
  2815. if (inlinee)
  2816. {
  2817. si = &inlinee->m_sourceInfo;
  2818. Assert(si);
  2819. }
  2820. if (statementIndex >= 0)
  2821. {
  2822. SmallSpanSequence *pSpanSequence = si->pSpanSequence;
  2823. if (pSpanSequence)
  2824. {
  2825. SmallSpanSequenceIter iter;
  2826. pSpanSequence->Reset(iter);
  2827. if (pSpanSequence->Item(statementIndex, iter, data))
  2828. {
  2829. return TRUE;
  2830. }
  2831. }
  2832. else
  2833. {
  2834. StatementMapList* pStatementMaps = GetStatementMaps();
  2835. Assert(pStatementMaps);
  2836. if (statementIndex >= pStatementMaps->Count())
  2837. {
  2838. return FALSE;
  2839. }
  2840. data.sourceBegin = pStatementMaps->Item(statementIndex)->sourceSpan.begin;
  2841. data.bytecodeBegin = pStatementMaps->Item(statementIndex)->byteCodeSpan.begin;
  2842. return TRUE;
  2843. }
  2844. }
  2845. return FALSE;
  2846. }
  2847. void FunctionBody::FindClosestStatements(int32 characterOffset, StatementLocation *firstStatementLocation, StatementLocation *secondStatementLocation)
  2848. {
  2849. auto statementMaps = this->GetStatementMaps();
  2850. if (statementMaps)
  2851. {
  2852. for(int i = 0; i < statementMaps->Count(); i++)
  2853. {
  2854. regex::Interval* pSourceSpan = &(statementMaps->Item(i)->sourceSpan);
  2855. if (FunctionBody::IsDummyGlobalRetStatement(pSourceSpan))
  2856. {
  2857. // Workaround for handling global return, which is an empty range.
  2858. continue;
  2859. }
  2860. if (pSourceSpan->begin < characterOffset
  2861. && (firstStatementLocation->function == nullptr || firstStatementLocation->statement.begin < pSourceSpan->begin))
  2862. {
  2863. firstStatementLocation->function = this;
  2864. firstStatementLocation->statement = *pSourceSpan;
  2865. firstStatementLocation->bytecodeSpan = statementMaps->Item(i)->byteCodeSpan;
  2866. }
  2867. else if (pSourceSpan->begin >= characterOffset
  2868. && (secondStatementLocation->function == nullptr || secondStatementLocation->statement.begin > pSourceSpan->begin))
  2869. {
  2870. secondStatementLocation->function = this;
  2871. secondStatementLocation->statement = *pSourceSpan;
  2872. secondStatementLocation->bytecodeSpan = statementMaps->Item(i)->byteCodeSpan;
  2873. }
  2874. }
  2875. }
  2876. }
  2877. #if ENABLE_NATIVE_CODEGEN
  2878. BOOL FunctionBody::GetMatchingStatementMapFromNativeAddress(DWORD_PTR codeAddress, StatementData &data, uint loopNum, FunctionBody *inlinee /* = nullptr */)
  2879. {
  2880. SmallSpanSequence * spanSequence = nullptr;
  2881. DWORD_PTR nativeBaseAddress = NULL;
  2882. EntryPointInfo * entryPoint;
  2883. if (loopNum == -1)
  2884. {
  2885. entryPoint = GetEntryPointFromNativeAddress(codeAddress);
  2886. }
  2887. else
  2888. {
  2889. entryPoint = GetLoopEntryPointInfoFromNativeAddress(codeAddress, loopNum);
  2890. }
  2891. if (entryPoint != nullptr)
  2892. {
  2893. spanSequence = entryPoint->GetNativeThrowSpanSequence();
  2894. nativeBaseAddress = entryPoint->GetNativeAddress();
  2895. }
  2896. int statementIndex = GetStatementIndexFromNativeAddress(spanSequence, codeAddress, nativeBaseAddress);
  2897. return GetMatchingStatementMap(data, statementIndex, inlinee);
  2898. }
  2899. BOOL FunctionBody::GetMatchingStatementMapFromNativeOffset(DWORD_PTR codeAddress, uint32 offset, StatementData &data, uint loopNum, FunctionBody *inlinee /* = nullptr */)
  2900. {
  2901. EntryPointInfo * entryPoint;
  2902. if (loopNum == -1)
  2903. {
  2904. entryPoint = GetEntryPointFromNativeAddress(codeAddress);
  2905. }
  2906. else
  2907. {
  2908. entryPoint = GetLoopEntryPointInfoFromNativeAddress(codeAddress, loopNum);
  2909. }
  2910. SmallSpanSequence *spanSequence = entryPoint ? entryPoint->GetNativeThrowSpanSequence() : nullptr;
  2911. int statementIndex = GetStatementIndexFromNativeOffset(spanSequence, offset);
  2912. return GetMatchingStatementMap(data, statementIndex, inlinee);
  2913. }
  2914. #endif
  2915. #if ENABLE_PROFILE_INFO
  2916. void FunctionBody::LoadDynamicProfileInfo()
  2917. {
  2918. SourceDynamicProfileManager * sourceDynamicProfileManager = GetSourceContextInfo()->sourceDynamicProfileManager;
  2919. if (sourceDynamicProfileManager != nullptr)
  2920. {
  2921. this->dynamicProfileInfo = sourceDynamicProfileManager->GetDynamicProfileInfo(this);
  2922. #if DBG_DUMP
  2923. if(this->dynamicProfileInfo)
  2924. {
  2925. if (Configuration::Global.flags.Dump.IsEnabled(DynamicProfilePhase, this->GetSourceContextId(), this->GetLocalFunctionId()))
  2926. {
  2927. Output::Print(_u("Loaded:"));
  2928. this->dynamicProfileInfo->Dump(this);
  2929. }
  2930. }
  2931. #endif
  2932. }
  2933. #ifdef DYNAMIC_PROFILE_MUTATOR
  2934. DynamicProfileMutator::Mutate(this);
  2935. #endif
  2936. }
  2937. bool FunctionBody::NeedEnsureDynamicProfileInfo() const
  2938. {
  2939. // Only need to ensure dynamic profile if we don't already have link up the dynamic profile info
  2940. // and dynamic profile collection is enabled
  2941. return
  2942. !this->m_isFromNativeCodeModule &&
  2943. !this->HasExecutionDynamicProfileInfo() &&
  2944. DynamicProfileInfo::IsEnabled(this);
  2945. }
  2946. DynamicProfileInfo * FunctionBody::EnsureDynamicProfileInfo()
  2947. {
  2948. if (this->NeedEnsureDynamicProfileInfo())
  2949. {
  2950. m_scriptContext->AddDynamicProfileInfo(this, this->dynamicProfileInfo);
  2951. Assert(!this->HasExecutionDynamicProfileInfo());
  2952. this->hasExecutionDynamicProfileInfo = true;
  2953. }
  2954. return this->dynamicProfileInfo;
  2955. }
  2956. DynamicProfileInfo* FunctionBody::AllocateDynamicProfile()
  2957. {
  2958. return DynamicProfileInfo::New(m_scriptContext->GetRecycler(), this);
  2959. }
  2960. #endif
  2961. BOOL FunctionBody::IsNativeOriginalEntryPoint() const
  2962. {
  2963. #if ENABLE_NATIVE_CODEGEN
  2964. JavascriptMethod originalEntryPoint = this->GetOriginalEntryPoint_Unchecked();
  2965. return
  2966. #if defined(_CONTROL_FLOW_GUARD) && !defined(_M_ARM)
  2967. (
  2968. #if ENABLE_OOP_NATIVE_CODEGEN
  2969. JITManager::GetJITManager()->IsOOPJITEnabled()
  2970. ? JITThunkEmitter<SectionAllocWrapper>::IsInThunk(this->GetScriptContext()->GetThreadContext()->GetJITThunkStartAddr(), (uintptr_t)originalEntryPoint)
  2971. :
  2972. #endif
  2973. this->GetScriptContext()->GetThreadContext()->GetJITThunkEmitter()->IsInThunk((uintptr_t)originalEntryPoint)
  2974. ) ||
  2975. #endif
  2976. this->GetScriptContext()->IsNativeAddress((void*)originalEntryPoint);
  2977. #else
  2978. return false;
  2979. #endif
  2980. }
  2981. bool FunctionBody::IsSimpleJitOriginalEntryPoint() const
  2982. {
  2983. const FunctionEntryPointInfo *const simpleJitEntryPointInfo = GetSimpleJitEntryPointInfo();
  2984. return simpleJitEntryPointInfo && simpleJitEntryPointInfo->GetNativeEntrypoint() == GetOriginalEntryPoint_Unchecked();
  2985. }
  2986. void FunctionProxy::Finalize(bool isShutdown)
  2987. {
  2988. this->CleanupFunctionProxyCounters();
  2989. }
  2990. #if DBG
  2991. bool FunctionBody::HasValidSourceInfo()
  2992. {
  2993. SourceContextInfo* sourceContextInfo;
  2994. if (m_scriptContext->GetSourceContextInfoMap())
  2995. {
  2996. if(m_scriptContext->GetSourceContextInfoMap()->TryGetValue(this->GetHostSourceContext(), &sourceContextInfo) &&
  2997. sourceContextInfo == this->GetSourceContextInfo())
  2998. {
  2999. return true;
  3000. }
  3001. }
  3002. Assert(this->IsDynamicScript());
  3003. if(m_scriptContext->GetDynamicSourceContextInfoMap())
  3004. {
  3005. if(m_scriptContext->GetDynamicSourceContextInfoMap()->TryGetValue(this->GetSourceContextInfo()->hash, &sourceContextInfo) &&
  3006. sourceContextInfo == this->GetSourceContextInfo())
  3007. {
  3008. return true;
  3009. }
  3010. }
  3011. // The SourceContextInfo will not be added to the dynamicSourceContextInfoMap, if they are host provided dynamic code. But they are valid source context info
  3012. if (this->GetSourceContextInfo()->isHostDynamicDocument)
  3013. {
  3014. return true;
  3015. }
  3016. return m_scriptContext->IsNoContextSourceContextInfo(this->GetSourceContextInfo());
  3017. }
  3018. // originalEntryPoint: DefaultDeferredParsingThunk, DefaultDeferredDeserializeThunk, DefaultEntryThunk, dynamic interpreter thunk or native entry point
  3019. // directEntryPoint:
  3020. // if (!profiled) - DefaultDeferredParsingThunk, DefaultDeferredDeserializeThunk, DefaultEntryThunk, CheckCodeGenThunk,
  3021. // dynamic interpreter thunk, native entry point
  3022. // if (profiling) - ProfileDeferredParsingThunk, ProfileDeferredDeserializeThunk, ProfileEntryThunk, CheckCodeGenThunk
  3023. bool FunctionProxy::HasValidNonProfileEntryPoint() const
  3024. {
  3025. JavascriptMethod directEntryPoint = this->GetDefaultEntryPointInfo()->jsMethod;
  3026. JavascriptMethod originalEntryPoint = this->GetOriginalEntryPoint_Unchecked();
  3027. // Check the direct entry point to see if it is codegen thunk
  3028. // if it is not, the background codegen thread has updated both original entry point and direct entry point
  3029. // and they should still match, same as cases other then code gen
  3030. return IsIntermediateCodeGenThunk(directEntryPoint) || originalEntryPoint == directEntryPoint
  3031. #if ENABLE_PROFILE_INFO
  3032. || (directEntryPoint == DynamicProfileInfo::EnsureDynamicProfileInfoThunk &&
  3033. this->IsFunctionBody() && this->GetFunctionBody()->IsNativeOriginalEntryPoint())
  3034. #ifdef ENABLE_WASM
  3035. || (GetFunctionBody()->IsWasmFunction() &&
  3036. (directEntryPoint == WasmLibrary::WasmDeferredParseInternalThunk || directEntryPoint == WasmLibrary::WasmLazyTrapCallback))
  3037. #endif
  3038. #ifdef ASMJS_PLAT
  3039. || (GetFunctionBody()->GetIsAsmJsFunction() && directEntryPoint == AsmJsDefaultEntryThunk)
  3040. || IsAsmJsCodeGenThunk(directEntryPoint)
  3041. #endif
  3042. #endif
  3043. ;
  3044. }
  3045. #if defined(ENABLE_SCRIPT_PROFILING) || defined(ENABLE_SCRIPT_DEBUGGING)
  3046. bool FunctionProxy::HasValidProfileEntryPoint() const
  3047. {
  3048. JavascriptMethod directEntryPoint = this->GetDefaultEntryPointInfo()->jsMethod;
  3049. JavascriptMethod originalEntryPoint = this->GetOriginalEntryPoint_Unchecked();
  3050. if (originalEntryPoint == DefaultDeferredParsingThunk)
  3051. {
  3052. return directEntryPoint == ProfileDeferredParsingThunk;
  3053. }
  3054. if (originalEntryPoint == DefaultDeferredDeserializeThunk)
  3055. {
  3056. return directEntryPoint == ProfileDeferredDeserializeThunk;
  3057. }
  3058. if (!this->IsFunctionBody())
  3059. {
  3060. return false;
  3061. }
  3062. #if ENABLE_PROFILE_INFO
  3063. FunctionBody * functionBody = this->GetFunctionBody();
  3064. if (functionBody->IsInterpreterThunk() || functionBody->IsSimpleJitOriginalEntryPoint())
  3065. {
  3066. return directEntryPoint == ProfileEntryThunk || IsIntermediateCodeGenThunk(directEntryPoint);
  3067. }
  3068. #if ENABLE_NATIVE_CODEGEN
  3069. // In the profiler mode, the EnsureDynamicProfileInfoThunk is valid as we would be assigning to appropriate thunk when that thunk called.
  3070. return functionBody->IsNativeOriginalEntryPoint() &&
  3071. (directEntryPoint == DynamicProfileInfo::EnsureDynamicProfileInfoThunk || directEntryPoint == ProfileEntryThunk);
  3072. #endif
  3073. #else
  3074. return true;
  3075. #endif
  3076. }
  3077. #endif
  3078. bool FunctionProxy::HasValidEntryPoint() const
  3079. {
  3080. if (this->IsWasmFunction() ||
  3081. (!m_scriptContext->HadProfiled() &&
  3082. !(this->m_scriptContext->IsScriptContextInDebugMode() && m_scriptContext->IsExceptionWrapperForBuiltInsEnabled())))
  3083. {
  3084. return this->HasValidNonProfileEntryPoint();
  3085. }
  3086. #if defined(ENABLE_SCRIPT_PROFILING) || defined(ENABLE_SCRIPT_DEBUGGING)
  3087. if (m_scriptContext->IsProfiling())
  3088. {
  3089. return this->HasValidProfileEntryPoint();
  3090. }
  3091. return this->HasValidNonProfileEntryPoint() || this->HasValidProfileEntryPoint();
  3092. #else
  3093. return this->HasValidNonProfileEntryPoint();
  3094. #endif
  3095. }
  3096. #endif
  3097. void ParseableFunctionInfo::SetDeferredParsingEntryPoint()
  3098. {
  3099. #if defined(ENABLE_SCRIPT_PROFILING) || defined(ENABLE_SCRIPT_DEBUGGING)
  3100. Assert(m_scriptContext->DeferredParsingThunk == ProfileDeferredParsingThunk
  3101. || m_scriptContext->DeferredParsingThunk == DefaultDeferredParsingThunk);
  3102. #else
  3103. Assert(m_scriptContext->DeferredParsingThunk == DefaultDeferredParsingThunk);
  3104. #endif
  3105. this->SetEntryPoint(this->GetDefaultEntryPointInfo(), m_scriptContext->DeferredParsingThunk);
  3106. this->SetOriginalEntryPoint(DefaultDeferredParsingThunk);
  3107. }
  3108. void ParseableFunctionInfo::SetInitialDefaultEntryPoint()
  3109. {
  3110. #if defined(ENABLE_SCRIPT_PROFILING) || defined(ENABLE_SCRIPT_DEBUGGING)
  3111. Assert(m_scriptContext->CurrentThunk == ProfileEntryThunk || m_scriptContext->CurrentThunk == DefaultEntryThunk);
  3112. Assert(this->GetOriginalEntryPoint_Unchecked() == DefaultDeferredParsingThunk ||
  3113. this->GetOriginalEntryPoint_Unchecked() == ProfileDeferredParsingThunk ||
  3114. this->GetOriginalEntryPoint_Unchecked() == DefaultDeferredDeserializeThunk ||
  3115. this->GetOriginalEntryPoint_Unchecked() == ProfileDeferredDeserializeThunk ||
  3116. this->GetOriginalEntryPoint_Unchecked() == DefaultEntryThunk ||
  3117. this->GetOriginalEntryPoint_Unchecked() == ProfileEntryThunk);
  3118. #else
  3119. Assert(m_scriptContext->CurrentThunk == DefaultEntryThunk);
  3120. Assert(this->GetOriginalEntryPoint_Unchecked() == DefaultDeferredParsingThunk ||
  3121. this->GetOriginalEntryPoint_Unchecked() == DefaultDeferredDeserializeThunk ||
  3122. this->GetOriginalEntryPoint_Unchecked() == DefaultEntryThunk);
  3123. #endif
  3124. Assert(this->m_defaultEntryPointInfo != nullptr);
  3125. // CONSIDER: we can optimize this to generate the dynamic interpreter thunk up front
  3126. // If we know that we are in the defer parsing thunk already
  3127. this->SetEntryPoint(this->GetDefaultEntryPointInfo(), m_scriptContext->CurrentThunk);
  3128. this->SetOriginalEntryPoint(DefaultEntryThunk);
  3129. }
  3130. void FunctionBody::SetCheckCodeGenEntryPoint(FunctionEntryPointInfo* entryPointInfo, JavascriptMethod entryPoint)
  3131. {
  3132. Assert(IsIntermediateCodeGenThunk(entryPoint));
  3133. Assert(
  3134. this->GetEntryPoint(entryPointInfo) == m_scriptContext->CurrentThunk ||
  3135. (entryPointInfo == this->m_defaultEntryPointInfo && this->IsInterpreterThunk()) ||
  3136. (
  3137. GetSimpleJitEntryPointInfo() &&
  3138. GetEntryPoint(entryPointInfo) == GetSimpleJitEntryPointInfo()->GetNativeEntrypoint()
  3139. ));
  3140. this->SetEntryPoint(entryPointInfo, entryPoint);
  3141. }
  3142. #if DYNAMIC_INTERPRETER_THUNK
  3143. void FunctionBody::GenerateDynamicInterpreterThunk()
  3144. {
  3145. if (this->m_dynamicInterpreterThunk == nullptr)
  3146. {
  3147. // NOTE: Etw rundown thread may be reading this->dynamicInterpreterThunk concurrently. We don't need to synchronize
  3148. // access as it is ok for etw rundown to get either null or updated new value.
  3149. if (m_isAsmJsFunction)
  3150. {
  3151. this->SetOriginalEntryPoint(this->m_scriptContext->GetNextDynamicAsmJsInterpreterThunk(&this->m_dynamicInterpreterThunk));
  3152. }
  3153. else
  3154. {
  3155. this->SetOriginalEntryPoint(this->m_scriptContext->GetNextDynamicInterpreterThunk(&this->m_dynamicInterpreterThunk));
  3156. }
  3157. if (this->m_dynamicInterpreterThunk != nullptr)
  3158. {
  3159. JS_ETW(EtwTrace::LogMethodInterpreterThunkLoadEvent(this));
  3160. }
  3161. }
  3162. else
  3163. {
  3164. this->SetOriginalEntryPoint((JavascriptMethod)InterpreterThunkEmitter::ConvertToEntryPoint(this->m_dynamicInterpreterThunk));
  3165. }
  3166. }
  3167. JavascriptMethod FunctionBody::EnsureDynamicInterpreterThunk(FunctionEntryPointInfo* entryPointInfo)
  3168. {
  3169. // This may be first call to the function, make sure we have dynamic profile info
  3170. //
  3171. // We need to ensure dynamic profile info even if we didn't generate a dynamic interpreter thunk
  3172. // This happens when we go through CheckCodeGen thunk, to DelayDynamicInterpreterThunk, to here
  3173. // but the background codegen thread updated the entry point with the native entry point.
  3174. this->EnsureDynamicProfileInfo();
  3175. Assert(HasValidEntryPoint());
  3176. if (InterpreterStackFrame::IsDelayDynamicInterpreterThunk(this->GetEntryPoint(entryPointInfo)))
  3177. {
  3178. // We are not doing code gen on this function, just change the entry point directly
  3179. Assert(InterpreterStackFrame::IsDelayDynamicInterpreterThunk(this->GetOriginalEntryPoint_Unchecked()));
  3180. GenerateDynamicInterpreterThunk();
  3181. this->SetEntryPoint(entryPointInfo, this->GetOriginalEntryPoint_Unchecked());
  3182. }
  3183. else if (this->GetEntryPoint(entryPointInfo) == ProfileEntryThunk)
  3184. {
  3185. // We are not doing codegen on this function, just change the entry point directly
  3186. // Don't replace the profile entry thunk
  3187. Assert(InterpreterStackFrame::IsDelayDynamicInterpreterThunk(this->GetOriginalEntryPoint_Unchecked()));
  3188. GenerateDynamicInterpreterThunk();
  3189. }
  3190. else if (InterpreterStackFrame::IsDelayDynamicInterpreterThunk(this->GetOriginalEntryPoint_Unchecked()))
  3191. {
  3192. JsUtil::JobProcessor * jobProcessor = this->GetScriptContext()->GetThreadContext()->GetJobProcessor();
  3193. if (jobProcessor->ProcessesInBackground())
  3194. {
  3195. JsUtil::BackgroundJobProcessor * backgroundJobProcessor = static_cast<JsUtil::BackgroundJobProcessor *>(jobProcessor);
  3196. AutoCriticalSection autocs(backgroundJobProcessor->GetCriticalSection());
  3197. // Check again under lock
  3198. if (InterpreterStackFrame::IsDelayDynamicInterpreterThunk(this->GetOriginalEntryPoint_Unchecked()))
  3199. {
  3200. // If the original entry point is DelayDynamicInterpreterThunk then there must be a version of this
  3201. // function being codegen'd.
  3202. Assert(IsIntermediateCodeGenThunk((JavascriptMethod)this->GetEntryPoint(this->GetDefaultEntryPointInfo())) || IsAsmJsCodeGenThunk((JavascriptMethod)this->GetEntryPoint(this->GetDefaultEntryPointInfo())));
  3203. GenerateDynamicInterpreterThunk();
  3204. }
  3205. }
  3206. else
  3207. {
  3208. // If the original entry point is DelayDynamicInterpreterThunk then there must be a version of this
  3209. // function being codegen'd.
  3210. Assert(IsIntermediateCodeGenThunk((JavascriptMethod)this->GetEntryPoint(this->GetDefaultEntryPointInfo())) || IsAsmJsCodeGenThunk((JavascriptMethod)this->GetEntryPoint(this->GetDefaultEntryPointInfo())));
  3211. GenerateDynamicInterpreterThunk();
  3212. }
  3213. }
  3214. return this->GetOriginalEntryPoint_Unchecked();
  3215. }
  3216. #endif
  3217. #if ENABLE_NATIVE_CODEGEN
  3218. void FunctionBody::SetNativeEntryPoint(FunctionEntryPointInfo* entryPointInfo, JavascriptMethod originalEntryPoint, JavascriptMethod directEntryPoint)
  3219. {
  3220. if(entryPointInfo->nativeEntryPointProcessed)
  3221. {
  3222. return;
  3223. }
  3224. bool isAsmJs = this->GetIsAsmjsMode();
  3225. Assert(IsIntermediateCodeGenThunk(entryPointInfo->jsMethod) || CONFIG_FLAG(Prejit) || this->m_isFromNativeCodeModule || isAsmJs);
  3226. entryPointInfo->EnsureIsReadyToCall();
  3227. // keep originalEntryPoint updated with the latest known good native entry point
  3228. if (entryPointInfo == this->GetDefaultEntryPointInfo())
  3229. {
  3230. this->SetOriginalEntryPoint(originalEntryPoint);
  3231. }
  3232. if (entryPointInfo->entryPointIndex == 0 && this->NeedEnsureDynamicProfileInfo())
  3233. {
  3234. entryPointInfo->jsMethod = DynamicProfileInfo::EnsureDynamicProfileInfoThunk;
  3235. }
  3236. else
  3237. {
  3238. entryPointInfo->jsMethod = directEntryPoint;
  3239. }
  3240. this->CaptureDynamicProfileState(entryPointInfo);
  3241. if(entryPointInfo->GetJitMode() == ExecutionMode::SimpleJit)
  3242. {
  3243. Assert(GetExecutionMode() == ExecutionMode::SimpleJit);
  3244. SetSimpleJitEntryPointInfo(entryPointInfo);
  3245. ResetSimpleJitCallCount();
  3246. }
  3247. else
  3248. {
  3249. Assert(entryPointInfo->GetJitMode() == ExecutionMode::FullJit);
  3250. Assert(isAsmJs || GetExecutionMode() == ExecutionMode::FullJit);
  3251. entryPointInfo->callsCount =
  3252. static_cast<uint8>(
  3253. min(
  3254. static_cast<uint>(static_cast<uint8>(CONFIG_FLAG(MinBailOutsBeforeRejit))) *
  3255. (Js::FunctionEntryPointInfo::GetDecrCallCountPerBailout() - 1),
  3256. 0xffu));
  3257. }
  3258. TraceExecutionMode();
  3259. JS_ETW(EtwTrace::LogMethodNativeLoadEvent(this, entryPointInfo));
  3260. #ifdef VTUNE_PROFILING
  3261. VTuneChakraProfile::LogMethodNativeLoadEvent(this, entryPointInfo);
  3262. #endif
  3263. #ifdef _M_ARM
  3264. // For ARM we need to make sure that pipeline is synchronized with memory/cache for newly jitted code.
  3265. _InstructionSynchronizationBarrier();
  3266. #endif
  3267. entryPointInfo->nativeEntryPointProcessed = true;
  3268. }
  3269. void FunctionBody::DefaultSetNativeEntryPoint(FunctionEntryPointInfo* entryPointInfo, FunctionBody * functionBody, JavascriptMethod entryPoint)
  3270. {
  3271. Assert(functionBody->m_scriptContext->CurrentThunk == DefaultEntryThunk);
  3272. functionBody->SetNativeEntryPoint(entryPointInfo, entryPoint, entryPoint);
  3273. }
  3274. void FunctionBody::ProfileSetNativeEntryPoint(FunctionEntryPointInfo* entryPointInfo, FunctionBody * functionBody, JavascriptMethod entryPoint)
  3275. {
  3276. #ifdef ENABLE_WASM
  3277. // Do not profile WebAssembly functions
  3278. if (functionBody->IsWasmFunction())
  3279. {
  3280. functionBody->SetNativeEntryPoint(entryPointInfo, entryPoint, entryPoint);
  3281. return;
  3282. }
  3283. #endif
  3284. Assert(functionBody->m_scriptContext->CurrentThunk == ProfileEntryThunk);
  3285. functionBody->SetNativeEntryPoint(entryPointInfo, entryPoint, ProfileEntryThunk);
  3286. }
  3287. Js::JavascriptMethod FunctionBody::GetLoopBodyEntryPoint(Js::LoopHeader * loopHeader, int entryPointIndex)
  3288. {
  3289. #if DBG
  3290. this->GetLoopNumber(loopHeader);
  3291. #endif
  3292. return loopHeader->GetEntryPointInfo(entryPointIndex)->jsMethod;
  3293. }
  3294. void FunctionBody::SetLoopBodyEntryPoint(Js::LoopHeader * loopHeader, EntryPointInfo* entryPointInfo, Js::JavascriptMethod entryPoint, uint loopNum)
  3295. {
  3296. #if DBG_DUMP
  3297. if (PHASE_TRACE1(Js::JITLoopBodyPhase))
  3298. {
  3299. DumpFunctionId(true);
  3300. Output::Print(_u(": %-20s LoopBody EntryPt Loop: %2d Address : %x\n"), GetDisplayName(), loopNum, entryPoint);
  3301. Output::Flush();
  3302. }
  3303. #endif
  3304. Assert(((LoopEntryPointInfo*)entryPointInfo)->loopHeader == loopHeader);
  3305. Assert(reinterpret_cast<void*>(entryPointInfo->jsMethod) == nullptr);
  3306. entryPointInfo->jsMethod = entryPoint;
  3307. ((Js::LoopEntryPointInfo*)entryPointInfo)->totalJittedLoopIterations =
  3308. static_cast<uint8>(
  3309. min(
  3310. static_cast<uint>(static_cast<uint8>(CONFIG_FLAG(MinBailOutsBeforeRejitForLoops))) *
  3311. (Js::LoopEntryPointInfo::GetDecrLoopCountPerBailout() - 1),
  3312. 0xffu));
  3313. // reset the counter to 1 less than the threshold for TJLoopBody
  3314. if (loopHeader->GetCurrentEntryPointInfo()->GetIsAsmJSFunction())
  3315. {
  3316. loopHeader->interpretCount = entryPointInfo->GetFunctionBody()->GetLoopInterpretCount(loopHeader) - 1;
  3317. }
  3318. JS_ETW(EtwTrace::LogLoopBodyLoadEvent(this, ((LoopEntryPointInfo*)entryPointInfo), ((uint16)loopNum)));
  3319. #ifdef VTUNE_PROFILING
  3320. VTuneChakraProfile::LogLoopBodyLoadEvent(this, ((LoopEntryPointInfo*)entryPointInfo), ((uint16)loopNum));
  3321. #endif
  3322. }
  3323. #endif
  3324. void FunctionBody::MarkScript(ByteBlock *byteCodeBlock, ByteBlock* auxBlock, ByteBlock* auxContextBlock,
  3325. uint byteCodeCount, uint byteCodeInLoopCount, uint byteCodeWithoutLDACount)
  3326. {
  3327. CheckNotExecuting();
  3328. CheckEmpty();
  3329. #ifdef PERF_COUNTERS
  3330. DWORD byteCodeSize = byteCodeBlock->GetLength()
  3331. + (auxBlock? auxBlock->GetLength() : 0)
  3332. + (auxContextBlock? auxContextBlock->GetLength() : 0);
  3333. PERF_COUNTER_ADD(Code, DynamicByteCodeSize, byteCodeSize);
  3334. #endif
  3335. SetByteCodeCount(byteCodeCount);
  3336. SetByteCodeInLoopCount(byteCodeInLoopCount);
  3337. SetByteCodeWithoutLDACount(byteCodeWithoutLDACount);
  3338. executionState.InitializeExecutionModeAndLimits(this);
  3339. this->SetAuxiliaryData(auxBlock);
  3340. this->SetAuxiliaryContextData(auxContextBlock);
  3341. // Memory barrier needed here to make sure the background codegen thread's inliner
  3342. // gets all the assignment before it sees that the function has been parse
  3343. MemoryBarrier();
  3344. this->byteCodeBlock = byteCodeBlock;
  3345. PERF_COUNTER_ADD(Code, TotalByteCodeSize, byteCodeSize);
  3346. // If this is a defer parse function body, we would not have registered it
  3347. // on the function bodies list so we should register it now
  3348. if (!this->m_isFuncRegistered)
  3349. {
  3350. this->GetUtf8SourceInfo()->SetFunctionBody(this);
  3351. }
  3352. }
  3353. uint
  3354. FunctionBody::GetLoopNumber(LoopHeader const * loopHeader) const
  3355. {
  3356. LoopHeader* loopHeaderArray = this->GetLoopHeaderArray();
  3357. Assert(loopHeader >= loopHeaderArray);
  3358. uint loopNum = (uint)(loopHeader - loopHeaderArray);
  3359. Assert(loopNum < GetLoopCount());
  3360. return loopNum;
  3361. }
  3362. uint
  3363. FunctionBody::GetLoopNumberWithLock(LoopHeader const * loopHeader) const
  3364. {
  3365. LoopHeader* loopHeaderArray = this->GetLoopHeaderArrayWithLock();
  3366. Assert(loopHeader >= loopHeaderArray);
  3367. uint loopNum = (uint)(loopHeader - loopHeaderArray);
  3368. Assert(loopNum < GetLoopCount());
  3369. return loopNum;
  3370. }
  3371. #ifdef ENABLE_SCRIPT_DEBUGGING
  3372. bool FunctionBody::InstallProbe(int offset)
  3373. {
  3374. if (offset < 0 || ((uint)offset + 1) >= byteCodeBlock->GetLength())
  3375. {
  3376. return false;
  3377. }
  3378. byte* pbyteCodeBlockBuffer = this->byteCodeBlock->GetBuffer();
  3379. if(!GetProbeBackingBlock())
  3380. {
  3381. // The probe backing block is set on a different thread than the main thread
  3382. // The recycler doesn't like allocations from a different thread, so we allocate
  3383. // the backing byte code block in the arena
  3384. ArenaAllocator *pArena = m_scriptContext->AllocatorForDiagnostics();
  3385. AssertMem(pArena);
  3386. ByteBlock* probeBackingBlock = ByteBlock::NewFromArena(pArena, pbyteCodeBlockBuffer, byteCodeBlock->GetLength());
  3387. SetProbeBackingBlock(probeBackingBlock);
  3388. }
  3389. // Make sure Break opcode only need one byte
  3390. Assert(OpCodeUtil::IsSmallEncodedOpcode(OpCode::Break));
  3391. #if ENABLE_NATIVE_CODEGEN
  3392. Assert(!OpCodeAttr::HasMultiSizeLayout(OpCode::Break));
  3393. #endif
  3394. *(byte *)(pbyteCodeBlockBuffer + offset) = (byte)OpCode::Break;
  3395. ++m_sourceInfo.m_probeCount;
  3396. return true;
  3397. }
  3398. bool FunctionBody::UninstallProbe(int offset)
  3399. {
  3400. if (offset < 0 || ((uint)offset + 1) >= byteCodeBlock->GetLength())
  3401. {
  3402. return false;
  3403. }
  3404. byte* pbyteCodeBlockBuffer = byteCodeBlock->GetBuffer();
  3405. Js::OpCode originalOpCode = ByteCodeReader::PeekByteOp(GetProbeBackingBlock()->GetBuffer() + offset);
  3406. *(pbyteCodeBlockBuffer + offset) = (byte)originalOpCode;
  3407. --m_sourceInfo.m_probeCount;
  3408. AssertMsg(m_sourceInfo.m_probeCount >= 0, "Probe (Break Point) count became negative!");
  3409. return true;
  3410. }
  3411. bool FunctionBody::ProbeAtOffset(int offset, OpCode* pOriginalOpcode)
  3412. {
  3413. if (!GetProbeBackingBlock())
  3414. {
  3415. return false;
  3416. }
  3417. if (offset < 0 || ((uint)offset + 1) >= this->byteCodeBlock->GetLength())
  3418. {
  3419. AssertMsg(false, "ProbeAtOffset called with out of bounds offset");
  3420. return false;
  3421. }
  3422. Js::OpCode runningOpCode = ByteCodeReader::PeekByteOp(this->byteCodeBlock->GetBuffer() + offset);
  3423. Js::OpCode originalOpcode = ByteCodeReader::PeekByteOp(GetProbeBackingBlock()->GetBuffer() + offset);
  3424. if ( runningOpCode != originalOpcode)
  3425. {
  3426. *pOriginalOpcode = originalOpcode;
  3427. return true;
  3428. }
  3429. else
  3430. {
  3431. // e.g. inline break or a step hit and is checking for a bp
  3432. return false;
  3433. }
  3434. }
  3435. #endif
  3436. void FunctionBody::SetStackNestedFuncParent(FunctionInfo * parentFunctionInfo)
  3437. {
  3438. FunctionBody * parentFunctionBody = parentFunctionInfo->GetFunctionBody();
  3439. RecyclerWeakReference<FunctionInfo>* parent = this->GetStackNestedFuncParent();
  3440. if (parent != nullptr)
  3441. {
  3442. Assert(parent->Get() == parentFunctionInfo);
  3443. return;
  3444. }
  3445. // Redeferral invalidates this assertion, as we may be recompiling with a different view of nested functions and
  3446. // thus making different stack-nested-function decisions. I'm inclined to allow this, since things that have been
  3447. // re-deferred will likely not be executed again, so it makes sense to exclude them from our analysis.
  3448. // Assert(CanDoStackNestedFunc());
  3449. Assert(parentFunctionBody->DoStackNestedFunc());
  3450. this->SetAuxPtr(AuxPointerType::StackNestedFuncParent, this->GetScriptContext()->GetRecycler()->CreateWeakReferenceHandle(parentFunctionInfo));
  3451. }
  3452. FunctionInfo * FunctionBody::GetStackNestedFuncParentStrongRef()
  3453. {
  3454. Assert(this->GetStackNestedFuncParent() != nullptr);
  3455. return this->GetStackNestedFuncParent()->Get();
  3456. }
  3457. RecyclerWeakReference<FunctionInfo> * FunctionBody::GetStackNestedFuncParent()
  3458. {
  3459. return static_cast<RecyclerWeakReference<FunctionInfo>*>(this->GetAuxPtr(AuxPointerType::StackNestedFuncParent));
  3460. }
  3461. FunctionInfo * FunctionBody::GetAndClearStackNestedFuncParent()
  3462. {
  3463. if (this->GetAuxPtr(AuxPointerType::StackNestedFuncParent))
  3464. {
  3465. FunctionInfo * parentFunctionInfo = GetStackNestedFuncParentStrongRef();
  3466. ClearStackNestedFuncParent();
  3467. return parentFunctionInfo;
  3468. }
  3469. return nullptr;
  3470. }
  3471. void FunctionBody::ClearStackNestedFuncParent()
  3472. {
  3473. this->SetAuxPtr(AuxPointerType::StackNestedFuncParent, nullptr);
  3474. }
  3475. void FunctionBody::CreateCacheIdToPropertyIdMap(uint rootObjectLoadInlineCacheStart, uint rootObjectLoadMethodInlineCacheStart,
  3476. uint rootObjectStoreInlineCacheStart,
  3477. uint totalFieldAccessInlineCacheCount, uint isInstInlineCacheCount)
  3478. {
  3479. Assert(this->GetRootObjectLoadInlineCacheStart() == 0);
  3480. Assert(this->GetRootObjectLoadMethodInlineCacheStart() == 0);
  3481. Assert(this->GetRootObjectStoreInlineCacheStart() == 0);
  3482. Assert(this->GetInlineCacheCount() == 0);
  3483. Assert(this->GetIsInstInlineCacheCount() == 0);
  3484. this->SetRootObjectLoadInlineCacheStart(rootObjectLoadInlineCacheStart);
  3485. this->SetRootObjectLoadMethodInlineCacheStart(rootObjectLoadMethodInlineCacheStart);
  3486. this->SetRootObjectStoreInlineCacheStart(rootObjectStoreInlineCacheStart);
  3487. this->SetInlineCacheCount(totalFieldAccessInlineCacheCount);
  3488. this->SetIsInstInlineCacheCount(isInstInlineCacheCount);
  3489. this->CreateCacheIdToPropertyIdMap();
  3490. }
  3491. void FunctionBody::CreateCacheIdToPropertyIdMap()
  3492. {
  3493. Assert(this->cacheIdToPropertyIdMap == nullptr);
  3494. Assert(this->inlineCaches == nullptr);
  3495. uint count = this->GetInlineCacheCount() ;
  3496. if (count!= 0)
  3497. {
  3498. this->cacheIdToPropertyIdMap =
  3499. RecyclerNewArrayLeaf(this->m_scriptContext->GetRecycler(), PropertyId, count);
  3500. #if DBG
  3501. for (uint i = 0; i < count; i++)
  3502. {
  3503. this->cacheIdToPropertyIdMap[i] = Js::Constants::NoProperty;
  3504. }
  3505. #endif
  3506. }
  3507. }
  3508. #if DBG
  3509. void FunctionBody::VerifyCacheIdToPropertyIdMap()
  3510. {
  3511. uint count = this->GetInlineCacheCount();
  3512. for (uint i = 0; i < count; i++)
  3513. {
  3514. Assert(this->cacheIdToPropertyIdMap[i] != Js::Constants::NoProperty);
  3515. }
  3516. }
  3517. #endif
  3518. void FunctionBody::SetPropertyIdForCacheId(uint cacheId, PropertyId propertyId)
  3519. {
  3520. Assert(this->cacheIdToPropertyIdMap != nullptr);
  3521. Assert(cacheId < this->GetInlineCacheCount());
  3522. Assert(this->cacheIdToPropertyIdMap[cacheId] == Js::Constants::NoProperty);
  3523. this->cacheIdToPropertyIdMap[cacheId] = propertyId;
  3524. }
  3525. void FunctionBody::CreateReferencedPropertyIdMap(uint referencedPropertyIdCount)
  3526. {
  3527. this->SetReferencedPropertyIdCount(referencedPropertyIdCount);
  3528. this->CreateReferencedPropertyIdMap();
  3529. }
  3530. void FunctionBody::CreateReferencedPropertyIdMap()
  3531. {
  3532. Assert(this->GetReferencedPropertyIdMap() == nullptr);
  3533. uint count = this->GetReferencedPropertyIdCount();
  3534. if (count!= 0)
  3535. {
  3536. this->SetReferencedPropertyIdMap(RecyclerNewArrayLeaf(this->m_scriptContext->GetRecycler(), PropertyId, count));
  3537. #if DBG
  3538. for (uint i = 0; i < count; i++)
  3539. {
  3540. this->GetReferencedPropertyIdMap()[i] = Js::Constants::NoProperty;
  3541. }
  3542. #endif
  3543. }
  3544. }
  3545. #if DBG
  3546. void FunctionBody::VerifyReferencedPropertyIdMap()
  3547. {
  3548. uint count = this->GetReferencedPropertyIdCount();
  3549. for (uint i = 0; i < count; i++)
  3550. {
  3551. Assert(this->GetReferencedPropertyIdMap()[i] != Js::Constants::NoProperty);
  3552. }
  3553. }
  3554. #endif
  3555. PropertyId FunctionBody::GetReferencedPropertyId(uint index)
  3556. {
  3557. if (index < (uint)TotalNumberOfBuiltInProperties)
  3558. {
  3559. return index;
  3560. }
  3561. uint mapIndex = index - TotalNumberOfBuiltInProperties;
  3562. return GetReferencedPropertyIdWithMapIndex(mapIndex);
  3563. }
  3564. PropertyId FunctionBody::GetReferencedPropertyIdWithLock(uint index)
  3565. {
  3566. if (index < (uint)TotalNumberOfBuiltInProperties)
  3567. {
  3568. return index;
  3569. }
  3570. uint mapIndex = index - TotalNumberOfBuiltInProperties;
  3571. return GetReferencedPropertyIdWithMapIndexWithLock(mapIndex);
  3572. }
  3573. PropertyId FunctionBody::GetReferencedPropertyIdWithMapIndex(uint mapIndex)
  3574. {
  3575. Assert(this->GetReferencedPropertyIdMap());
  3576. Assert(mapIndex < this->GetReferencedPropertyIdCount());
  3577. return this->GetReferencedPropertyIdMap()[mapIndex];
  3578. }
  3579. PropertyId FunctionBody::GetReferencedPropertyIdWithMapIndexWithLock(uint mapIndex)
  3580. {
  3581. Assert(this->GetReferencedPropertyIdMapWithLock());
  3582. Assert(mapIndex < this->GetReferencedPropertyIdCount());
  3583. return this->GetReferencedPropertyIdMapWithLock()[mapIndex];
  3584. }
  3585. void FunctionBody::SetReferencedPropertyIdWithMapIndex(uint mapIndex, PropertyId propertyId)
  3586. {
  3587. Assert(propertyId >= TotalNumberOfBuiltInProperties);
  3588. Assert(mapIndex < this->GetReferencedPropertyIdCount());
  3589. Assert(this->GetReferencedPropertyIdMap() != nullptr);
  3590. Assert(this->GetReferencedPropertyIdMap()[mapIndex] == Js::Constants::NoProperty);
  3591. this->GetReferencedPropertyIdMap()[mapIndex] = propertyId;
  3592. }
  3593. void FunctionBody::CreateConstantTable()
  3594. {
  3595. Assert(this->GetConstTable() == nullptr);
  3596. Assert(GetConstantCount() > FirstRegSlot);
  3597. this->SetConstTable(RecyclerNewArrayZ(this->m_scriptContext->GetRecycler(), Field(Var), GetConstantCount()));
  3598. // Initialize with the root object, which will always be recorded here.
  3599. Js::RootObjectBase * rootObject = this->LoadRootObject();
  3600. if (rootObject)
  3601. {
  3602. this->RecordConstant(RootObjectRegSlot, rootObject);
  3603. }
  3604. else
  3605. {
  3606. Assert(false);
  3607. this->RecordConstant(RootObjectRegSlot, this->m_scriptContext->GetLibrary()->GetUndefined());
  3608. }
  3609. }
  3610. void FunctionBody::RecordConstant(RegSlot location, Var var)
  3611. {
  3612. Assert(location < GetConstantCount());
  3613. Assert(this->GetConstTable());
  3614. Assert(var != nullptr);
  3615. Assert(this->GetConstTable()[location - FunctionBody::FirstRegSlot] == nullptr);
  3616. this->GetConstTable()[location - FunctionBody::FirstRegSlot] = var;
  3617. }
  3618. void FunctionBody::RecordNullObject(RegSlot location)
  3619. {
  3620. ScriptContext *scriptContext = this->GetScriptContext();
  3621. Var nullObject = JavascriptOperators::OP_LdNull(scriptContext);
  3622. this->RecordConstant(location, nullObject);
  3623. }
  3624. void FunctionBody::RecordUndefinedObject(RegSlot location)
  3625. {
  3626. ScriptContext *scriptContext = this->GetScriptContext();
  3627. Var undefObject = JavascriptOperators::OP_LdUndef(scriptContext);
  3628. this->RecordConstant(location, undefObject);
  3629. }
  3630. void FunctionBody::RecordTrueObject(RegSlot location)
  3631. {
  3632. ScriptContext *scriptContext = this->GetScriptContext();
  3633. Var trueObject = JavascriptBoolean::OP_LdTrue(scriptContext);
  3634. this->RecordConstant(location, trueObject);
  3635. }
  3636. void FunctionBody::RecordFalseObject(RegSlot location)
  3637. {
  3638. ScriptContext *scriptContext = this->GetScriptContext();
  3639. Var falseObject = JavascriptBoolean::OP_LdFalse(scriptContext);
  3640. this->RecordConstant(location, falseObject);
  3641. }
  3642. void FunctionBody::RecordIntConstant(RegSlot location, unsigned int val)
  3643. {
  3644. ScriptContext *scriptContext = this->GetScriptContext();
  3645. Var intConst = JavascriptNumber::ToVar((int32)val, scriptContext);
  3646. this->RecordConstant(location, intConst);
  3647. }
  3648. void FunctionBody::RecordStrConstant(RegSlot location, LPCOLESTR psz, uint32 cch, bool forcePropertyString)
  3649. {
  3650. ScriptContext *scriptContext = this->GetScriptContext();
  3651. PropertyRecord const * propertyRecord;
  3652. if (forcePropertyString)
  3653. {
  3654. scriptContext->GetOrAddPropertyRecord(psz, cch, &propertyRecord);
  3655. }
  3656. else
  3657. {
  3658. scriptContext->FindPropertyRecord(psz, cch, &propertyRecord);
  3659. }
  3660. Var str;
  3661. if (propertyRecord == nullptr)
  3662. {
  3663. str = JavascriptString::NewCopyBuffer(psz, cch, scriptContext);
  3664. }
  3665. else
  3666. {
  3667. // If a particular string constant already has a propertyId, just create a property string for it
  3668. // as it might be likely that it is used for a property lookup
  3669. str = scriptContext->GetPropertyString(propertyRecord->GetPropertyId());
  3670. }
  3671. this->RecordConstant(location, str);
  3672. }
  3673. void FunctionBody::RecordFloatConstant(RegSlot location, double d)
  3674. {
  3675. ScriptContext *scriptContext = this->GetScriptContext();
  3676. Var floatConst = JavascriptNumber::ToVarIntCheck(d, scriptContext);
  3677. this->RecordConstant(location, floatConst);
  3678. }
  3679. void FunctionBody::RecordNullDisplayConstant(RegSlot location)
  3680. {
  3681. this->RecordConstant(location, (Js::Var)&Js::NullFrameDisplay);
  3682. }
  3683. void FunctionBody::RecordStrictNullDisplayConstant(RegSlot location)
  3684. {
  3685. this->RecordConstant(location, (Js::Var)&Js::StrictNullFrameDisplay);
  3686. }
  3687. void FunctionBody::InitConstantSlots(Var *dstSlots)
  3688. {
  3689. // Initialize the given slots from the constant table.
  3690. uint32 constCount = GetConstantCount();
  3691. Assert(constCount > FunctionBody::FirstRegSlot);
  3692. js_memcpy_s(dstSlots, (constCount - FunctionBody::FirstRegSlot) * sizeof(Var),
  3693. this->GetConstTable(), (constCount - FunctionBody::FirstRegSlot) * sizeof(Var));
  3694. }
  3695. Var FunctionBody::GetConstantVar(RegSlot location)
  3696. {
  3697. Assert(this->GetConstTable());
  3698. Assert(location < GetConstantCount());
  3699. Assert(location != 0);
  3700. return this->GetConstTable()[location - FunctionBody::FirstRegSlot];
  3701. }
  3702. #if DBG_DUMP
  3703. void FunctionBody::Dump()
  3704. {
  3705. Js::ByteCodeDumper::Dump(this);
  3706. }
  3707. void FunctionBody::DumpScopes()
  3708. {
  3709. if(this->GetScopeObjectChain())
  3710. {
  3711. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  3712. Output::Print(_u("%s (%s) :\n"), this->GetDisplayName(), this->GetDebugNumberSet(debugStringBuffer));
  3713. this->GetScopeObjectChain()->pScopeChain->Map( [=] (uint index, DebuggerScope* scope )
  3714. {
  3715. scope->Dump();
  3716. });
  3717. }
  3718. }
  3719. #if ENABLE_NATIVE_CODEGEN
  3720. void EntryPointInfo::DumpNativeOffsetMaps()
  3721. {
  3722. // Native Offsets
  3723. if (this->nativeOffsetMaps.Count() > 0)
  3724. {
  3725. Output::Print(_u("Native Map: baseAddr: 0x%0Ix, size: 0x%0Ix\nstatementId, offset range, address range\n"),
  3726. this->GetNativeAddress(),
  3727. this->GetCodeSize());
  3728. int count = this->nativeOffsetMaps.Count();
  3729. for(int i = 0; i < count; i++)
  3730. {
  3731. const NativeOffsetMap* map = &this->nativeOffsetMaps.Item(i);
  3732. Output::Print(_u("S%4d, (%5d, %5d) (0x%012Ix, 0x%012Ix)\n"), map->statementIndex,
  3733. map->nativeOffsetSpan.begin,
  3734. map->nativeOffsetSpan.end,
  3735. map->nativeOffsetSpan.begin + this->GetNativeAddress(),
  3736. map->nativeOffsetSpan.end + this->GetNativeAddress());
  3737. }
  3738. }
  3739. }
  3740. #endif
  3741. void FunctionBody::DumpStatementMaps()
  3742. {
  3743. // Source Map to ByteCode
  3744. StatementMapList * pStatementMaps = this->GetStatementMaps();
  3745. if (pStatementMaps)
  3746. {
  3747. Output::Print(_u("Statement Map:\nstatementId, SourceSpan, ByteCodeSpan\n"));
  3748. int count = pStatementMaps->Count();
  3749. for(int i = 0; i < count; i++)
  3750. {
  3751. StatementMap* map = pStatementMaps->Item(i);
  3752. Output::Print(_u("S%4d, (C%5d, C%5d) (B%5d, B%5d) Inner=%d\n"), i,
  3753. map->sourceSpan.begin,
  3754. map->sourceSpan.end,
  3755. map->byteCodeSpan.begin,
  3756. map->byteCodeSpan.end,
  3757. map->isSubexpression);
  3758. }
  3759. }
  3760. }
  3761. #if ENABLE_NATIVE_CODEGEN
  3762. void EntryPointInfo::DumpNativeThrowSpanSequence()
  3763. {
  3764. // Native Throw Map
  3765. if (this->nativeThrowSpanSequence)
  3766. {
  3767. Output::Print(_u("Native Throw Map: baseAddr: 0x%0Ix, size: 0x%Ix\nstatementId, offset range, address range\n"),
  3768. this->GetNativeAddress(),
  3769. this->GetCodeSize());
  3770. int count = this->nativeThrowSpanSequence->Count();
  3771. SmallSpanSequenceIter iter;
  3772. for (int i = 0; i < count; i++)
  3773. {
  3774. StatementData data;
  3775. if (this->nativeThrowSpanSequence->Item(i, iter, data))
  3776. {
  3777. Output::Print(_u("S%4d, (%5d -----) (0x%012Ix --------)\n"), data.sourceBegin, // statementIndex
  3778. data.bytecodeBegin, // nativeOffset
  3779. data.bytecodeBegin + this->GetNativeAddress());
  3780. }
  3781. }
  3782. }
  3783. }
  3784. #endif
  3785. void FunctionBody::PrintStatementSourceLine(uint statementIndex)
  3786. {
  3787. if (m_isWasmFunction)
  3788. {
  3789. // currently no source view support for wasm
  3790. return;
  3791. }
  3792. const uint startOffset = GetStatementStartOffset(statementIndex);
  3793. // startOffset should only be 0 if statementIndex is 0, otherwise it is EOF and we should skip printing anything
  3794. if (startOffset != 0 || statementIndex == 0)
  3795. {
  3796. PrintStatementSourceLineFromStartOffset(startOffset);
  3797. }
  3798. }
  3799. void FunctionBody::PrintStatementSourceLineFromStartOffset(uint cchStartOffset)
  3800. {
  3801. ULONG line;
  3802. LONG col;
  3803. LPCUTF8 source = GetStartOfDocument(_u("FunctionBody::PrintStatementSourceLineFromStartOffset"));
  3804. Utf8SourceInfo* sourceInfo = this->GetUtf8SourceInfo();
  3805. Assert(sourceInfo != nullptr);
  3806. LPCUTF8 sourceInfoSrc = sourceInfo->GetSource(_u("FunctionBody::PrintStatementSourceLineFromStartOffset"));
  3807. if(!sourceInfoSrc)
  3808. {
  3809. Assert(sourceInfo->GetIsLibraryCode());
  3810. return;
  3811. }
  3812. if( source != sourceInfoSrc )
  3813. {
  3814. Output::Print(_u("\nDETECTED MISMATCH:\n"));
  3815. Output::Print(_u("GetUtf8SourceInfo()->GetSource(): 0x%08X: %.*s ...\n"), sourceInfo, 16, sourceInfo);
  3816. Output::Print(_u("GetStartOfDocument(): 0x%08X: %.*s ...\n"), source, 16, source);
  3817. AssertMsg(false, "Non-matching start of document");
  3818. }
  3819. GetLineCharOffsetFromStartChar(cchStartOffset, &line, &col, false /*canAllocateLineCache*/);
  3820. if (sourceInfo->GetSourceHolder() != ISourceHolder::GetEmptySourceHolder())
  3821. {
  3822. WORD color = 0;
  3823. if (Js::Configuration::Global.flags.DumpLineNoInColor)
  3824. {
  3825. color = Output::SetConsoleForeground(12);
  3826. }
  3827. Output::Print(_u("\n\n Line %3d: "), line + 1);
  3828. // Need to match up cchStartOffset to appropriate cbStartOffset given function's cbStartOffset and cchStartOffset
  3829. size_t i = utf8::CharacterIndexToByteIndex(source, sourceInfo->GetCbLength(), cchStartOffset, this->m_cbStartOffset, this->m_cchStartOffset);
  3830. size_t lastOffset = StartOffset() + LengthInBytes();
  3831. for (;i < lastOffset && source[i] != '\n' && source[i] != '\r'; i++)
  3832. {
  3833. Output::Print(_u("%C"), source[i]);
  3834. }
  3835. Output::Print(_u("\n"));
  3836. Output::Print(_u(" Col %4d:%s^\n"), col + 1, ((col+1)<10000) ? _u(" ") : _u(""));
  3837. if (color != 0)
  3838. {
  3839. Output::SetConsoleForeground(color);
  3840. }
  3841. }
  3842. }
  3843. #endif // DBG_DUMP
  3844. /**
  3845. * Get the source code offset for the given <statementIndex>.
  3846. */
  3847. uint FunctionBody::GetStatementStartOffset(const uint statementIndex)
  3848. {
  3849. uint startOffset = 0;
  3850. if (statementIndex != Js::Constants::NoStatementIndex)
  3851. {
  3852. const Js::FunctionBody::SourceInfo * sourceInfo = &(this->m_sourceInfo);
  3853. if (sourceInfo->pSpanSequence != nullptr)
  3854. {
  3855. Js::SmallSpanSequenceIter iter;
  3856. sourceInfo->pSpanSequence->Reset(iter);
  3857. Js::StatementData data;
  3858. sourceInfo->pSpanSequence->Item(statementIndex, iter, data);
  3859. startOffset = data.sourceBegin;
  3860. }
  3861. else
  3862. {
  3863. int index = statementIndex;
  3864. Js::FunctionBody::StatementMap * statementMap = GetNextNonSubexpressionStatementMap(GetStatementMaps(), index);
  3865. startOffset = statementMap->sourceSpan.Begin();
  3866. }
  3867. }
  3868. return startOffset;
  3869. }
  3870. #ifdef IR_VIEWER
  3871. /* BEGIN potentially reusable code */
  3872. /*
  3873. This code could be reused for locating source code in a debugger or to
  3874. retrieve the text of source statements.
  3875. Currently this code is used to retrieve the text of a source code statement
  3876. in the IR_VIEWER feature.
  3877. */
  3878. /**
  3879. * Given a statement's starting offset in the source code, calculate the beginning and end of a statement,
  3880. * as well as the line and column number where the statement appears.
  3881. *
  3882. * @param startOffset (input) The offset into the source code where this statement begins.
  3883. * @param sourceBegin (output) The beginning of the statement in the source string.
  3884. * @param sourceEnd (output) The end of the statement in the source string.
  3885. * @param line (output) The line number where the statement appeared in the source.
  3886. * @param col (output) The column number where the statement appeared in the source.
  3887. */
  3888. void FunctionBody::GetSourceLineFromStartOffset(const uint startOffset, LPCUTF8 *sourceBegin, LPCUTF8 *sourceEnd,
  3889. ULONG * line, LONG * col)
  3890. {
  3891. //
  3892. // get source info
  3893. //
  3894. LPCUTF8 source = GetStartOfDocument(_u("IR Viewer FunctionBody::GetSourceLineFromStartOffset"));
  3895. Utf8SourceInfo* sourceInfo = this->GetUtf8SourceInfo();
  3896. Assert(sourceInfo != nullptr);
  3897. LPCUTF8 sourceInfoSrc = sourceInfo->GetSource(_u("IR Viewer FunctionBody::GetSourceLineFromStartOffset"));
  3898. if (!sourceInfoSrc)
  3899. {
  3900. Assert(sourceInfo->GetIsLibraryCode());
  3901. return;
  3902. }
  3903. if (source != sourceInfoSrc)
  3904. {
  3905. Output::Print(_u("\nDETECTED MISMATCH:\n"));
  3906. Output::Print(_u("GetUtf8SourceInfo()->GetSource(): 0x%08X: %.*s ...\n"), sourceInfo, 16, sourceInfo);
  3907. Output::Print(_u("GetStartOfDocument(): 0x%08X: %.*s ...\n"), source, 16, source);
  3908. AssertMsg(false, "Non-matching start of document");
  3909. }
  3910. //
  3911. // calculate source line info
  3912. //
  3913. size_t cbStartOffset = utf8::CharacterIndexToByteIndex(source, sourceInfo->GetCbLength(), (const charcount_t)startOffset, (size_t)this->m_cbStartOffset, (charcount_t)this->m_cchStartOffset);
  3914. GetLineCharOffsetFromStartChar(startOffset, line, col);
  3915. size_t lastOffset = StartOffset() + LengthInBytes();
  3916. size_t i = 0;
  3917. for (i = cbStartOffset; i < lastOffset && source[i] != '\n' && source[i] != '\r'; i++)
  3918. {
  3919. // do nothing; scan until end of statement
  3920. }
  3921. size_t cbEndOffset = i;
  3922. //
  3923. // return
  3924. //
  3925. *sourceBegin = &source[cbStartOffset];
  3926. *sourceEnd = &source[cbEndOffset];
  3927. }
  3928. /**
  3929. * Given a statement index and output parameters, calculate the beginning and end of a statement,
  3930. * as well as the line and column number where the statement appears.
  3931. *
  3932. * @param statementIndex (input) The statement's index (as used by the StatementBoundary pragma).
  3933. * @param sourceBegin (output) The beginning of the statement in the source string.
  3934. * @param sourceEnd (output) The end of the statement in the source string.
  3935. * @param line (output) The line number where the statement appeared in the source.
  3936. * @param col (output) The column number where the statement appeared in the source.
  3937. */
  3938. void FunctionBody::GetStatementSourceInfo(const uint statementIndex, LPCUTF8 *sourceBegin, LPCUTF8 *sourceEnd,
  3939. ULONG * line, LONG * col)
  3940. {
  3941. const size_t startOffset = GetStatementStartOffset(statementIndex);
  3942. // startOffset should only be 0 if statementIndex is 0, otherwise it is EOF and we should return empty string
  3943. if (startOffset != 0 || statementIndex == 0)
  3944. {
  3945. GetSourceLineFromStartOffset(startOffset, sourceBegin, sourceEnd, line, col);
  3946. }
  3947. else
  3948. {
  3949. *sourceBegin = nullptr;
  3950. *sourceEnd = nullptr;
  3951. *line = 0;
  3952. *col = 0;
  3953. return;
  3954. }
  3955. }
  3956. /* END potentially reusable code */
  3957. #endif /* IR_VIEWER */
  3958. #if ENABLE_TTD
  3959. void FunctionBody::GetSourceLineFromStartOffset_TTD(const uint startOffset, ULONG* line, LONG* col)
  3960. {
  3961. GetLineCharOffsetFromStartChar(startOffset, line, col);
  3962. }
  3963. #endif
  3964. #ifdef IR_VIEWER
  3965. Js::DynamicObject * FunctionBody::GetIRDumpBaseObject()
  3966. {
  3967. if (!this->m_irDumpBaseObject)
  3968. {
  3969. this->m_irDumpBaseObject = this->m_scriptContext->GetLibrary()->CreateObject();
  3970. }
  3971. return this->m_irDumpBaseObject;
  3972. }
  3973. #endif /* IR_VIEWER */
  3974. #ifdef VTUNE_PROFILING
  3975. #include "jitprofiling.h"
  3976. int EntryPointInfo::GetNativeOffsetMapCount() const
  3977. {
  3978. return this->nativeOffsetMaps.Count();
  3979. }
  3980. uint EntryPointInfo::PopulateLineInfo(void* pInfo, FunctionBody* body)
  3981. {
  3982. LineNumberInfo* pLineInfo = (LineNumberInfo*)pInfo;
  3983. ULONG functionLineNumber = body->GetLineNumber();
  3984. pLineInfo[0].Offset = 0;
  3985. pLineInfo[0].LineNumber = functionLineNumber;
  3986. int lineNumber = 0;
  3987. int j = 1; // start with 1 since offset 0 has already been populated with function line number
  3988. int count = this->nativeOffsetMaps.Count();
  3989. for(int i = 0; i < count; i++)
  3990. {
  3991. const NativeOffsetMap* map = &this->nativeOffsetMaps.Item(i);
  3992. uint32 statementIndex = map->statementIndex;
  3993. if (statementIndex == 0)
  3994. {
  3995. // statementIndex is 0, first line in the function, populate with function line number
  3996. pLineInfo[j].Offset = map->nativeOffsetSpan.begin;
  3997. pLineInfo[j].LineNumber = functionLineNumber;
  3998. j++;
  3999. }
  4000. lineNumber = body->GetSourceLineNumber(statementIndex);
  4001. if (lineNumber != 0)
  4002. {
  4003. pLineInfo[j].Offset = map->nativeOffsetSpan.end;
  4004. pLineInfo[j].LineNumber = lineNumber;
  4005. j++;
  4006. }
  4007. }
  4008. return j;
  4009. }
  4010. ULONG FunctionBody::GetSourceLineNumber(uint statementIndex)
  4011. {
  4012. ULONG line = 0;
  4013. if (statementIndex != Js::Constants::NoStatementIndex)
  4014. {
  4015. uint startOffset = GetStartOffset(statementIndex);
  4016. if (startOffset != 0 || statementIndex == 0)
  4017. {
  4018. GetLineCharOffsetFromStartChar(startOffset, &line, nullptr, false /*canAllocateLineCache*/);
  4019. line = line + 1;
  4020. }
  4021. }
  4022. return line;
  4023. }
  4024. uint FunctionBody::GetStartOffset(uint statementIndex) const
  4025. {
  4026. uint startOffset = 0;
  4027. const Js::FunctionBody::SourceInfo * sourceInfo = &this->m_sourceInfo;
  4028. if (sourceInfo->pSpanSequence != nullptr)
  4029. {
  4030. Js::SmallSpanSequenceIter iter;
  4031. sourceInfo->pSpanSequence->Reset(iter);
  4032. Js::StatementData data;
  4033. sourceInfo->pSpanSequence->Item(statementIndex, iter, data);
  4034. startOffset = data.sourceBegin;
  4035. }
  4036. else
  4037. {
  4038. int index = statementIndex;
  4039. Js::FunctionBody::StatementMap * statementMap = GetNextNonSubexpressionStatementMap(GetStatementMaps(), index);
  4040. startOffset = statementMap->sourceSpan.Begin();
  4041. }
  4042. return startOffset;
  4043. }
  4044. #endif
  4045. void ParseableFunctionInfo::SetIsNonUserCode(bool set)
  4046. {
  4047. // Mark current function as a non-user code, so that we can distinguish cases where exceptions are
  4048. // caught in non-user code (see ProbeContainer::HasAllowedForException).
  4049. SetFlags(set, Flags_NonUserCode);
  4050. // Propagate setting for all functions in this scope (nested).
  4051. this->ForEachNestedFunc([&](FunctionProxy* proxy, uint32 index)
  4052. {
  4053. ParseableFunctionInfo * pBody = proxy->GetParseableFunctionInfo();
  4054. if (pBody != nullptr)
  4055. {
  4056. pBody->SetIsNonUserCode(set);
  4057. }
  4058. return true;
  4059. });
  4060. }
  4061. void FunctionBody::InsertSymbolToRegSlotList(JsUtil::CharacterBuffer<WCHAR> const& propName, RegSlot reg, RegSlot totalRegsCount)
  4062. {
  4063. if (totalRegsCount > 0)
  4064. {
  4065. PropertyId propertyId = GetOrAddPropertyIdTracked(propName);
  4066. InsertSymbolToRegSlotList(reg, propertyId, totalRegsCount);
  4067. }
  4068. }
  4069. void FunctionBody::InsertSymbolToRegSlotList(RegSlot reg, PropertyId propertyId, RegSlot totalRegsCount)
  4070. {
  4071. if (totalRegsCount > 0)
  4072. {
  4073. if (this->GetPropertyIdOnRegSlotsContainer() == nullptr)
  4074. {
  4075. this->SetPropertyIdOnRegSlotsContainer(PropertyIdOnRegSlotsContainer::New(m_scriptContext->GetRecycler()));
  4076. }
  4077. if (this->GetPropertyIdOnRegSlotsContainer()->propertyIdsForRegSlots == nullptr)
  4078. {
  4079. this->GetPropertyIdOnRegSlotsContainer()->CreateRegSlotsArray(m_scriptContext->GetRecycler(), totalRegsCount);
  4080. }
  4081. Assert(this->GetPropertyIdOnRegSlotsContainer() != nullptr);
  4082. this->GetPropertyIdOnRegSlotsContainer()->Insert(reg, propertyId);
  4083. }
  4084. }
  4085. void FunctionBody::SetPropertyIdsOfFormals(PropertyIdArray * formalArgs)
  4086. {
  4087. Assert(formalArgs);
  4088. if (this->GetPropertyIdOnRegSlotsContainer() == nullptr)
  4089. {
  4090. this->SetPropertyIdOnRegSlotsContainer(PropertyIdOnRegSlotsContainer::New(m_scriptContext->GetRecycler()));
  4091. }
  4092. this->GetPropertyIdOnRegSlotsContainer()->SetFormalArgs(formalArgs);
  4093. }
  4094. #ifdef ENABLE_SCRIPT_PROFILING
  4095. HRESULT FunctionBody::RegisterFunction(BOOL fChangeMode, BOOL fOnlyCurrent)
  4096. {
  4097. if (!this->IsFunctionParsed())
  4098. {
  4099. return S_OK;
  4100. }
  4101. HRESULT hr = this->ReportFunctionCompiled();
  4102. if (FAILED(hr))
  4103. {
  4104. return hr;
  4105. }
  4106. if (fChangeMode)
  4107. {
  4108. this->SetEntryToProfileMode();
  4109. }
  4110. if (!fOnlyCurrent)
  4111. {
  4112. for (uint uIndex = 0; uIndex < this->GetNestedCount(); uIndex++)
  4113. {
  4114. Js::ParseableFunctionInfo * pBody = this->GetNestedFunctionForExecution(uIndex);
  4115. if (pBody == nullptr || !pBody->IsFunctionParsed())
  4116. {
  4117. continue;
  4118. }
  4119. hr = pBody->GetFunctionBody()->RegisterFunction(fChangeMode);
  4120. if (FAILED(hr))
  4121. {
  4122. break;
  4123. }
  4124. }
  4125. }
  4126. return hr;
  4127. }
  4128. HRESULT FunctionBody::ReportScriptCompiled()
  4129. {
  4130. AssertMsg(m_scriptContext != nullptr, "Script Context is null when reporting function information");
  4131. PROFILER_SCRIPT_TYPE type = IsDynamicScript() ? PROFILER_SCRIPT_TYPE_DYNAMIC : PROFILER_SCRIPT_TYPE_USER;
  4132. IDebugDocumentContext *pDebugDocumentContext = nullptr;
  4133. this->m_scriptContext->GetDocumentContext(this, &pDebugDocumentContext);
  4134. HRESULT hr = m_scriptContext->OnScriptCompiled((PROFILER_TOKEN) this->GetUtf8SourceInfo()->GetSourceInfoId(), type, pDebugDocumentContext);
  4135. RELEASEPTR(pDebugDocumentContext);
  4136. return hr;
  4137. }
  4138. HRESULT FunctionBody::ReportFunctionCompiled()
  4139. {
  4140. // Some assumptions by Logger interface.
  4141. // to send NULL as a name in case the name is anonymous and hint is anonymous code.
  4142. const char16 *pwszName = GetExternalDisplayName();
  4143. IDebugDocumentContext *pDebugDocumentContext = nullptr;
  4144. this->m_scriptContext->GetDocumentContext(this, &pDebugDocumentContext);
  4145. SetHasFunctionCompiledSent(true);
  4146. HRESULT hr = m_scriptContext->OnFunctionCompiled(m_functionNumber, (PROFILER_TOKEN) this->GetUtf8SourceInfo()->GetSourceInfoId(), pwszName, nullptr, pDebugDocumentContext);
  4147. RELEASEPTR(pDebugDocumentContext);
  4148. #if DBG
  4149. if (m_iProfileSession >= m_scriptContext->GetProfileSession())
  4150. {
  4151. OUTPUT_TRACE_DEBUGONLY(Js::ScriptProfilerPhase, _u("FunctionBody::ReportFunctionCompiled, Duplicate compile event (%d < %d) for FunctionNumber : %d\n"),
  4152. m_iProfileSession, m_scriptContext->GetProfileSession(), m_functionNumber);
  4153. }
  4154. AssertMsg(m_iProfileSession < m_scriptContext->GetProfileSession(), "Duplicate compile event sent");
  4155. m_iProfileSession = m_scriptContext->GetProfileSession();
  4156. #endif
  4157. return hr;
  4158. }
  4159. void FunctionBody::SetEntryToProfileMode()
  4160. {
  4161. #if ENABLE_NATIVE_CODEGEN
  4162. AssertMsg(this->m_scriptContext->CurrentThunk == ProfileEntryThunk, "ScriptContext not in profile mode");
  4163. #if DBG
  4164. AssertMsg(m_iProfileSession == m_scriptContext->GetProfileSession(), "Changing mode to profile for function that didn't send compile event");
  4165. #endif
  4166. // This is always done when bg thread is paused hence we don't need any kind of thread-synchronization at this point.
  4167. // Change entry points to Profile Thunk
  4168. // If the entrypoint is CodeGenOnDemand or CodeGen - then we don't change the entry points
  4169. ProxyEntryPointInfo* defaultEntryPointInfo = this->GetDefaultEntryPointInfo();
  4170. if (!IsIntermediateCodeGenThunk(defaultEntryPointInfo->jsMethod)
  4171. && defaultEntryPointInfo->jsMethod != DynamicProfileInfo::EnsureDynamicProfileInfoThunk)
  4172. {
  4173. if (this->GetOriginalEntryPoint_Unchecked() == DefaultDeferredParsingThunk)
  4174. {
  4175. defaultEntryPointInfo->jsMethod = ProfileDeferredParsingThunk;
  4176. }
  4177. else if (this->GetOriginalEntryPoint_Unchecked() == DefaultDeferredDeserializeThunk)
  4178. {
  4179. defaultEntryPointInfo->jsMethod = ProfileDeferredDeserializeThunk;
  4180. }
  4181. else
  4182. {
  4183. defaultEntryPointInfo->jsMethod = ProfileEntryThunk;
  4184. }
  4185. }
  4186. // Update old entry points on the deferred prototype type so that they match current defaultEntryPointInfo.
  4187. // to make sure that new JavascriptFunction instances use profile thunk.
  4188. if (this->deferredPrototypeType)
  4189. {
  4190. this->deferredPrototypeType->SetEntryPoint(this->GetDefaultEntryPointInfo()->jsMethod);
  4191. this->deferredPrototypeType->SetEntryPointInfo(this->GetDefaultEntryPointInfo());
  4192. }
  4193. #if DBG
  4194. if (!this->HasValidEntryPoint())
  4195. {
  4196. OUTPUT_TRACE_DEBUGONLY(Js::ScriptProfilerPhase, _u("FunctionBody::SetEntryToProfileMode, Assert due to HasValidEntryPoint(), directEntrypoint : 0x%0IX, originalentrypoint : 0x%0IX\n"),
  4197. this->GetDefaultEntryPointInfo()->jsMethod, this->GetOriginalEntryPoint());
  4198. AssertMsg(false, "Not a valid EntryPoint");
  4199. }
  4200. #endif
  4201. #endif //ENABLE_NATIVE_CODEGEN
  4202. }
  4203. #endif // ENABLE_SCRIPT_PROFILING
  4204. #if DBG
  4205. void FunctionBody::MustBeInDebugMode()
  4206. {
  4207. Assert(GetUtf8SourceInfo()->IsInDebugMode());
  4208. Assert(m_sourceInfo.pSpanSequence == nullptr);
  4209. Assert(this->GetStatementMaps() != nullptr);
  4210. }
  4211. #endif
  4212. void ParseableFunctionInfo::CleanupToReparse()
  4213. {
  4214. #if DBG
  4215. if (this->IsFunctionBody())
  4216. {
  4217. GetFunctionBody()->UnlockCounters();
  4218. }
  4219. #endif
  4220. // The current function is already compiled. In order to prep this function to ready for debug mode, most of the previous information need to be thrown away.
  4221. // Clean up the nested functions
  4222. this->ForEachNestedFunc([&](FunctionProxy* proxy, uint32 index)
  4223. {
  4224. // Note: redeferred functions may have fully compiled children. If we find a redeferred function, keep walking.
  4225. if (proxy && ((proxy->CanBeDeferred() && proxy->GetFunctionInfo()->GetCompileCount() > 0) || proxy->IsFunctionBody()))
  4226. {
  4227. proxy->GetParseableFunctionInfo()->CleanupToReparse();
  4228. }
  4229. return true;
  4230. });
  4231. this->CleanupToReparseHelper();
  4232. if (this->IsFunctionBody())
  4233. {
  4234. this->GetFunctionBody()->CleanupToReparseHelper();
  4235. }
  4236. }
  4237. void FunctionBody::CleanupToReparseHelper()
  4238. {
  4239. this->CleanupRecyclerData(/* isShutdown */ false, true /* capture entry point cleanup stack trace */);
  4240. this->entryPoints->ClearAndZero();
  4241. // Store the originalEntryPoint to restore it back immediately.
  4242. this->CreateNewDefaultEntryPoint();
  4243. this->SetOriginalEntryPoint(this->GetScriptContext()->CurrentThunk);
  4244. if (this->m_defaultEntryPointInfo)
  4245. {
  4246. this->GetDefaultFunctionEntryPointInfo()->entryPointIndex = 0;
  4247. }
  4248. this->SetAuxiliaryData(nullptr);
  4249. this->SetAuxiliaryContextData(nullptr);
  4250. AssertMsg(!this->byteCodeBlock || !this->IsWasmFunction(), "We should never reset the bytecode block for Wasm");
  4251. this->byteCodeBlock = nullptr;
  4252. this->SetLoopHeaderArray(nullptr);
  4253. this->SetConstTable(nullptr);
  4254. this->SetCodeGenRuntimeData(nullptr);
  4255. this->cacheIdToPropertyIdMap = nullptr;
  4256. this->SetFormalsPropIdArray(nullptr);
  4257. this->SetReferencedPropertyIdMap(nullptr);
  4258. this->SetLiteralRegexs(nullptr);
  4259. this->SetSlotIdInCachedScopeToNestedIndexArray(nullptr);
  4260. this->SetStatementMaps(nullptr);
  4261. this->SetCodeGenGetSetRuntimeData(nullptr);
  4262. this->SetPropertyIdOnRegSlotsContainer(nullptr);
  4263. this->profiledLdElemCount = 0;
  4264. this->profiledStElemCount = 0;
  4265. this->profiledCallSiteCount = 0;
  4266. this->profiledArrayCallSiteCount = 0;
  4267. this->profiledDivOrRemCount = 0;
  4268. this->profiledSwitchCount = 0;
  4269. this->profiledReturnTypeCount = 0;
  4270. this->profiledSlotCount = 0;
  4271. this->SetLoopCount(0);
  4272. this->m_envDepth = (uint16)-1;
  4273. this->SetByteCodeCount(0);
  4274. this->SetByteCodeWithoutLDACount(0);
  4275. this->SetByteCodeInLoopCount(0);
  4276. #if ENABLE_PROFILE_INFO
  4277. if (this->dynamicProfileInfo != nullptr)
  4278. {
  4279. SourceContextInfo * sourceContextInfo = GetSourceContextInfo();
  4280. if(sourceContextInfo && sourceContextInfo->sourceDynamicProfileManager)
  4281. {
  4282. sourceContextInfo->sourceDynamicProfileManager->RemoveDynamicProfileInfo(GetFunctionInfo()->GetLocalFunctionId());
  4283. }
  4284. #ifdef DYNAMIC_PROFILE_STORAGE
  4285. DynamicProfileInfoList * profileInfoList = GetScriptContext()->GetProfileInfoList();
  4286. if (profileInfoList)
  4287. {
  4288. FOREACH_SLISTBASE_ENTRY_EDITING(Field(DynamicProfileInfo*), info, profileInfoList, iter)
  4289. {
  4290. if (info->HasFunctionBody() && info->GetFunctionBody() == this)
  4291. {
  4292. iter.UnlinkCurrent();
  4293. break;
  4294. }
  4295. }
  4296. NEXT_SLISTBASE_ENTRY_EDITING;
  4297. }
  4298. #endif
  4299. this->dynamicProfileInfo = nullptr;
  4300. }
  4301. #endif
  4302. this->hasExecutionDynamicProfileInfo = false;
  4303. this->SetFirstTmpRegister(Constants::NoRegister);
  4304. this->SetVarCount(0);
  4305. this->SetConstantCount(0);
  4306. this->SetLocalClosureRegister(Constants::NoRegister);
  4307. this->SetParamClosureRegister(Constants::NoRegister);
  4308. this->SetLocalFrameDisplayRegister(Constants::NoRegister);
  4309. this->SetEnvRegister(Constants::NoRegister);
  4310. this->SetThisRegisterForEventHandler(Constants::NoRegister);
  4311. this->SetFirstInnerScopeRegister(Constants::NoRegister);
  4312. this->SetFuncExprScopeRegister(Constants::NoRegister);
  4313. this->SetInnerScopeCount(0);
  4314. this->hasCachedScopePropIds = false;
  4315. this->ResetObjectLiteralTypes();
  4316. this->SetInlineCacheCount(0);
  4317. this->SetRootObjectLoadInlineCacheStart(0);
  4318. this->SetRootObjectLoadMethodInlineCacheStart(0);
  4319. this->SetRootObjectStoreInlineCacheStart(0);
  4320. this->SetIsInstInlineCacheCount(0);
  4321. this->m_inlineCachesOnFunctionObject = false;
  4322. this->SetReferencedPropertyIdCount(0);
  4323. #if ENABLE_PROFILE_INFO
  4324. this->SetPolymorphicCallSiteInfoHead(nullptr);
  4325. #endif
  4326. this->executionState.SetInterpretedCount(0);
  4327. this->m_hasDoneAllNonLocalReferenced = false;
  4328. this->SetDebuggerScopeIndex(0);
  4329. this->m_isAsmJsScheduledForFullJIT = false;
  4330. this->m_asmJsTotalLoopCount = 0;
  4331. recentlyBailedOutOfJittedLoopBody = false;
  4332. SetLoopInterpreterLimit(CONFIG_FLAG(LoopInterpretCount));
  4333. ReinitializeExecutionModeAndLimits();
  4334. Assert(this->m_sourceInfo.m_probeCount == 0);
  4335. this->m_sourceInfo.m_probeBackingBlock = nullptr;
  4336. #if DBG
  4337. // This could be non-zero if the function threw exception before. Reset it.
  4338. this->m_DEBUG_executionCount = 0;
  4339. #endif
  4340. if (this->m_sourceInfo.pSpanSequence != nullptr)
  4341. {
  4342. HeapDelete(this->m_sourceInfo.pSpanSequence);
  4343. this->m_sourceInfo.pSpanSequence = nullptr;
  4344. }
  4345. if (this->m_sourceInfo.m_auxStatementData != nullptr)
  4346. {
  4347. // This must be consistent with how we allocate the data for this and inner structures.
  4348. // We are using recycler, thus it's enough just to set to NULL.
  4349. Assert(m_scriptContext->GetRecycler()->IsValidObject(m_sourceInfo.m_auxStatementData));
  4350. m_sourceInfo.m_auxStatementData = nullptr;
  4351. }
  4352. }
  4353. void ParseableFunctionInfo::CleanupToReparseHelper()
  4354. {
  4355. #if DYNAMIC_INTERPRETER_THUNK
  4356. if (m_isAsmJsFunction && m_dynamicInterpreterThunk)
  4357. {
  4358. m_scriptContext->ReleaseDynamicAsmJsInterpreterThunk((BYTE*)this->m_dynamicInterpreterThunk, true);
  4359. this->m_dynamicInterpreterThunk = nullptr;
  4360. }
  4361. #endif
  4362. this->SetScopeInfo(nullptr);
  4363. this->SetPropertyIdsForScopeSlotArray(nullptr, 0);
  4364. this->GetUtf8SourceInfo()->DeleteLineOffsetCache();
  4365. // Reset to default.
  4366. this->flags = this->IsClassConstructor() ? Flags_None : Flags_HasNoExplicitReturnValue;
  4367. ResetInParams();
  4368. this->m_isAsmjsMode = false;
  4369. this->m_isAsmJsFunction = false;
  4370. }
  4371. #ifdef ENABLE_SCRIPT_DEBUGGING
  4372. void FunctionBody::SetEntryToDeferParseForDebugger()
  4373. {
  4374. ProxyEntryPointInfo* defaultEntryPointInfo = this->GetDefaultEntryPointInfo();
  4375. if (defaultEntryPointInfo->jsMethod != DefaultDeferredParsingThunk
  4376. #if defined(ENABLE_SCRIPT_PROFILING) || defined(ENABLE_SCRIPT_DEBUGGING)
  4377. && defaultEntryPointInfo->jsMethod != ProfileDeferredParsingThunk
  4378. #endif
  4379. )
  4380. {
  4381. #if defined(ENABLE_SCRIPT_PROFILING) || defined(ENABLE_SCRIPT_DEBUGGING)
  4382. // Just change the thunk, the cleanup will be done once the function gets called.
  4383. if (this->m_scriptContext->CurrentThunk == ProfileEntryThunk)
  4384. {
  4385. defaultEntryPointInfo->jsMethod = ProfileDeferredParsingThunk;
  4386. }
  4387. else
  4388. #endif
  4389. {
  4390. defaultEntryPointInfo->jsMethod = DefaultDeferredParsingThunk;
  4391. }
  4392. this->SetOriginalEntryPoint(DefaultDeferredParsingThunk);
  4393. // Abandon the shared type so a new function will get a new one
  4394. this->deferredPrototypeType = nullptr;
  4395. this->SetAttributes((FunctionInfo::Attributes) (this->GetAttributes() | FunctionInfo::Attributes::DeferredParse));
  4396. }
  4397. // Set other state back to before parse as well
  4398. this->SetStackNestedFunc(false);
  4399. this->SetAuxPtr(AuxPointerType::StackNestedFuncParent, nullptr);
  4400. this->SetReparsed(true);
  4401. #if DBG
  4402. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  4403. OUTPUT_VERBOSE_TRACE(Js::DebuggerPhase, _u("Regenerate Due To Debug Mode: function %s (%s) from script context %p\n"),
  4404. this->GetDisplayName(), this->GetDebugNumberSet(debugStringBuffer), m_scriptContext);
  4405. this->UnlockCounters(); // asuming background jit is stopped and allow the counter setters access again
  4406. #endif
  4407. }
  4408. #endif
  4409. void FunctionBody::ClearEntryPoints()
  4410. {
  4411. if (this->entryPoints)
  4412. {
  4413. this->MapEntryPoints([] (int index, FunctionEntryPointInfo* entryPoint)
  4414. {
  4415. if (nullptr != entryPoint)
  4416. {
  4417. // Finalize = Free up work item if it hasn't been released yet + entry point clean up
  4418. // isShutdown is false because cleanup is called only in the !isShutdown case
  4419. entryPoint->Finalize(/*isShutdown*/ false);
  4420. }
  4421. });
  4422. this->MapLoopHeaders([] (uint loopNumber, LoopHeader* header)
  4423. {
  4424. header->MapEntryPoints([] (int index, LoopEntryPointInfo* entryPoint)
  4425. {
  4426. entryPoint->Cleanup(/*isShutdown*/ false, true /* capture cleanup stack */);
  4427. });
  4428. });
  4429. }
  4430. this->entryPoints->ClearAndZero();
  4431. }
  4432. //
  4433. // For library code all references to jitted entry points need to be removed
  4434. //
  4435. void FunctionBody::ResetEntryPoint()
  4436. {
  4437. ClearEntryPoints();
  4438. this->CreateNewDefaultEntryPoint();
  4439. this->SetOriginalEntryPoint(DefaultEntryThunk);
  4440. m_defaultEntryPointInfo->jsMethod = m_scriptContext->CurrentThunk;
  4441. if (this->deferredPrototypeType)
  4442. {
  4443. // Update old entry points on the deferred prototype type,
  4444. // as they may point to old native code gen regions which age gone now.
  4445. this->deferredPrototypeType->SetEntryPoint(this->GetDefaultEntryPointInfo()->jsMethod);
  4446. this->deferredPrototypeType->SetEntryPointInfo(this->GetDefaultEntryPointInfo());
  4447. }
  4448. ReinitializeExecutionModeAndLimits();
  4449. }
  4450. void FunctionBody::AddDeferParseAttribute()
  4451. {
  4452. this->SetAttributes((FunctionInfo::Attributes) (this->GetAttributes() | FunctionInfo::Attributes::DeferredParse));
  4453. }
  4454. void FunctionBody::RemoveDeferParseAttribute()
  4455. {
  4456. this->SetAttributes((FunctionInfo::Attributes) (this->GetAttributes() & (~FunctionInfo::Attributes::DeferredParse)));
  4457. }
  4458. Js::DebuggerScope * FunctionBody::GetDiagCatchScopeObjectAt(int byteCodeOffset)
  4459. {
  4460. if (GetScopeObjectChain())
  4461. {
  4462. for (int i = 0; i < GetScopeObjectChain()->pScopeChain->Count(); i++)
  4463. {
  4464. Js::DebuggerScope *debuggerScope = GetScopeObjectChain()->pScopeChain->Item(i);
  4465. Assert(debuggerScope);
  4466. if (debuggerScope->IsCatchScope() && debuggerScope->IsOffsetInScope(byteCodeOffset))
  4467. {
  4468. return debuggerScope;
  4469. }
  4470. }
  4471. }
  4472. return nullptr;
  4473. }
  4474. ushort SmallSpanSequence::GetDiff(int current, int prev)
  4475. {
  4476. int diff = current - prev;
  4477. if ((diff) < SHRT_MIN || (diff) >= SHRT_MAX)
  4478. {
  4479. diff = SHRT_MAX;
  4480. if (!this->pActualOffsetList)
  4481. {
  4482. this->pActualOffsetList = JsUtil::GrowingUint32HeapArray::Create(4);
  4483. }
  4484. this->pActualOffsetList->Add(current);
  4485. }
  4486. return (ushort)diff;
  4487. }
  4488. // Get Values of the beginning of the statement at particular index.
  4489. BOOL SmallSpanSequence::GetRangeAt(int index, SmallSpanSequenceIter &iter, int * pCountOfMissed, StatementData & data)
  4490. {
  4491. Assert((uint32)index < pStatementBuffer->Count());
  4492. SmallSpan span(pStatementBuffer->ItemInBuffer((uint32)index));
  4493. int countOfMissed = 0;
  4494. if ((short)span.sourceBegin == SHRT_MAX)
  4495. {
  4496. // Look in ActualOffset store
  4497. Assert(this->pActualOffsetList);
  4498. Assert(this->pActualOffsetList->Count() > 0);
  4499. Assert(this->pActualOffsetList->Count() > (uint32)iter.indexOfActualOffset);
  4500. data.sourceBegin = this->pActualOffsetList->ItemInBuffer((uint32)iter.indexOfActualOffset);
  4501. countOfMissed++;
  4502. }
  4503. else
  4504. {
  4505. data.sourceBegin = iter.accumulatedSourceBegin + (short)span.sourceBegin;
  4506. }
  4507. if (span.bytecodeBegin == SHRT_MAX)
  4508. {
  4509. // Look in ActualOffset store
  4510. Assert(this->pActualOffsetList);
  4511. Assert(this->pActualOffsetList->Count() > 0);
  4512. Assert(this->pActualOffsetList->Count() > (uint32)(iter.indexOfActualOffset + countOfMissed));
  4513. data.bytecodeBegin = this->pActualOffsetList->ItemInBuffer((uint32)iter.indexOfActualOffset + countOfMissed);
  4514. countOfMissed++;
  4515. }
  4516. else
  4517. {
  4518. data.bytecodeBegin = iter.accumulatedBytecodeBegin + span.bytecodeBegin;
  4519. }
  4520. if (pCountOfMissed)
  4521. {
  4522. *pCountOfMissed = countOfMissed;
  4523. }
  4524. return TRUE;
  4525. }
  4526. void SmallSpanSequence::Reset(SmallSpanSequenceIter &iter)
  4527. {
  4528. iter.accumulatedIndex = 0;
  4529. iter.accumulatedSourceBegin = baseValue;
  4530. iter.accumulatedBytecodeBegin = 0;
  4531. iter.indexOfActualOffset = 0;
  4532. }
  4533. BOOL SmallSpanSequence::GetMatchingStatementFromBytecode(int bytecode, SmallSpanSequenceIter &iter, StatementData & data)
  4534. {
  4535. if (Count() > 0 && bytecode >= 0)
  4536. {
  4537. // Support only in forward direction
  4538. if (bytecode < iter.accumulatedBytecodeBegin
  4539. || iter.accumulatedIndex <= 0 || (uint32)iter.accumulatedIndex >= Count())
  4540. {
  4541. // re-initialize the accumulators
  4542. Reset(iter);
  4543. }
  4544. while ((uint32)iter.accumulatedIndex < Count())
  4545. {
  4546. int countOfMissed = 0;
  4547. if (!GetRangeAt(iter.accumulatedIndex, iter, &countOfMissed, data))
  4548. {
  4549. Assert(FALSE);
  4550. break;
  4551. }
  4552. if (data.bytecodeBegin >= bytecode)
  4553. {
  4554. if (data.bytecodeBegin > bytecode)
  4555. {
  4556. // Not exactly at the current bytecode, so it falls in between previous statement.
  4557. data.sourceBegin = iter.accumulatedSourceBegin;
  4558. data.bytecodeBegin = iter.accumulatedBytecodeBegin;
  4559. }
  4560. return TRUE;
  4561. }
  4562. // Look for the next
  4563. iter.accumulatedSourceBegin = data.sourceBegin;
  4564. iter.accumulatedBytecodeBegin = data.bytecodeBegin;
  4565. iter.accumulatedIndex++;
  4566. if (countOfMissed)
  4567. {
  4568. iter.indexOfActualOffset += countOfMissed;
  4569. }
  4570. }
  4571. if (iter.accumulatedIndex != -1)
  4572. {
  4573. // Give the last one.
  4574. Assert(data.bytecodeBegin < bytecode);
  4575. return TRUE;
  4576. }
  4577. }
  4578. // Failed to give the correct one, init to default
  4579. iter.accumulatedIndex = -1;
  4580. return FALSE;
  4581. }
  4582. BOOL SmallSpanSequence::Item(int index, SmallSpanSequenceIter &iter, StatementData & data)
  4583. {
  4584. if (!pStatementBuffer || (uint32)index >= pStatementBuffer->Count())
  4585. {
  4586. return FALSE;
  4587. }
  4588. if (iter.accumulatedIndex <= 0 || iter.accumulatedIndex > index)
  4589. {
  4590. Reset(iter);
  4591. }
  4592. while (iter.accumulatedIndex <= index)
  4593. {
  4594. Assert((uint32)iter.accumulatedIndex < pStatementBuffer->Count());
  4595. int countOfMissed = 0;
  4596. if (!GetRangeAt(iter.accumulatedIndex, iter, &countOfMissed, data))
  4597. {
  4598. Assert(FALSE);
  4599. break;
  4600. }
  4601. // We store the next index
  4602. iter.accumulatedSourceBegin = data.sourceBegin;
  4603. iter.accumulatedBytecodeBegin = data.bytecodeBegin;
  4604. iter.accumulatedIndex++;
  4605. if (countOfMissed)
  4606. {
  4607. iter.indexOfActualOffset += countOfMissed;
  4608. }
  4609. if ((iter.accumulatedIndex - 1) == index)
  4610. {
  4611. return TRUE;
  4612. }
  4613. }
  4614. return FALSE;
  4615. }
  4616. BOOL SmallSpanSequence::Seek(int index, StatementData & data)
  4617. {
  4618. // This method will not alter any state of the variables, so this will just do plain search
  4619. // from the beginning to look for that index.
  4620. SmallSpanSequenceIter iter;
  4621. Reset(iter);
  4622. return Item(index, iter, data);
  4623. }
  4624. PropertyIdOnRegSlotsContainer * PropertyIdOnRegSlotsContainer::New(Recycler * recycler)
  4625. {
  4626. return RecyclerNew(recycler, PropertyIdOnRegSlotsContainer);
  4627. }
  4628. PropertyIdOnRegSlotsContainer::PropertyIdOnRegSlotsContainer()
  4629. : propertyIdsForRegSlots(nullptr), length(0), propertyIdsForFormalArgs(nullptr), formalsUpperBound(Js::Constants::NoRegister)
  4630. {
  4631. }
  4632. void PropertyIdOnRegSlotsContainer::CreateRegSlotsArray(Recycler * recycler, uint _length)
  4633. {
  4634. Assert(propertyIdsForRegSlots == nullptr);
  4635. propertyIdsForRegSlots = RecyclerNewArrayLeafZ(recycler, PropertyId, _length);
  4636. length = _length;
  4637. }
  4638. void PropertyIdOnRegSlotsContainer::SetFormalArgs(PropertyIdArray * formalArgs)
  4639. {
  4640. propertyIdsForFormalArgs = formalArgs;
  4641. }
  4642. //
  4643. // Helper methods for PropertyIdOnRegSlotsContainer
  4644. void PropertyIdOnRegSlotsContainer::Insert(RegSlot reg, PropertyId propId)
  4645. {
  4646. //
  4647. // Reg is being used as an index;
  4648. Assert(propertyIdsForRegSlots);
  4649. Assert(reg < length);
  4650. //
  4651. // the current reg is unaccounted for const reg count. while fetching calculate the actual regslot value.
  4652. Assert(propertyIdsForRegSlots[reg] == 0 || propertyIdsForRegSlots[reg] == propId);
  4653. propertyIdsForRegSlots[reg] = propId;
  4654. }
  4655. void PropertyIdOnRegSlotsContainer::FetchItemAt(uint index, FunctionBody *pFuncBody, __out PropertyId *pPropId, __out RegSlot *pRegSlot)
  4656. {
  4657. Assert(index < length);
  4658. Assert(pPropId);
  4659. Assert(pRegSlot);
  4660. Assert(pFuncBody);
  4661. *pPropId = propertyIdsForRegSlots[index];
  4662. *pRegSlot = pFuncBody->MapRegSlot(index);
  4663. }
  4664. bool PropertyIdOnRegSlotsContainer::IsRegSlotFormal(RegSlot reg)
  4665. {
  4666. if (propertyIdsForFormalArgs != nullptr && reg < length)
  4667. {
  4668. PropertyId propId = propertyIdsForRegSlots[reg];
  4669. for (uint32 i = 0; i < propertyIdsForFormalArgs->count; i++)
  4670. {
  4671. if (propertyIdsForFormalArgs->elements[i] == propId)
  4672. {
  4673. return true;
  4674. }
  4675. }
  4676. }
  4677. return false;
  4678. }
  4679. ScopeType FrameDisplay::GetScopeType(void* scope)
  4680. {
  4681. if(Js::ActivationObject::Is(scope))
  4682. {
  4683. return ScopeType_ActivationObject;
  4684. }
  4685. if(Js::ScopeSlots::Is(scope))
  4686. {
  4687. return ScopeType_SlotArray;
  4688. }
  4689. return ScopeType_WithScope;
  4690. }
  4691. // ScopeSlots
  4692. bool ScopeSlots::IsDebuggerScopeSlotArray()
  4693. {
  4694. return DebuggerScope::Is(slotArray[ScopeMetadataSlotIndex]);
  4695. }
  4696. // DebuggerScope
  4697. bool DebuggerScope::Is(void* ptr)
  4698. {
  4699. if (!ptr)
  4700. {
  4701. return false;
  4702. }
  4703. return VirtualTableInfo<DebuggerScope>::HasVirtualTable(ptr);
  4704. }
  4705. // Get the sibling for the current debugger scope.
  4706. DebuggerScope * DebuggerScope::GetSiblingScope(RegSlot location, FunctionBody *functionBody)
  4707. {
  4708. bool isBlockSlotOrObject = scopeType == Js::DiagExtraScopesType::DiagBlockScopeInSlot || scopeType == Js::DiagExtraScopesType::DiagBlockScopeInObject;
  4709. bool isCatchSlotOrObject = scopeType == Js::DiagExtraScopesType::DiagCatchScopeInSlot || scopeType == Js::DiagExtraScopesType::DiagCatchScopeInObject;
  4710. // This is expected to be called only when the current scope is either slot or activation object.
  4711. Assert(isBlockSlotOrObject || isCatchSlotOrObject);
  4712. if (siblingScope == nullptr)
  4713. {
  4714. // If the sibling isn't there, attempt to retrieve it if we're reparsing or create it anew if this is the first parse.
  4715. siblingScope = functionBody->RecordStartScopeObject(isBlockSlotOrObject ? Js::DiagExtraScopesType::DiagBlockScopeDirect : Js::DiagExtraScopesType::DiagCatchScopeDirect, GetStart(), location);
  4716. }
  4717. return siblingScope;
  4718. }
  4719. // Adds a new property to be tracked in the debugger scope.
  4720. // location - The slot array index or register slot location of where the property is stored.
  4721. // propertyId - The property ID of the property.
  4722. // flags - Flags that help describe the property.
  4723. void DebuggerScope::AddProperty(RegSlot location, Js::PropertyId propertyId, DebuggerScopePropertyFlags flags)
  4724. {
  4725. DebuggerScopeProperty scopeProperty;
  4726. scopeProperty.location = location;
  4727. scopeProperty.propId = propertyId;
  4728. // This offset is uninitialized until the property is initialized (with a ld opcode, for example).
  4729. scopeProperty.byteCodeInitializationOffset = Constants::InvalidByteCodeOffset;
  4730. scopeProperty.flags = flags;
  4731. // Delay allocate the property list so we don't take up memory if there are no properties in this scope.
  4732. // Scopes are created during non-debug mode as well so we want to keep them as small as possible.
  4733. this->EnsurePropertyListIsAllocated();
  4734. // The property doesn't exist yet, so add it.
  4735. this->scopeProperties->Add(scopeProperty);
  4736. }
  4737. bool DebuggerScope::HasProperty(Js::PropertyId propertyId)
  4738. {
  4739. int i = -1;
  4740. return GetPropertyIndex(propertyId, i);
  4741. }
  4742. bool DebuggerScope::GetPropertyIndex(Js::PropertyId propertyId, int& index)
  4743. {
  4744. if (!this->HasProperties())
  4745. {
  4746. index = -1;
  4747. return false;
  4748. }
  4749. bool found = this->scopeProperties->MapUntil( [&](int i, const DebuggerScopeProperty& scopeProperty) {
  4750. if(scopeProperty.propId == propertyId)
  4751. {
  4752. index = scopeProperty.location;
  4753. return true;
  4754. }
  4755. return false;
  4756. });
  4757. if(!found)
  4758. {
  4759. return false;
  4760. }
  4761. return true;
  4762. }
  4763. #if DBG
  4764. void DebuggerScope::Dump()
  4765. {
  4766. int indent = (GetScopeDepth() - 1) * 4;
  4767. Output::Print(indent, _u("Begin scope: Address: %p Type: %s Location: %d Sibling: %p Range: [%d, %d]\n "), this, GetDebuggerScopeTypeString(scopeType), scopeLocation, PointerValue(this->siblingScope), range.begin, range.end);
  4768. if (this->HasProperties())
  4769. {
  4770. this->scopeProperties->Map( [=] (int i, Js::DebuggerScopeProperty& scopeProperty) {
  4771. Output::Print(indent, _u("%s(%d) Location: %d Const: %s Initialized: %d\n"), ThreadContext::GetContextForCurrentThread()->GetPropertyName(scopeProperty.propId)->GetBuffer(),
  4772. scopeProperty.propId, scopeProperty.location, scopeProperty.IsConst() ? _u("true"): _u("false"), scopeProperty.byteCodeInitializationOffset);
  4773. });
  4774. }
  4775. Output::Print(_u("\n"));
  4776. }
  4777. // Returns the debugger scope type in string format.
  4778. PCWSTR DebuggerScope::GetDebuggerScopeTypeString(DiagExtraScopesType scopeType)
  4779. {
  4780. switch (scopeType)
  4781. {
  4782. case DiagExtraScopesType::DiagBlockScopeDirect:
  4783. return _u("DiagBlockScopeDirect");
  4784. case DiagExtraScopesType::DiagBlockScopeInObject:
  4785. return _u("DiagBlockScopeInObject");
  4786. case DiagExtraScopesType::DiagBlockScopeInSlot:
  4787. return _u("DiagBlockScopeInSlot");
  4788. case DiagExtraScopesType::DiagBlockScopeRangeEnd:
  4789. return _u("DiagBlockScopeRangeEnd");
  4790. case DiagExtraScopesType::DiagCatchScopeDirect:
  4791. return _u("DiagCatchScopeDirect");
  4792. case DiagExtraScopesType::DiagCatchScopeInObject:
  4793. return _u("DiagCatchScopeInObject");
  4794. case DiagExtraScopesType::DiagCatchScopeInSlot:
  4795. return _u("DiagCatchScopeInSlot");
  4796. case DiagExtraScopesType::DiagUnknownScope:
  4797. return _u("DiagUnknownScope");
  4798. case DiagExtraScopesType::DiagWithScope:
  4799. return _u("DiagWithScope");
  4800. case DiagExtraScopesType::DiagParamScope:
  4801. return _u("DiagParamScope");
  4802. case DiagExtraScopesType::DiagParamScopeInObject:
  4803. return _u("DiagParamScopeInObject");
  4804. default:
  4805. AssertMsg(false, "Missing a debug scope type.");
  4806. return _u("");
  4807. }
  4808. }
  4809. #endif
  4810. #if ENABLE_TTD
  4811. Js::PropertyId DebuggerScope::GetPropertyIdForSlotIndex_TTD(uint32 slotIndex) const
  4812. {
  4813. const Js::DebuggerScopeProperty& scopeProperty = this->scopeProperties->Item(slotIndex);
  4814. return scopeProperty.propId;
  4815. }
  4816. #endif
  4817. // Updates the current offset of where the property is first initialized. This is used to
  4818. // detect whether or not a property is in a dead zone when broken in the debugger.
  4819. // location - The slot array index or register slot location of where the property is stored.
  4820. // propertyId - The property ID of the property.
  4821. // byteCodeOffset - The offset to set the initialization point at.
  4822. // isFunctionDeclaration - Whether or not the property is a function declaration or not. Used for verification.
  4823. // <returns> - True if the property was found and updated for the current scope, else false.
  4824. bool DebuggerScope::UpdatePropertyInitializationOffset(
  4825. RegSlot location,
  4826. Js::PropertyId propertyId,
  4827. int byteCodeOffset,
  4828. bool isFunctionDeclaration /*= false*/)
  4829. {
  4830. if (UpdatePropertyInitializationOffsetInternal(location, propertyId, byteCodeOffset, isFunctionDeclaration))
  4831. {
  4832. return true;
  4833. }
  4834. if (siblingScope != nullptr && siblingScope->UpdatePropertyInitializationOffsetInternal(location, propertyId, byteCodeOffset, isFunctionDeclaration))
  4835. {
  4836. return true;
  4837. }
  4838. return false;
  4839. }
  4840. bool DebuggerScope::UpdatePropertyInitializationOffsetInternal(
  4841. RegSlot location,
  4842. Js::PropertyId propertyId,
  4843. int byteCodeOffset,
  4844. bool isFunctionDeclaration /*= false*/)
  4845. {
  4846. if (scopeProperties == nullptr)
  4847. {
  4848. return false;
  4849. }
  4850. for (int i = 0; i < scopeProperties->Count(); ++i)
  4851. {
  4852. DebuggerScopeProperty propertyItem = scopeProperties->Item(i);
  4853. if (propertyItem.propId == propertyId && propertyItem.location == location)
  4854. {
  4855. if (propertyItem.byteCodeInitializationOffset == Constants::InvalidByteCodeOffset)
  4856. {
  4857. propertyItem.byteCodeInitializationOffset = byteCodeOffset;
  4858. scopeProperties->SetExistingItem(i, propertyItem);
  4859. }
  4860. #if DBG
  4861. else
  4862. {
  4863. // If the bytecode initialization offset is not Constants::InvalidByteCodeOffset,
  4864. // it means we have two or more functions declared in the same scope with the same name
  4865. // and one has already been marked. We track each location with a property entry
  4866. // on the debugging side (when calling DebuggerScope::AddProperty()) as opposed to scanning
  4867. // and checking if the property already exists each time we add in order to avoid duplicates.
  4868. AssertMsg(isFunctionDeclaration, "Only function declarations can be defined more than once in the same scope with the same name.");
  4869. AssertMsg(propertyItem.byteCodeInitializationOffset == byteCodeOffset, "The bytecode offset for all function declarations should be identical for this scope.");
  4870. }
  4871. #endif // DBG
  4872. return true;
  4873. }
  4874. }
  4875. return false;
  4876. }
  4877. // Updates the debugger scopes fields due to a regeneration of bytecode (happens during debugger attach or detach, for
  4878. // example).
  4879. void DebuggerScope::UpdateDueToByteCodeRegeneration(DiagExtraScopesType scopeType, int start, RegSlot scopeLocation)
  4880. {
  4881. #if DBG
  4882. if (this->scopeType != Js::DiagUnknownScope)
  4883. {
  4884. // If the scope is unknown, it was deserialized without a scope type. Otherwise, it should not have changed.
  4885. // The scope type can change on a re-parse in certain scenarios related to eval detection in legacy mode -> Winblue: 272122
  4886. AssertMsg(this->scopeType == scopeType, "The debugger scope type should not have changed when generating bytecode again.");
  4887. }
  4888. #endif // DBG
  4889. this->scopeType = scopeType;
  4890. this->SetBegin(start);
  4891. if(this->scopeProperties)
  4892. {
  4893. this->scopeProperties->Clear();
  4894. }
  4895. // Reset the scope location as it may have changed during bytecode generation from the last run.
  4896. this->SetScopeLocation(scopeLocation);
  4897. if (siblingScope)
  4898. {
  4899. // If we had a sibling scope during initial parsing, clear it now so that it will be reset
  4900. // when it is retrieved during this bytecode generation pass, in GetSiblingScope().
  4901. // GetSiblingScope() will ensure that the FunctionBody currentDebuggerScopeIndex value is
  4902. // updated accordingly to account for future scopes coming after the sibling.
  4903. // Calling of GetSiblingScope() will happen when register properties are added to this scope
  4904. // via TrackRegisterPropertyForDebugger().
  4905. siblingScope = nullptr;
  4906. }
  4907. }
  4908. void DebuggerScope::UpdatePropertiesInForInOrOfCollectionScope()
  4909. {
  4910. if (this->scopeProperties != nullptr)
  4911. {
  4912. this->scopeProperties->All([&](Js::DebuggerScopeProperty& propertyItem)
  4913. {
  4914. propertyItem.flags |= DebuggerScopePropertyFlags_ForInOrOfCollection;
  4915. return true;
  4916. });
  4917. }
  4918. }
  4919. void DebuggerScope::EnsurePropertyListIsAllocated()
  4920. {
  4921. if (this->scopeProperties == nullptr)
  4922. {
  4923. this->scopeProperties = RecyclerNew(this->recycler, DebuggerScopePropertyList, this->recycler);
  4924. }
  4925. }
  4926. // Checks if the passed in ByteCodeGenerator offset is in this scope's being/end range.
  4927. bool DebuggerScope::IsOffsetInScope(int offset) const
  4928. {
  4929. Assert(this->range.end != -1);
  4930. return this->range.Includes(offset);
  4931. }
  4932. // Determines if the DebuggerScope contains a property with the passed in ID and
  4933. // location in the internal property list.
  4934. // propertyId - The ID of the property to search for.
  4935. // location - The slot array index or register to search for.
  4936. // outScopeProperty - Optional parameter that will return the property, if found.
  4937. bool DebuggerScope::Contains(Js::PropertyId propertyId, RegSlot location) const
  4938. {
  4939. DebuggerScopeProperty tempProperty;
  4940. return TryGetProperty(propertyId, location, &tempProperty);
  4941. }
  4942. // Gets whether or not the scope is a block scope (non-catch or with).
  4943. bool DebuggerScope::IsBlockScope() const
  4944. {
  4945. AssertMsg(this->scopeType != Js::DiagBlockScopeRangeEnd, "Debugger scope type should never be set to range end - only reserved for marking the end of a scope (not persisted).");
  4946. return this->scopeType == Js::DiagBlockScopeDirect
  4947. || this->scopeType == Js::DiagBlockScopeInObject
  4948. || this->scopeType == Js::DiagBlockScopeInSlot
  4949. || this->scopeType == Js::DiagBlockScopeRangeEnd;
  4950. }
  4951. // Gets whether or not the scope is a catch block scope.
  4952. bool DebuggerScope::IsCatchScope() const
  4953. {
  4954. return this->scopeType == Js::DiagCatchScopeDirect
  4955. || this->scopeType == Js::DiagCatchScopeInObject
  4956. || this->scopeType == Js::DiagCatchScopeInSlot;
  4957. }
  4958. // Gets whether or not the scope is a with block scope.
  4959. bool DebuggerScope::IsWithScope() const
  4960. {
  4961. return this->scopeType == Js::DiagWithScope;
  4962. }
  4963. // Gets whether or not the scope is a slot array scope.
  4964. bool DebuggerScope::IsSlotScope() const
  4965. {
  4966. return this->scopeType == Js::DiagBlockScopeInSlot
  4967. || this->scopeType == Js::DiagCatchScopeInSlot;
  4968. }
  4969. bool DebuggerScope::IsParamScope() const
  4970. {
  4971. return this->scopeType == Js::DiagParamScope
  4972. || this->scopeType == Js::DiagParamScopeInObject;
  4973. }
  4974. // Gets whether or not the scope has any properties in it.
  4975. bool DebuggerScope::HasProperties() const
  4976. {
  4977. return this->scopeProperties && this->scopeProperties->Count() > 0;
  4978. }
  4979. // Checks if this scope is an ancestor of the passed in scope.
  4980. bool DebuggerScope::IsAncestorOf(const DebuggerScope* potentialChildScope)
  4981. {
  4982. if (potentialChildScope == nullptr)
  4983. {
  4984. // If the child scope is null, it represents the global scope which
  4985. // cannot be a child of anything.
  4986. return false;
  4987. }
  4988. const DebuggerScope* currentScope = potentialChildScope;
  4989. while (currentScope)
  4990. {
  4991. if (currentScope->GetParentScope() == this)
  4992. {
  4993. return true;
  4994. }
  4995. currentScope = currentScope->GetParentScope();
  4996. }
  4997. return false;
  4998. }
  4999. // Checks if all properties of the scope are currently in a dead zone given the specified offset.
  5000. bool DebuggerScope::AreAllPropertiesInDeadZone(int byteCodeOffset) const
  5001. {
  5002. if (!this->HasProperties())
  5003. {
  5004. return false;
  5005. }
  5006. return this->scopeProperties->All([&](Js::DebuggerScopeProperty& propertyItem)
  5007. {
  5008. return propertyItem.IsInDeadZone(byteCodeOffset);
  5009. });
  5010. }
  5011. // Attempts to get the specified property. Returns true if the property was copied to the structure; false otherwise.
  5012. bool DebuggerScope::TryGetProperty(Js::PropertyId propertyId, RegSlot location, DebuggerScopeProperty* outScopeProperty) const
  5013. {
  5014. Assert(outScopeProperty);
  5015. if (scopeProperties == nullptr)
  5016. {
  5017. return false;
  5018. }
  5019. for (int i = 0; i < scopeProperties->Count(); ++i)
  5020. {
  5021. DebuggerScopeProperty propertyItem = scopeProperties->Item(i);
  5022. if (propertyItem.propId == propertyId && propertyItem.location == location)
  5023. {
  5024. *outScopeProperty = propertyItem;
  5025. return true;
  5026. }
  5027. }
  5028. return false;
  5029. }
  5030. bool DebuggerScope::TryGetValidProperty(Js::PropertyId propertyId, RegSlot location, int offset, DebuggerScopeProperty* outScopeProperty, bool* isInDeadZone) const
  5031. {
  5032. if (TryGetProperty(propertyId, location, outScopeProperty))
  5033. {
  5034. if (IsOffsetInScope(offset))
  5035. {
  5036. if (isInDeadZone != nullptr)
  5037. {
  5038. *isInDeadZone = outScopeProperty->IsInDeadZone(offset);
  5039. }
  5040. return true;
  5041. }
  5042. }
  5043. return false;
  5044. }
  5045. void DebuggerScope::SetBegin(int begin)
  5046. {
  5047. range.begin = begin;
  5048. if (siblingScope != nullptr)
  5049. {
  5050. siblingScope->SetBegin(begin);
  5051. }
  5052. }
  5053. void DebuggerScope::SetEnd(int end)
  5054. {
  5055. range.end = end;
  5056. if (siblingScope != nullptr)
  5057. {
  5058. siblingScope->SetEnd(end);
  5059. }
  5060. }
  5061. // Finds the common ancestor scope between this scope and the passed in scope.
  5062. // Returns nullptr if the scopes are part of different trees.
  5063. DebuggerScope* DebuggerScope::FindCommonAncestor(DebuggerScope* debuggerScope)
  5064. {
  5065. AnalysisAssert(debuggerScope);
  5066. if (this == debuggerScope)
  5067. {
  5068. return debuggerScope;
  5069. }
  5070. if (this->IsAncestorOf(debuggerScope))
  5071. {
  5072. return this;
  5073. }
  5074. if (debuggerScope->IsAncestorOf(this))
  5075. {
  5076. return debuggerScope;
  5077. }
  5078. DebuggerScope* firstNode = this;
  5079. DebuggerScope* secondNode = debuggerScope;
  5080. int firstDepth = firstNode->GetScopeDepth();
  5081. int secondDepth = secondNode->GetScopeDepth();
  5082. // Calculate the depth difference in order to bring the deep node up to the sibling
  5083. // level of the shorter node.
  5084. int depthDifference = abs(firstDepth - secondDepth);
  5085. DebuggerScope*& nodeToBringUp = firstDepth > secondDepth ? firstNode : secondNode;
  5086. while (depthDifference > 0)
  5087. {
  5088. AnalysisAssert(nodeToBringUp);
  5089. nodeToBringUp = nodeToBringUp->GetParentScope();
  5090. --depthDifference;
  5091. }
  5092. // Move up the tree and see where the nodes meet.
  5093. while (firstNode && secondNode)
  5094. {
  5095. if (firstNode == secondNode)
  5096. {
  5097. return firstNode;
  5098. }
  5099. firstNode = firstNode->GetParentScope();
  5100. secondNode = secondNode->GetParentScope();
  5101. }
  5102. // The nodes are not part of the same scope tree.
  5103. return nullptr;
  5104. }
  5105. // Gets the depth of the scope in the parent link tree.
  5106. int DebuggerScope::GetScopeDepth() const
  5107. {
  5108. int depth = 0;
  5109. const DebuggerScope* currentDebuggerScope = this;
  5110. while (currentDebuggerScope)
  5111. {
  5112. currentDebuggerScope = currentDebuggerScope->GetParentScope();
  5113. ++depth;
  5114. }
  5115. return depth;
  5116. }
  5117. bool ScopeObjectChain::TryGetDebuggerScopePropertyInfo(PropertyId propertyId, RegSlot location, int offset, bool* isPropertyInDebuggerScope, bool *isConst, bool* isInDeadZone)
  5118. {
  5119. Assert(pScopeChain);
  5120. Assert(isPropertyInDebuggerScope);
  5121. Assert(isConst);
  5122. *isPropertyInDebuggerScope = false;
  5123. *isConst = false;
  5124. // Search through each block scope until we find the current scope. If the register was found
  5125. // in any of the scopes going down until we reach the scope of the debug break, then it's in scope.
  5126. // if found but not in the scope, the out param will be updated (since it is actually a let or const), so that caller can make a call accordingly.
  5127. for (int i = 0; i < pScopeChain->Count(); i++)
  5128. {
  5129. Js::DebuggerScope *debuggerScope = pScopeChain->Item(i);
  5130. DebuggerScopeProperty debuggerScopeProperty;
  5131. if (!debuggerScope->IsParamScope() && debuggerScope->TryGetProperty(propertyId, location, &debuggerScopeProperty))
  5132. {
  5133. bool isOffsetInScope = debuggerScope->IsOffsetInScope(offset);
  5134. // For the Object scope, all the properties will have the same location (-1) so they can match. Use further check below to determine the propertyInDebuggerScope
  5135. *isPropertyInDebuggerScope = isOffsetInScope || !debuggerScope->IsBlockObjectScope();
  5136. if (isOffsetInScope)
  5137. {
  5138. if (isInDeadZone != nullptr)
  5139. {
  5140. *isInDeadZone = debuggerScopeProperty.IsInDeadZone(offset);
  5141. }
  5142. *isConst = debuggerScopeProperty.IsConst();
  5143. return true;
  5144. }
  5145. }
  5146. }
  5147. return false;
  5148. }
  5149. void FunctionBody::AllocateForInCache()
  5150. {
  5151. uint profiledForInLoopCount = this->GetProfiledForInLoopCount();
  5152. if (profiledForInLoopCount == 0)
  5153. {
  5154. return;
  5155. }
  5156. this->SetAuxPtr(AuxPointerType::ForInCacheArray, AllocatorNewArrayZ(CacheAllocator, this->GetScriptContext()->ForInCacheAllocator(), ForInCache, profiledForInLoopCount));
  5157. }
  5158. ForInCache * FunctionBody::GetForInCache(uint index)
  5159. {
  5160. Assert(index < this->GetProfiledForInLoopCount());
  5161. return &((ForInCache *)this->GetAuxPtr(AuxPointerType::ForInCacheArray))[index];
  5162. }
  5163. ForInCache * FunctionBody::GetForInCacheArray()
  5164. {
  5165. return ((ForInCache *)this->GetAuxPtrWithLock(AuxPointerType::ForInCacheArray));
  5166. }
  5167. void FunctionBody::CleanUpForInCache(bool isShutdown)
  5168. {
  5169. uint profiledForInLoopCount = this->GetProfiledForInLoopCount();
  5170. if (profiledForInLoopCount == 0)
  5171. {
  5172. return;
  5173. }
  5174. ForInCache * forInCacheArray = (ForInCache *)this->GetAuxPtr(AuxPointerType::ForInCacheArray);
  5175. if (forInCacheArray)
  5176. {
  5177. if (isShutdown)
  5178. {
  5179. memset(forInCacheArray, 0, sizeof(ForInCache) * profiledForInLoopCount);
  5180. }
  5181. else
  5182. {
  5183. AllocatorDeleteArray(CacheAllocator, this->GetScriptContext()->ForInCacheAllocator(), profiledForInLoopCount, forInCacheArray);
  5184. this->SetAuxPtr(AuxPointerType::ForInCacheArray, nullptr);
  5185. }
  5186. }
  5187. }
  5188. void FunctionBody::AllocateInlineCache()
  5189. {
  5190. Assert(this->inlineCaches == nullptr);
  5191. uint isInstInlineCacheStart = this->GetInlineCacheCount();
  5192. uint totalCacheCount = isInstInlineCacheStart + GetIsInstInlineCacheCount();
  5193. if (totalCacheCount != 0)
  5194. {
  5195. // Root object inline cache are not leaf
  5196. void ** inlineCaches = RecyclerNewArrayZ(this->m_scriptContext->GetRecycler(),
  5197. void*, totalCacheCount);
  5198. #if DBG
  5199. this->m_inlineCacheTypes = RecyclerNewArrayLeafZ(this->m_scriptContext->GetRecycler(),
  5200. byte, totalCacheCount);
  5201. #endif
  5202. uint i = 0;
  5203. uint plainInlineCacheEnd = GetRootObjectLoadInlineCacheStart();
  5204. __analysis_assume(plainInlineCacheEnd <= totalCacheCount);
  5205. for (; i < plainInlineCacheEnd; i++)
  5206. {
  5207. inlineCaches[i] = AllocatorNewZ(InlineCacheAllocator,
  5208. this->m_scriptContext->GetInlineCacheAllocator(), InlineCache);
  5209. }
  5210. Js::RootObjectBase * rootObject = this->GetRootObject();
  5211. ThreadContext * threadContext = this->GetScriptContext()->GetThreadContext();
  5212. uint rootObjectLoadInlineCacheEnd = GetRootObjectLoadMethodInlineCacheStart();
  5213. __analysis_assume(rootObjectLoadInlineCacheEnd <= totalCacheCount);
  5214. for (; i < rootObjectLoadInlineCacheEnd; i++)
  5215. {
  5216. inlineCaches[i] = rootObject->GetInlineCache(
  5217. threadContext->GetPropertyName(this->GetPropertyIdFromCacheId(i)), false, false);
  5218. }
  5219. uint rootObjectLoadMethodInlineCacheEnd = GetRootObjectStoreInlineCacheStart();
  5220. __analysis_assume(rootObjectLoadMethodInlineCacheEnd <= totalCacheCount);
  5221. for (; i < rootObjectLoadMethodInlineCacheEnd; i++)
  5222. {
  5223. inlineCaches[i] = rootObject->GetInlineCache(
  5224. threadContext->GetPropertyName(this->GetPropertyIdFromCacheId(i)), true, false);
  5225. }
  5226. uint rootObjectStoreInlineCacheEnd = isInstInlineCacheStart;
  5227. __analysis_assume(rootObjectStoreInlineCacheEnd <= totalCacheCount);
  5228. for (; i < rootObjectStoreInlineCacheEnd; i++)
  5229. {
  5230. #pragma prefast(suppress:6386, "The analysis assume didn't help prefast figure out this is in range")
  5231. inlineCaches[i] = rootObject->GetInlineCache(
  5232. threadContext->GetPropertyName(this->GetPropertyIdFromCacheId(i)), false, true);
  5233. }
  5234. for (; i < totalCacheCount; i++)
  5235. {
  5236. inlineCaches[i] = AllocatorNewStructZ(CacheAllocator,
  5237. this->m_scriptContext->GetIsInstInlineCacheAllocator(), IsInstInlineCache);
  5238. }
  5239. #if DBG
  5240. this->m_inlineCacheTypes = RecyclerNewArrayLeafZ(this->m_scriptContext->GetRecycler(),
  5241. byte, totalCacheCount);
  5242. #endif
  5243. this->inlineCaches = inlineCaches;
  5244. }
  5245. }
  5246. InlineCache *FunctionBody::GetInlineCache(uint index)
  5247. {
  5248. Assert(this->inlineCaches != nullptr);
  5249. Assert(index < this->GetInlineCacheCount());
  5250. #if DBG
  5251. Assert(this->m_inlineCacheTypes[index] == InlineCacheTypeNone ||
  5252. this->m_inlineCacheTypes[index] == InlineCacheTypeInlineCache);
  5253. this->m_inlineCacheTypes[index] = InlineCacheTypeInlineCache;
  5254. #endif
  5255. return reinterpret_cast<InlineCache *>(this->inlineCaches[index]);
  5256. }
  5257. bool FunctionBody::CanFunctionObjectHaveInlineCaches()
  5258. {
  5259. if (this->DoStackNestedFunc() || this->IsCoroutine())
  5260. {
  5261. return false;
  5262. }
  5263. uint totalCacheCount = this->GetInlineCacheCount() + this->GetIsInstInlineCacheCount();
  5264. if (PHASE_FORCE(Js::ScriptFunctionWithInlineCachePhase, this) && totalCacheCount > 0)
  5265. {
  5266. return true;
  5267. }
  5268. // Only have inline caches on function object for possible inlining candidates.
  5269. // Since we don't know the size of the top function, check against the maximum possible inline threshold
  5270. // Negative inline byte code size threshold will disable inline cache on function object.
  5271. const int byteCodeSizeThreshold = CONFIG_FLAG(InlineThreshold) + CONFIG_FLAG(InlineThresholdAdjustCountInSmallFunction);
  5272. if (byteCodeSizeThreshold < 0 || this->GetByteCodeWithoutLDACount() > (uint)byteCodeSizeThreshold)
  5273. {
  5274. return false;
  5275. }
  5276. // Negative FuncObjectInlineCacheThreshold will disable inline cache on function object.
  5277. if (CONFIG_FLAG(FuncObjectInlineCacheThreshold) < 0 || totalCacheCount > (uint)CONFIG_FLAG(FuncObjectInlineCacheThreshold) || totalCacheCount == 0)
  5278. {
  5279. return false;
  5280. }
  5281. return true;
  5282. }
  5283. void** FunctionBody::GetInlineCaches()
  5284. {
  5285. return this->inlineCaches;
  5286. }
  5287. #if DBG
  5288. byte* FunctionBody::GetInlineCacheTypes()
  5289. {
  5290. return this->m_inlineCacheTypes;
  5291. }
  5292. #endif
  5293. IsInstInlineCache *FunctionBody::GetIsInstInlineCache(uint index)
  5294. {
  5295. Assert(this->inlineCaches != nullptr);
  5296. Assert(index < GetIsInstInlineCacheCount());
  5297. index += this->GetInlineCacheCount();
  5298. #if DBG
  5299. Assert(this->m_inlineCacheTypes[index] == InlineCacheTypeNone ||
  5300. this->m_inlineCacheTypes[index] == InlineCacheTypeIsInst);
  5301. this->m_inlineCacheTypes[index] = InlineCacheTypeIsInst;
  5302. #endif
  5303. return reinterpret_cast<IsInstInlineCache *>(this->inlineCaches[index]);
  5304. }
  5305. PolymorphicInlineCache * FunctionBody::GetPolymorphicInlineCache(uint index)
  5306. {
  5307. return this->polymorphicInlineCaches.GetInlineCache(this, index);
  5308. }
  5309. PolymorphicInlineCache * FunctionBody::CreateNewPolymorphicInlineCache(uint index, PropertyId propertyId, InlineCache * inlineCache)
  5310. {
  5311. Assert(GetPolymorphicInlineCache(index) == nullptr);
  5312. // Only create polymorphic inline caches for non-root inline cache indexes
  5313. if (index < GetRootObjectLoadInlineCacheStart()
  5314. #if DBG
  5315. && !PHASE_OFF1(Js::PolymorphicInlineCachePhase)
  5316. #endif
  5317. )
  5318. {
  5319. PolymorphicInlineCache * polymorphicInlineCache = CreatePolymorphicInlineCache(index, MinPolymorphicInlineCacheSize);
  5320. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  5321. if (PHASE_VERBOSE_TRACE1(Js::PolymorphicInlineCachePhase))
  5322. {
  5323. this->DumpFullFunctionName();
  5324. Output::Print(_u(": New PIC, index = %d, size = %d\n"), index, MinPolymorphicInlineCacheSize);
  5325. }
  5326. #endif
  5327. #if PHASE_PRINT_INTRUSIVE_TESTTRACE1
  5328. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  5329. #endif
  5330. PHASE_PRINT_INTRUSIVE_TESTTRACE1(
  5331. Js::PolymorphicInlineCachePhase,
  5332. _u("TestTrace PIC: New, Function %s (%s), 0x%x, index = %d, size = %d\n"), this->GetDisplayName(), this->GetDebugNumberSet(debugStringBuffer), polymorphicInlineCache, index, MinPolymorphicInlineCacheSize);
  5333. uint indexInPolymorphicCache = polymorphicInlineCache->GetInlineCacheIndexForType(inlineCache->GetType());
  5334. inlineCache->CopyTo(propertyId, m_scriptContext, &(polymorphicInlineCache->GetInlineCaches()[indexInPolymorphicCache]));
  5335. polymorphicInlineCache->UpdateInlineCachesFillInfo(indexInPolymorphicCache, true /*set*/);
  5336. return polymorphicInlineCache;
  5337. }
  5338. return nullptr;
  5339. }
  5340. PolymorphicInlineCache * FunctionBody::CreateBiggerPolymorphicInlineCache(uint index, PropertyId propertyId)
  5341. {
  5342. PolymorphicInlineCache * polymorphicInlineCache = GetPolymorphicInlineCache(index);
  5343. Assert(polymorphicInlineCache && polymorphicInlineCache->CanAllocateBigger());
  5344. uint16 polymorphicInlineCacheSize = polymorphicInlineCache->GetSize();
  5345. uint16 newPolymorphicInlineCacheSize = PolymorphicInlineCache::GetNextSize(polymorphicInlineCacheSize);
  5346. Assert(newPolymorphicInlineCacheSize > polymorphicInlineCacheSize);
  5347. PolymorphicInlineCache * newPolymorphicInlineCache = CreatePolymorphicInlineCache(index, newPolymorphicInlineCacheSize);
  5348. polymorphicInlineCache->CopyTo(propertyId, m_scriptContext, newPolymorphicInlineCache);
  5349. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  5350. if (PHASE_VERBOSE_TRACE1(Js::PolymorphicInlineCachePhase))
  5351. {
  5352. this->DumpFullFunctionName();
  5353. Output::Print(_u(": Bigger PIC, index = %d, oldSize = %d, newSize = %d\n"), index, polymorphicInlineCacheSize, newPolymorphicInlineCacheSize);
  5354. }
  5355. #endif
  5356. #if PHASE_PRINT_INTRUSIVE_TESTTRACE1
  5357. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  5358. #endif
  5359. PHASE_PRINT_INTRUSIVE_TESTTRACE1(
  5360. Js::PolymorphicInlineCachePhase,
  5361. _u("TestTrace PIC: Bigger, Function %s (%s), 0x%x, index = %d, size = %d\n"), this->GetDisplayName(), this->GetDebugNumberSet(debugStringBuffer), newPolymorphicInlineCache, index, newPolymorphicInlineCacheSize);
  5362. return newPolymorphicInlineCache;
  5363. }
  5364. void FunctionBody::ResetInlineCaches()
  5365. {
  5366. SetInlineCacheCount(0);
  5367. SetRootObjectLoadInlineCacheStart(0);
  5368. SetRootObjectStoreInlineCacheStart(0);
  5369. SetIsInstInlineCacheCount(0);
  5370. this->inlineCaches = nullptr;
  5371. this->polymorphicInlineCaches.Reset();
  5372. }
  5373. PolymorphicInlineCache * FunctionBody::CreatePolymorphicInlineCache(uint index, uint16 size)
  5374. {
  5375. Recycler * recycler = this->m_scriptContext->GetRecycler();
  5376. PolymorphicInlineCache * newPolymorphicInlineCache = FunctionBodyPolymorphicInlineCache::New(size, this);
  5377. this->polymorphicInlineCaches.SetInlineCache(recycler, this, index, newPolymorphicInlineCache);
  5378. return newPolymorphicInlineCache;
  5379. }
  5380. uint FunctionBody::NewObjectLiteral()
  5381. {
  5382. Assert(this->GetObjectLiteralTypes() == nullptr);
  5383. return IncObjLiteralCount();
  5384. }
  5385. Field(DynamicType*)* FunctionBody::GetObjectLiteralTypeRef(uint index)
  5386. {
  5387. Assert(index < GetObjLiteralCount());
  5388. auto literalTypes = this->GetObjectLiteralTypes();
  5389. Assert(literalTypes != nullptr);
  5390. return literalTypes + index;
  5391. }
  5392. Field(DynamicType*)* FunctionBody::GetObjectLiteralTypeRefWithLock(uint index)
  5393. {
  5394. Assert(index < GetObjLiteralCount());
  5395. auto literalTypes = this->GetObjectLiteralTypesWithLock();
  5396. Assert(literalTypes != nullptr);
  5397. return literalTypes + index;
  5398. }
  5399. void FunctionBody::AllocateObjectLiteralTypeArray()
  5400. {
  5401. Assert(this->GetObjectLiteralTypes() == nullptr);
  5402. uint objLiteralCount = GetObjLiteralCount();
  5403. if (objLiteralCount == 0)
  5404. {
  5405. return;
  5406. }
  5407. this->SetObjectLiteralTypes(RecyclerNewArrayZ(this->GetScriptContext()->GetRecycler(), DynamicType *, objLiteralCount));
  5408. }
  5409. uint FunctionBody::NewLiteralRegex()
  5410. {
  5411. if (this->GetLiteralRegexes() != nullptr)
  5412. {
  5413. // This is a function nested in a redeferred function, so we won't regenerate byte code and won't make use of the index.
  5414. // The regex count is already correct, so don't increment it.
  5415. return 0;
  5416. }
  5417. return IncLiteralRegexCount();
  5418. }
  5419. void FunctionBody::AllocateLiteralRegexArray()
  5420. {
  5421. Assert(!this->GetLiteralRegexes());
  5422. uint32 literalRegexCount = GetLiteralRegexCount();
  5423. if (literalRegexCount == 0)
  5424. {
  5425. return;
  5426. }
  5427. this->SetLiteralRegexs(RecyclerNewArrayZ(m_scriptContext->GetRecycler(), UnifiedRegex::RegexPattern *, literalRegexCount));
  5428. }
  5429. #ifdef ASMJS_PLAT
  5430. AsmJsFunctionInfo* FunctionBody::AllocateAsmJsFunctionInfo()
  5431. {
  5432. Assert( !this->GetAsmJsFunctionInfo() );
  5433. this->SetAuxPtr(AuxPointerType::AsmJsFunctionInfo, RecyclerNew( m_scriptContext->GetRecycler(), AsmJsFunctionInfo));
  5434. return this->GetAsmJsFunctionInfo();
  5435. }
  5436. AsmJsModuleInfo* FunctionBody::AllocateAsmJsModuleInfo()
  5437. {
  5438. Assert( !this->GetAsmJsModuleInfo() );
  5439. Recycler* rec = m_scriptContext->GetRecycler();
  5440. this->SetAuxPtr(AuxPointerType::AsmJsModuleInfo, RecyclerNew(rec, AsmJsModuleInfo, rec));
  5441. return this->GetAsmJsModuleInfo();
  5442. }
  5443. #endif
  5444. PropertyIdArray * FunctionBody::AllocatePropertyIdArrayForFormals(uint32 size, uint32 count, byte extraSlots)
  5445. {
  5446. //TODO: saravind: Should the allocation be a Leaf Allocation?
  5447. PropertyIdArray * formalsPropIdArray = RecyclerNewPlus(GetScriptContext()->GetRecycler(), size, Js::PropertyIdArray, count, extraSlots);
  5448. SetFormalsPropIdArray(formalsPropIdArray);
  5449. return formalsPropIdArray;
  5450. }
  5451. UnifiedRegex::RegexPattern *FunctionBody::GetLiteralRegex(const uint index)
  5452. {
  5453. Assert(index < GetLiteralRegexCount());
  5454. Assert(this->GetLiteralRegexes());
  5455. return this->GetLiteralRegexes()[index];
  5456. }
  5457. UnifiedRegex::RegexPattern *FunctionBody::GetLiteralRegexWithLock(const uint index)
  5458. {
  5459. Assert(index < GetLiteralRegexCount());
  5460. Assert(this->GetLiteralRegexesWithLock());
  5461. return this->GetLiteralRegexesWithLock()[index];
  5462. }
  5463. void FunctionBody::SetLiteralRegex(const uint index, UnifiedRegex::RegexPattern *const pattern)
  5464. {
  5465. Assert(index < GetLiteralRegexCount());
  5466. Assert(this->GetLiteralRegexes());
  5467. auto literalRegexes = this->GetLiteralRegexes();
  5468. if (literalRegexes[index] && literalRegexes[index] == pattern)
  5469. {
  5470. return;
  5471. }
  5472. Assert(!literalRegexes[index]);
  5473. literalRegexes[index] = pattern;
  5474. }
  5475. void FunctionBody::ResetObjectLiteralTypes()
  5476. {
  5477. this->SetObjectLiteralTypes(nullptr);
  5478. this->SetObjLiteralCount(0);
  5479. }
  5480. void FunctionBody::ResetLiteralRegexes()
  5481. {
  5482. SetLiteralRegexCount(0);
  5483. this->SetLiteralRegexs(nullptr);
  5484. }
  5485. Js::AuxArray<uint32> * FunctionBody::AllocateSlotIdInCachedScopeToNestedIndexArray(uint32 slotCount)
  5486. {
  5487. Js::AuxArray<uint32> * slotIdToNestedIndexArray = RecyclerNewPlusLeaf(GetScriptContext()->GetRecycler(), slotCount * sizeof(uint32), Js::AuxArray<uint32>, slotCount);
  5488. SetSlotIdInCachedScopeToNestedIndexArray(slotIdToNestedIndexArray);
  5489. return slotIdToNestedIndexArray;
  5490. }
  5491. void FunctionBody::ResetProfileIds()
  5492. {
  5493. #if ENABLE_PROFILE_INFO
  5494. Assert(!HasDynamicProfileInfo()); // profile data relies on the profile ID counts; it should not have been created yet
  5495. Assert(!this->GetCodeGenRuntimeData()); // relies on 'profiledCallSiteCount'
  5496. profiledCallSiteCount = 0;
  5497. profiledArrayCallSiteCount = 0;
  5498. profiledReturnTypeCount = 0;
  5499. profiledSlotCount = 0;
  5500. profiledLdElemCount = 0;
  5501. profiledStElemCount = 0;
  5502. #endif
  5503. }
  5504. void FunctionBody::ResetByteCodeGenState()
  5505. {
  5506. // Byte code generation failed for this function. Revert any intermediate state being tracked in the function body, in
  5507. // case byte code generation is attempted again for this function body.
  5508. DebugOnly(this->UnlockCounters());
  5509. ResetInlineCaches();
  5510. ResetObjectLiteralTypes();
  5511. ResetLiteralRegexes();
  5512. ResetLoops();
  5513. ResetProfileIds();
  5514. ResetSlotIdInCachedScopeToNestedIndexArray();
  5515. SetFirstTmpRegister(Constants::NoRegister);
  5516. SetLocalClosureRegister(Constants::NoRegister);
  5517. SetParamClosureRegister(Constants::NoRegister);
  5518. SetLocalFrameDisplayRegister(Constants::NoRegister);
  5519. SetEnvRegister(Constants::NoRegister);
  5520. SetThisRegisterForEventHandler(Constants::NoRegister);
  5521. SetFirstInnerScopeRegister(Constants::NoRegister);
  5522. SetFuncExprScopeRegister(Constants::NoRegister);
  5523. SetInnerScopeCount(0);
  5524. hasCachedScopePropIds = false;
  5525. this->SetConstantCount(0);
  5526. this->SetConstTable(nullptr);
  5527. AssertMsg(!this->byteCodeBlock || !this->IsWasmFunction(), "We should never reset the bytecode block for Wasm");
  5528. this->byteCodeBlock = nullptr;
  5529. // Also, remove the function body from the source info to prevent any further processing
  5530. // of the function such as attempts to set breakpoints.
  5531. if (GetIsFuncRegistered())
  5532. {
  5533. this->GetUtf8SourceInfo()->RemoveFunctionBody(this);
  5534. }
  5535. // There is other state that is set by the byte code generator but the state should be the same each time byte code
  5536. // generation is done for the function, so it doesn't need to be reverted
  5537. }
  5538. void FunctionBody::ResetByteCodeGenVisitState()
  5539. {
  5540. // This function body is about to be visited by the byte code generator after defer-parsing it. Since the previous visit
  5541. // pass may have failed, we need to restore state that is tracked on the function body by the visit pass.
  5542. // Note: do not reset literal regexes if the function has already been compiled (e.g., is a parsed function enclosed by a
  5543. // redeferred function) as we will not use the count of literals anyway, and the counters may be accessed by the background thread.
  5544. DebugOnly(this->UnlockCounters());
  5545. if (this->byteCodeBlock == nullptr)
  5546. {
  5547. ResetLiteralRegexes();
  5548. }
  5549. }
  5550. #if ENABLE_NATIVE_CODEGEN
  5551. const FunctionCodeGenRuntimeData *FunctionBody::GetInlineeCodeGenRuntimeData(const ProfileId profiledCallSiteId) const
  5552. {
  5553. Assert(profiledCallSiteId < profiledCallSiteCount);
  5554. auto codeGenRuntimeData = this->GetCodeGenRuntimeDataWithLock();
  5555. return codeGenRuntimeData ? codeGenRuntimeData[profiledCallSiteId] : nullptr;
  5556. }
  5557. const FunctionCodeGenRuntimeData *FunctionBody::GetInlineeCodeGenRuntimeDataForTargetInlinee(const ProfileId profiledCallSiteId, Js::FunctionBody *inlineeFuncBody) const
  5558. {
  5559. Assert(profiledCallSiteId < profiledCallSiteCount);
  5560. auto codeGenRuntimeData = this->GetCodeGenRuntimeDataWithLock();
  5561. if (!codeGenRuntimeData)
  5562. {
  5563. return nullptr;
  5564. }
  5565. const FunctionCodeGenRuntimeData *runtimeData = codeGenRuntimeData[profiledCallSiteId];
  5566. while (runtimeData && runtimeData->GetFunctionBody() != inlineeFuncBody)
  5567. {
  5568. runtimeData = runtimeData->GetNext();
  5569. }
  5570. return runtimeData;
  5571. }
  5572. FunctionCodeGenRuntimeData *FunctionBody::EnsureInlineeCodeGenRuntimeData(
  5573. Recycler *const recycler,
  5574. __in_range(0, profiledCallSiteCount - 1) const ProfileId profiledCallSiteId,
  5575. FunctionBody *const inlinee)
  5576. {
  5577. Assert(recycler);
  5578. Assert(profiledCallSiteId < profiledCallSiteCount);
  5579. Assert(inlinee);
  5580. if(!this->GetCodeGenRuntimeData())
  5581. {
  5582. const auto codeGenRuntimeData = RecyclerNewArrayZ(recycler, FunctionCodeGenRuntimeData *, profiledCallSiteCount);
  5583. this->SetCodeGenRuntimeData(codeGenRuntimeData);
  5584. }
  5585. auto codeGenRuntimeData = this->GetCodeGenRuntimeData();
  5586. const auto inlineeData = codeGenRuntimeData[profiledCallSiteId];
  5587. if(!inlineeData)
  5588. {
  5589. return codeGenRuntimeData[profiledCallSiteId] = RecyclerNew(recycler, FunctionCodeGenRuntimeData, inlinee);
  5590. }
  5591. // Find the right code gen runtime data
  5592. FunctionCodeGenRuntimeData *next = inlineeData;
  5593. while(next && (next->GetFunctionBody() != inlinee))
  5594. {
  5595. next = next->GetNext();
  5596. }
  5597. if (next)
  5598. {
  5599. return next;
  5600. }
  5601. FunctionCodeGenRuntimeData *runtimeData = RecyclerNew(recycler, FunctionCodeGenRuntimeData, inlinee);
  5602. runtimeData->SetupRuntimeDataChain(inlineeData);
  5603. return codeGenRuntimeData[profiledCallSiteId] = runtimeData;
  5604. }
  5605. const FunctionCodeGenRuntimeData *FunctionBody::GetLdFldInlineeCodeGenRuntimeData(const InlineCacheIndex inlineCacheIndex) const
  5606. {
  5607. Assert(inlineCacheIndex < this->GetInlineCacheCount());
  5608. auto data = this->GetCodeGenGetSetRuntimeDataWithLock();
  5609. return (data != nullptr) ? data[inlineCacheIndex] : nullptr;
  5610. }
  5611. FunctionCodeGenRuntimeData *FunctionBody::EnsureLdFldInlineeCodeGenRuntimeData(
  5612. Recycler *const recycler,
  5613. const InlineCacheIndex inlineCacheIndex,
  5614. FunctionBody *const inlinee)
  5615. {
  5616. Assert(recycler);
  5617. Assert(inlineCacheIndex < this->GetInlineCacheCount());
  5618. Assert(inlinee);
  5619. if (this->GetCodeGenGetSetRuntimeData() == nullptr)
  5620. {
  5621. const auto codeGenRuntimeData = RecyclerNewArrayZ(recycler, FunctionCodeGenRuntimeData *, this->GetInlineCacheCount());
  5622. this->SetCodeGenGetSetRuntimeData(codeGenRuntimeData);
  5623. }
  5624. auto codeGenGetSetRuntimeData = this->GetCodeGenGetSetRuntimeData();
  5625. const auto inlineeData = codeGenGetSetRuntimeData[inlineCacheIndex];
  5626. if (inlineeData)
  5627. {
  5628. return inlineeData;
  5629. }
  5630. return codeGenGetSetRuntimeData[inlineCacheIndex] = RecyclerNew(recycler, FunctionCodeGenRuntimeData, inlinee);
  5631. }
  5632. #endif
  5633. void FunctionBody::AllocateLoopHeaders()
  5634. {
  5635. Assert(this->GetLoopHeaderArray() == nullptr);
  5636. uint loopCount = GetLoopCount();
  5637. if (loopCount != 0)
  5638. {
  5639. this->SetLoopHeaderArray(RecyclerNewArrayZ(this->m_scriptContext->GetRecycler(), LoopHeader, loopCount));
  5640. auto loopHeaderArray = this->GetLoopHeaderArray();
  5641. for (uint i = 0; i < loopCount; i++)
  5642. {
  5643. loopHeaderArray[i].Init(this);
  5644. }
  5645. }
  5646. }
  5647. void FunctionBody::ReleaseLoopHeaders()
  5648. {
  5649. #if ENABLE_NATIVE_CODEGEN
  5650. this->MapLoopHeaders([](uint loopNumber, LoopHeader * loopHeader)
  5651. {
  5652. loopHeader->ReleaseEntryPoints();
  5653. });
  5654. #endif
  5655. }
  5656. void FunctionBody::ResetLoops()
  5657. {
  5658. SetLoopCount(0);
  5659. this->SetLoopHeaderArray(nullptr);
  5660. }
  5661. void FunctionBody::RestoreOldDefaultEntryPoint(FunctionEntryPointInfo* oldEntryPointInfo,
  5662. JavascriptMethod oldOriginalEntryPoint,
  5663. FunctionEntryPointInfo* newEntryPointInfo)
  5664. {
  5665. Assert(newEntryPointInfo);
  5666. this->SetDefaultFunctionEntryPointInfo(oldEntryPointInfo, oldOriginalEntryPoint);
  5667. this->entryPoints->RemoveAt(newEntryPointInfo->entryPointIndex);
  5668. }
  5669. FunctionEntryPointInfo* FunctionBody::CreateNewDefaultEntryPoint()
  5670. {
  5671. Recycler *const recycler = this->m_scriptContext->GetRecycler();
  5672. const JavascriptMethod currentThunk = m_scriptContext->CurrentThunk;
  5673. void* validationCookie = nullptr;
  5674. #if ENABLE_NATIVE_CODEGEN
  5675. validationCookie = (void*)m_scriptContext->GetNativeCodeGenerator();
  5676. #endif
  5677. FunctionEntryPointInfo *const entryPointInfo =
  5678. RecyclerNewFinalized(
  5679. recycler,
  5680. FunctionEntryPointInfo,
  5681. this,
  5682. currentThunk,
  5683. m_scriptContext->GetThreadContext(),
  5684. validationCookie);
  5685. AddEntryPointToEntryPointList(entryPointInfo);
  5686. {
  5687. // Allocations in this region may trigger expiry and cause unexpected changes to state
  5688. AUTO_NO_EXCEPTION_REGION;
  5689. FunctionEntryPointInfo *const simpleJitEntryPointInfo = GetSimpleJitEntryPointInfo();
  5690. Js::JavascriptMethod originalEntryPoint, directEntryPoint;
  5691. if(simpleJitEntryPointInfo && GetExecutionMode() == ExecutionMode::FullJit)
  5692. {
  5693. directEntryPoint =
  5694. originalEntryPoint = simpleJitEntryPointInfo->GetNativeEntrypoint();
  5695. }
  5696. else
  5697. {
  5698. #if DYNAMIC_INTERPRETER_THUNK
  5699. // If the dynamic interpreter thunk hasn't been created yet, then the entry point can be set to
  5700. // the default entry point. Otherwise, since the new default entry point is being created to
  5701. // move back to the interpreter, the original entry point is going to be the dynamic interpreter thunk
  5702. originalEntryPoint =
  5703. m_dynamicInterpreterThunk
  5704. ? reinterpret_cast<JavascriptMethod>(InterpreterThunkEmitter::ConvertToEntryPoint(m_dynamicInterpreterThunk))
  5705. : DefaultEntryThunk;
  5706. #else
  5707. originalEntryPoint = DefaultEntryThunk;
  5708. #endif
  5709. directEntryPoint = currentThunk == DefaultEntryThunk ? originalEntryPoint : currentThunk;
  5710. }
  5711. entryPointInfo->jsMethod = directEntryPoint;
  5712. SetDefaultFunctionEntryPointInfo(entryPointInfo, originalEntryPoint);
  5713. }
  5714. return entryPointInfo;
  5715. }
  5716. LoopHeader *FunctionBody::GetLoopHeader(uint index) const
  5717. {
  5718. Assert(this->GetLoopHeaderArray() != nullptr);
  5719. Assert(index < GetLoopCount());
  5720. return &this->GetLoopHeaderArray()[index];
  5721. }
  5722. LoopHeader *FunctionBody::GetLoopHeaderWithLock(uint index) const
  5723. {
  5724. Assert(this->GetLoopHeaderArrayWithLock() != nullptr);
  5725. Assert(index < GetLoopCount());
  5726. return &this->GetLoopHeaderArrayWithLock()[index];
  5727. }
  5728. FunctionEntryPointInfo *FunctionBody::GetSimpleJitEntryPointInfo() const
  5729. {
  5730. return static_cast<FunctionEntryPointInfo *>(this->GetAuxPtr(AuxPointerType::SimpleJitEntryPointInfo));
  5731. }
  5732. void FunctionBody::SetSimpleJitEntryPointInfo(FunctionEntryPointInfo *const entryPointInfo)
  5733. {
  5734. this->SetAuxPtr(AuxPointerType::SimpleJitEntryPointInfo, entryPointInfo);
  5735. }
  5736. uint32 FunctionBody::GetInterpretedCount() const
  5737. {
  5738. return executionState.GetInterpretedCount();
  5739. }
  5740. uint32 FunctionBody::IncreaseInterpretedCount()
  5741. {
  5742. return executionState.IncreaseInterpretedCount();
  5743. }
  5744. void FunctionBody::SetAsmJsExecutionMode()
  5745. {
  5746. executionState.SetAsmJsExecutionMode();
  5747. }
  5748. void FunctionBody::SetDefaultInterpreterExecutionMode()
  5749. {
  5750. executionState.SetDefaultInterpreterExecutionMode();
  5751. }
  5752. ExecutionMode FunctionBody::GetExecutionMode() const
  5753. {
  5754. return executionState.GetExecutionMode();
  5755. }
  5756. ExecutionMode FunctionBody::GetInterpreterExecutionMode(const bool isPostBailout)
  5757. {
  5758. return executionState.GetInterpreterExecutionMode(isPostBailout);
  5759. }
  5760. bool FunctionBody::IsInterpreterExecutionMode() const
  5761. {
  5762. return GetExecutionMode() <= ExecutionMode::ProfilingInterpreter;
  5763. }
  5764. bool FunctionBody::TryTransitionToNextExecutionMode()
  5765. {
  5766. return executionState.TryTransitionToNextExecutionMode();
  5767. }
  5768. void FunctionBody::TryTransitionToNextInterpreterExecutionMode()
  5769. {
  5770. executionState.TryTransitionToNextInterpreterExecutionMode();
  5771. }
  5772. void FunctionBody::SetIsSpeculativeJitCandidate()
  5773. {
  5774. executionState.SetIsSpeculativeJitCandidate();
  5775. }
  5776. bool FunctionBody::TryTransitionToJitExecutionMode()
  5777. {
  5778. return executionState.TryTransitionToJitExecutionMode();
  5779. }
  5780. void FunctionBody::TransitionToSimpleJitExecutionMode()
  5781. {
  5782. executionState.TransitionToSimpleJitExecutionMode();
  5783. }
  5784. void FunctionBody::TransitionToFullJitExecutionMode()
  5785. {
  5786. executionState.TransitionToFullJitExecutionMode();
  5787. }
  5788. void FunctionBody::ReinitializeExecutionModeAndLimits()
  5789. {
  5790. // Do not remove wasCalledFromLoop
  5791. wasCalledFromLoop = false;
  5792. executionState.ReinitializeExecutionModeAndLimits(this);
  5793. }
  5794. void FunctionBody::ResetSimpleJitLimitAndCallCount()
  5795. {
  5796. Assert(GetDefaultFunctionEntryPointInfo() == GetSimpleJitEntryPointInfo());
  5797. executionState.ResetSimpleJitLimit();
  5798. ResetSimpleJitCallCount();
  5799. }
  5800. void FunctionBody::SetSimpleJitCallCount(const uint16 simpleJitLimit) const
  5801. {
  5802. Assert(GetExecutionMode() == ExecutionMode::SimpleJit);
  5803. Assert(GetDefaultFunctionEntryPointInfo() == GetSimpleJitEntryPointInfo());
  5804. // Simple JIT counts down and transitions on overflow
  5805. const uint8 limit = static_cast<uint8>(min(0xffui16, simpleJitLimit));
  5806. GetSimpleJitEntryPointInfo()->callsCount = limit == 0 ? 0 : limit - 1;
  5807. }
  5808. void FunctionBody::ResetSimpleJitCallCount()
  5809. {
  5810. uint32 interpretedCount = GetInterpretedCount();
  5811. uint16 simpleJitLimit = static_cast<uint16>(executionState.GetSimpleJitLimit());
  5812. SetSimpleJitCallCount(
  5813. simpleJitLimit > interpretedCount
  5814. ? simpleJitLimit - static_cast<uint16>(interpretedCount)
  5815. : 0ui16);
  5816. }
  5817. uint16 FunctionBody::GetProfiledIterations() const
  5818. {
  5819. return executionState.GetProfiledIterations();
  5820. }
  5821. void FunctionBody::OnFullJitDequeued(const FunctionEntryPointInfo *const entryPointInfo)
  5822. {
  5823. executionState.AssertIsInitialized();
  5824. Assert(GetExecutionMode() == ExecutionMode::FullJit);
  5825. Assert(entryPointInfo);
  5826. if(entryPointInfo != GetDefaultFunctionEntryPointInfo())
  5827. {
  5828. return;
  5829. }
  5830. // Re-queue the full JIT work item after this many iterations
  5831. executionState.SetFullJitRequeueThreshold(static_cast<uint16>(DEFAULT_CONFIG_FullJitRequeueThreshold));
  5832. }
  5833. void FunctionBody::TraceExecutionMode(const char *const eventDescription) const
  5834. {
  5835. executionState.AssertIsInitialized();
  5836. if(PHASE_TRACE(Phase::ExecutionModePhase, this))
  5837. {
  5838. DoTraceExecutionMode(eventDescription);
  5839. }
  5840. }
  5841. void FunctionBody::TraceInterpreterExecutionMode() const
  5842. {
  5843. executionState.AssertIsInitialized();
  5844. if(!PHASE_TRACE(Phase::ExecutionModePhase, this))
  5845. {
  5846. return;
  5847. }
  5848. switch(GetExecutionMode())
  5849. {
  5850. case ExecutionMode::Interpreter:
  5851. case ExecutionMode::AutoProfilingInterpreter:
  5852. case ExecutionMode::ProfilingInterpreter:
  5853. DoTraceExecutionMode(nullptr);
  5854. break;
  5855. }
  5856. }
  5857. void FunctionBody::DoTraceExecutionMode(const char *const eventDescription) const
  5858. {
  5859. Assert(PHASE_TRACE(Phase::ExecutionModePhase, this));
  5860. executionState.AssertIsInitialized();
  5861. char16 functionIdString[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  5862. Output::Print(
  5863. _u("ExecutionMode - ")
  5864. _u("function: %s (%s), ")
  5865. _u("mode: %S, ")
  5866. _u("size: %u, "),
  5867. GetDisplayName(),
  5868. GetDebugNumberSet(functionIdString),
  5869. ExecutionModeName(executionState.GetExecutionMode()),
  5870. GetByteCodeCount());
  5871. executionState.PrintLimits();
  5872. if(eventDescription)
  5873. {
  5874. Output::Print(_u(", event: %S"), eventDescription);
  5875. }
  5876. Output::Print(_u("\n"));
  5877. Output::Flush();
  5878. }
  5879. bool FunctionBody::DoSimpleJit() const
  5880. {
  5881. return
  5882. !PHASE_OFF(Js::SimpleJitPhase, this) &&
  5883. #ifdef ASMJS_PLAT
  5884. !GetIsAsmjsMode() &&
  5885. #endif
  5886. !GetScriptContext()->GetConfig()->IsNoNative() &&
  5887. !GetScriptContext()->IsScriptContextInDebugMode() &&
  5888. DoInterpreterProfile() &&
  5889. #pragma warning(suppress: 6235) // (<non-zero constant> || <expression>) is always a non-zero constant.
  5890. (!CONFIG_FLAG(NewSimpleJit) || DoInterpreterAutoProfile()) &&
  5891. !IsCoroutine(); // Generator JIT requires bailout which SimpleJit cannot do since it skips GlobOpt
  5892. }
  5893. bool FunctionBody::DoSimpleJitWithLock() const
  5894. {
  5895. return
  5896. !PHASE_OFF(Js::SimpleJitPhase, this) &&
  5897. #ifdef ASMJS_PLAT
  5898. !GetIsAsmjsMode() &&
  5899. #endif
  5900. !GetScriptContext()->GetConfig()->IsNoNative() &&
  5901. !this->IsInDebugMode() &&
  5902. DoInterpreterProfileWithLock() &&
  5903. #pragma warning(suppress: 6235) // (<non-zero constant> || <expression>) is always a non-zero constant.
  5904. (!CONFIG_FLAG(NewSimpleJit) || DoInterpreterAutoProfile()) &&
  5905. !IsCoroutine(); // Generator JIT requires bailout which SimpleJit cannot do since it skips GlobOpt
  5906. }
  5907. bool FunctionBody::DoSimpleJitDynamicProfile() const
  5908. {
  5909. Assert(DoSimpleJitWithLock());
  5910. return !PHASE_OFF(Js::SimpleJitDynamicProfilePhase, this) && !CONFIG_FLAG(NewSimpleJit);
  5911. }
  5912. bool FunctionBody::DoInterpreterProfile() const
  5913. {
  5914. #if ENABLE_PROFILE_INFO
  5915. return !PHASE_OFF(InterpreterProfilePhase, this) && DynamicProfileInfo::IsEnabled(this);
  5916. #else
  5917. return false;
  5918. #endif
  5919. }
  5920. bool FunctionBody::DoInterpreterProfileWithLock() const
  5921. {
  5922. #if ENABLE_PROFILE_INFO
  5923. return !PHASE_OFF(InterpreterProfilePhase, this) && DynamicProfileInfo::IsEnabled(this);
  5924. #else
  5925. return false;
  5926. #endif
  5927. }
  5928. bool FunctionBody::DoInterpreterAutoProfile() const
  5929. {
  5930. Assert(DoInterpreterProfile());
  5931. #ifdef ASMJS_PLAT
  5932. if (this->GetIsAsmjsMode()) return false;
  5933. #endif
  5934. return !PHASE_OFF(InterpreterAutoProfilePhase, this) && !this->IsInDebugMode();
  5935. }
  5936. bool FunctionBody::WasCalledFromLoop() const
  5937. {
  5938. return wasCalledFromLoop;
  5939. }
  5940. void FunctionBody::SetWasCalledFromLoop()
  5941. {
  5942. if(wasCalledFromLoop)
  5943. {
  5944. return;
  5945. }
  5946. wasCalledFromLoop = true;
  5947. if(Configuration::Global.flags.EnforceExecutionModeLimits)
  5948. {
  5949. if(PHASE_TRACE(Phase::ExecutionModePhase, this))
  5950. {
  5951. executionState.CommitExecutedIterations();
  5952. TraceExecutionMode("WasCalledFromLoop (before)");
  5953. }
  5954. }
  5955. else
  5956. {
  5957. // This function is likely going to be called frequently since it's called from a loop. Reduce the full JIT
  5958. // threshold to realize the full JIT perf benefit sooner.
  5959. executionState.CommitExecutedIterations();
  5960. TraceExecutionMode("WasCalledFromLoop (before)");
  5961. uint16 fullJitThreshold = executionState.GetFullJitThreshold();
  5962. if(fullJitThreshold > 1)
  5963. {
  5964. executionState.SetFullJitThreshold(fullJitThreshold / 2, !CONFIG_FLAG(NewSimpleJit));
  5965. }
  5966. }
  5967. {
  5968. // Reduce the loop interpreter limit too, for the same reasons as above
  5969. const uint oldLoopInterpreterLimit = GetLoopInterpreterLimit();
  5970. const uint newLoopInterpreterLimit = GetReducedLoopInterpretCount();
  5971. Assert(newLoopInterpreterLimit <= oldLoopInterpreterLimit);
  5972. SetLoopInterpreterLimit(newLoopInterpreterLimit);
  5973. // Adjust loop headers' interpret counts to ensure that loops will still be profiled a number of times before
  5974. // loop bodies are jitted
  5975. const uint oldLoopProfileThreshold = GetLoopProfileThreshold(oldLoopInterpreterLimit);
  5976. const uint newLoopProfileThreshold = GetLoopProfileThreshold(newLoopInterpreterLimit);
  5977. MapLoopHeaders([=](const uint index, LoopHeader *const loopHeader)
  5978. {
  5979. const uint interpretedCount = loopHeader->interpretCount;
  5980. if(interpretedCount <= newLoopProfileThreshold || interpretedCount >= oldLoopInterpreterLimit)
  5981. {
  5982. // The loop hasn't been profiled yet and wouldn't have started profiling even with the new profile
  5983. // threshold, or it has already been profiled the necessary minimum number of times based on the old limit
  5984. return;
  5985. }
  5986. if(interpretedCount <= oldLoopProfileThreshold)
  5987. {
  5988. // The loop hasn't been profiled yet, but would have started profiling with the new profile threshold. Start
  5989. // profiling on the next iteration.
  5990. loopHeader->interpretCount = newLoopProfileThreshold;
  5991. return;
  5992. }
  5993. // The loop has been profiled some already. Preserve the number of profiled iterations.
  5994. loopHeader->interpretCount = newLoopProfileThreshold + (interpretedCount - oldLoopProfileThreshold);
  5995. });
  5996. }
  5997. TraceExecutionMode("WasCalledFromLoop");
  5998. }
  5999. bool FunctionBody::RecentlyBailedOutOfJittedLoopBody() const
  6000. {
  6001. return recentlyBailedOutOfJittedLoopBody;
  6002. }
  6003. void FunctionBody::SetRecentlyBailedOutOfJittedLoopBody(const bool value)
  6004. {
  6005. recentlyBailedOutOfJittedLoopBody = value;
  6006. }
  6007. uint16 FunctionBody::GetMinProfileIterations()
  6008. {
  6009. return
  6010. static_cast<uint>(
  6011. CONFIG_FLAG(NewSimpleJit)
  6012. ? DEFAULT_CONFIG_MinProfileIterations
  6013. : DEFAULT_CONFIG_MinProfileIterations_OldSimpleJit);
  6014. }
  6015. uint16 FunctionBody::GetMinFunctionProfileIterations()
  6016. {
  6017. return GetMinProfileIterations();
  6018. }
  6019. uint FunctionBody::GetMinLoopProfileIterations(const uint loopInterpreterLimit)
  6020. {
  6021. return min(static_cast<uint>(GetMinProfileIterations()), loopInterpreterLimit);
  6022. }
  6023. uint FunctionBody::GetLoopProfileThreshold(const uint loopInterpreterLimit) const
  6024. {
  6025. return
  6026. DoInterpreterProfile()
  6027. ? DoInterpreterAutoProfile()
  6028. ? loopInterpreterLimit - GetMinLoopProfileIterations(loopInterpreterLimit)
  6029. : 0
  6030. : static_cast<uint>(-1);
  6031. }
  6032. uint FunctionBody::GetReducedLoopInterpretCount()
  6033. {
  6034. const uint loopInterpretCount = CONFIG_FLAG(LoopInterpretCount);
  6035. if(CONFIG_ISENABLED(LoopInterpretCountFlag))
  6036. {
  6037. return loopInterpretCount;
  6038. }
  6039. return max(loopInterpretCount / 3, GetMinLoopProfileIterations(loopInterpretCount));
  6040. }
  6041. uint FunctionBody::GetLoopInterpretCount(LoopHeader* loopHeader) const
  6042. {
  6043. if(loopHeader->isNested)
  6044. {
  6045. Assert(GetLoopInterpreterLimit() >= GetReducedLoopInterpretCount());
  6046. return GetReducedLoopInterpretCount();
  6047. }
  6048. return GetLoopInterpreterLimit();
  6049. }
  6050. bool FunctionBody::DoObjectHeaderInlining()
  6051. {
  6052. return !PHASE_OFF1(ObjectHeaderInliningPhase);
  6053. }
  6054. bool FunctionBody::DoObjectHeaderInliningForConstructors()
  6055. {
  6056. return !PHASE_OFF1(ObjectHeaderInliningForConstructorsPhase) && DoObjectHeaderInlining();
  6057. }
  6058. bool FunctionBody::DoObjectHeaderInliningForConstructor(const uint32 inlineSlotCapacity)
  6059. {
  6060. return inlineSlotCapacity == 0 ? DoObjectHeaderInliningForEmptyObjects() : DoObjectHeaderInliningForConstructors();
  6061. }
  6062. bool FunctionBody::DoObjectHeaderInliningForObjectLiterals()
  6063. {
  6064. return !PHASE_OFF1(ObjectHeaderInliningForObjectLiteralsPhase) && DoObjectHeaderInlining();
  6065. }
  6066. bool FunctionBody::DoObjectHeaderInliningForObjectLiteral(const uint32 inlineSlotCapacity)
  6067. {
  6068. return
  6069. inlineSlotCapacity == 0
  6070. ? DoObjectHeaderInliningForEmptyObjects()
  6071. : DoObjectHeaderInliningForObjectLiterals() &&
  6072. inlineSlotCapacity <= static_cast<uint32>(MaxPreInitializedObjectHeaderInlinedTypeInlineSlotCount);
  6073. }
  6074. bool FunctionBody::DoObjectHeaderInliningForObjectLiteral(
  6075. const PropertyIdArray *const propIds)
  6076. {
  6077. Assert(propIds);
  6078. return
  6079. DoObjectHeaderInliningForObjectLiteral(propIds->count) &&
  6080. PathTypeHandlerBase::UsePathTypeHandlerForObjectLiteral(propIds);
  6081. }
  6082. bool FunctionBody::DoObjectHeaderInliningForEmptyObjects()
  6083. {
  6084. #pragma prefast(suppress:6237, "(<zero> && <expression>) is always zero. <expression> is never evaluated and might have side effects.")
  6085. return PHASE_ON1(ObjectHeaderInliningForEmptyObjectsPhase) && DoObjectHeaderInlining();
  6086. }
  6087. void FunctionBody::Finalize(bool isShutdown)
  6088. {
  6089. #if ENABLE_DEBUG_CONFIG_OPTIONS
  6090. if (Js::Configuration::Global.flags.Instrument.IsEnabled(Js::LinearScanPhase, this->GetSourceContextId(), this->GetLocalFunctionId()))
  6091. {
  6092. this->DumpRegStats(this);
  6093. }
  6094. #endif
  6095. this->Cleanup(isShutdown);
  6096. this->CleanupSourceInfo(isShutdown);
  6097. this->CleanupFunctionProxyCounters();
  6098. }
  6099. void FunctionBody::OnMark()
  6100. {
  6101. this->m_hasActiveReference = true;
  6102. }
  6103. void FunctionBody::CleanupSourceInfo(bool isScriptContextClosing)
  6104. {
  6105. Assert(this->cleanedUp);
  6106. if (!sourceInfoCleanedUp)
  6107. {
  6108. if (GetIsFuncRegistered() && !isScriptContextClosing)
  6109. {
  6110. // If our function is registered, then there must
  6111. // be a Utf8SourceInfo pinned by it.
  6112. Assert(this->m_utf8SourceInfo);
  6113. this->GetUtf8SourceInfo()->RemoveFunctionBody(this);
  6114. }
  6115. if (this->m_sourceInfo.pSpanSequence != nullptr)
  6116. {
  6117. HeapDelete(this->m_sourceInfo.pSpanSequence);
  6118. this->m_sourceInfo.pSpanSequence = nullptr;
  6119. }
  6120. sourceInfoCleanedUp = true;
  6121. }
  6122. }
  6123. template<bool IsScriptContextShutdown>
  6124. void FunctionBody::CleanUpInlineCaches()
  6125. {
  6126. uint unregisteredInlineCacheCount = 0;
  6127. if (nullptr != this->inlineCaches)
  6128. {
  6129. // Inline caches are in this order
  6130. // plain inline cache
  6131. // root object load inline cache
  6132. // root object store inline cache
  6133. // isInst inline cache
  6134. // The inlineCacheCount includes all but isInst inline cache
  6135. uint i = 0;
  6136. uint plainInlineCacheEnd = GetRootObjectLoadInlineCacheStart();
  6137. for (; i < plainInlineCacheEnd; i++)
  6138. {
  6139. if (nullptr != this->inlineCaches[i])
  6140. {
  6141. InlineCache* inlineCache = (InlineCache*)this->inlineCaches[i];
  6142. if (IsScriptContextShutdown)
  6143. {
  6144. inlineCache->Clear();
  6145. }
  6146. else
  6147. {
  6148. if (inlineCache->RemoveFromInvalidationList())
  6149. {
  6150. unregisteredInlineCacheCount++;
  6151. }
  6152. AllocatorDelete(InlineCacheAllocator, this->m_scriptContext->GetInlineCacheAllocator(), inlineCache);
  6153. }
  6154. }
  6155. }
  6156. RootObjectBase * rootObjectBase = this->GetRootObject();
  6157. uint rootObjectLoadInlineCacheEnd = GetRootObjectLoadMethodInlineCacheStart();
  6158. for (; i < rootObjectLoadInlineCacheEnd; i++)
  6159. {
  6160. if (nullptr != this->inlineCaches[i])
  6161. {
  6162. if (IsScriptContextShutdown)
  6163. {
  6164. ((InlineCache*)this->inlineCaches[i])->Clear();
  6165. }
  6166. else
  6167. {
  6168. // A single root object inline caches for a given property is shared by all functions. It is ref counted
  6169. // and doesn't get released to the allocator until there are no more outstanding references. Thus we don't need
  6170. // to (and, in fact, cannot) remove it from the invalidation list here. Instead, we'll do it in ReleaseInlineCache
  6171. // when there are no more outstanding references.
  6172. unregisteredInlineCacheCount += rootObjectBase->ReleaseInlineCache(this->GetPropertyIdFromCacheId(i), false, false, IsScriptContextShutdown);
  6173. }
  6174. }
  6175. }
  6176. uint rootObjectLoadMethodInlineCacheEnd = GetRootObjectStoreInlineCacheStart();
  6177. for (; i < rootObjectLoadMethodInlineCacheEnd; i++)
  6178. {
  6179. if (nullptr != this->inlineCaches[i])
  6180. {
  6181. if (IsScriptContextShutdown)
  6182. {
  6183. ((InlineCache*)this->inlineCaches[i])->Clear();
  6184. }
  6185. else
  6186. {
  6187. // A single root object inline caches for a given property is shared by all functions. It is ref counted
  6188. // and doesn't get released to the allocator until there are no more outstanding references. Thus we don't need
  6189. // to (and, in fact, cannot) remove it from the invalidation list here. Instead, we'll do it in ReleaseInlineCache
  6190. // when there are no more outstanding references.
  6191. unregisteredInlineCacheCount += rootObjectBase->ReleaseInlineCache(this->GetPropertyIdFromCacheId(i), true, false, IsScriptContextShutdown);
  6192. }
  6193. }
  6194. }
  6195. uint rootObjectStoreInlineCacheEnd = this->GetInlineCacheCount();
  6196. for (; i < rootObjectStoreInlineCacheEnd; i++)
  6197. {
  6198. if (nullptr != this->inlineCaches[i])
  6199. {
  6200. if (IsScriptContextShutdown)
  6201. {
  6202. ((InlineCache*)this->inlineCaches[i])->Clear();
  6203. }
  6204. else
  6205. {
  6206. // A single root object inline caches for a given property is shared by all functions. It is ref counted
  6207. // and doesn't get released to the allocator until there are no more outstanding references. Thus we don't need
  6208. // to (and, in fact, cannot) remove it from the invalidation list here. Instead, we'll do it in ReleaseInlineCache
  6209. // when there are no more outstanding references.
  6210. unregisteredInlineCacheCount += rootObjectBase->ReleaseInlineCache(this->GetPropertyIdFromCacheId(i), false, true, IsScriptContextShutdown);
  6211. }
  6212. }
  6213. }
  6214. uint totalCacheCount = GetInlineCacheCount() + GetIsInstInlineCacheCount();
  6215. for (; i < totalCacheCount; i++)
  6216. {
  6217. if (nullptr != this->inlineCaches[i])
  6218. {
  6219. IsInstInlineCache* inlineCache = (IsInstInlineCache*)this->inlineCaches[i];
  6220. if (IsScriptContextShutdown)
  6221. {
  6222. inlineCache->Clear();
  6223. }
  6224. else
  6225. {
  6226. inlineCache->Unregister(this->m_scriptContext);
  6227. AllocatorDelete(CacheAllocator, this->m_scriptContext->GetIsInstInlineCacheAllocator(), inlineCache);
  6228. }
  6229. }
  6230. }
  6231. this->inlineCaches = nullptr;
  6232. }
  6233. auto codeGenRuntimeData = this->GetCodeGenRuntimeData();
  6234. if (nullptr != codeGenRuntimeData)
  6235. {
  6236. for (ProfileId i = 0; i < this->profiledCallSiteCount; i++)
  6237. {
  6238. const FunctionCodeGenRuntimeData* runtimeData = codeGenRuntimeData[i];
  6239. if (nullptr != runtimeData)
  6240. {
  6241. runtimeData->MapInlineCaches([&](InlineCache* inlineCache)
  6242. {
  6243. if (nullptr != inlineCache)
  6244. {
  6245. if (IsScriptContextShutdown)
  6246. {
  6247. inlineCache->Clear();
  6248. }
  6249. else
  6250. {
  6251. if (inlineCache->RemoveFromInvalidationList())
  6252. {
  6253. unregisteredInlineCacheCount++;
  6254. }
  6255. AllocatorDelete(InlineCacheAllocator, this->m_scriptContext->GetInlineCacheAllocator(), inlineCache);
  6256. }
  6257. }
  6258. });
  6259. }
  6260. }
  6261. }
  6262. auto codeGenGetSetRuntimeData = this->GetCodeGenGetSetRuntimeData();
  6263. if (codeGenGetSetRuntimeData != nullptr)
  6264. {
  6265. for (uint i = 0; i < this->GetInlineCacheCount(); i++)
  6266. {
  6267. auto runtimeData = codeGenGetSetRuntimeData[i];
  6268. if (nullptr != runtimeData)
  6269. {
  6270. runtimeData->MapInlineCaches([&](InlineCache* inlineCache)
  6271. {
  6272. if (nullptr != inlineCache)
  6273. {
  6274. if (IsScriptContextShutdown)
  6275. {
  6276. inlineCache->Clear();
  6277. }
  6278. else
  6279. {
  6280. if (inlineCache->RemoveFromInvalidationList())
  6281. {
  6282. unregisteredInlineCacheCount++;
  6283. }
  6284. AllocatorDelete(InlineCacheAllocator, this->m_scriptContext->GetInlineCacheAllocator(), inlineCache);
  6285. }
  6286. }
  6287. });
  6288. }
  6289. }
  6290. }
  6291. if (unregisteredInlineCacheCount > 0)
  6292. {
  6293. AssertMsg(!IsScriptContextShutdown, "Unregistration of inlineCache should only be done if this is not scriptContext shutdown.");
  6294. ThreadContext* threadContext = this->m_scriptContext->GetThreadContext();
  6295. threadContext->NotifyInlineCacheBatchUnregistered(unregisteredInlineCacheCount);
  6296. }
  6297. while (this->GetPolymorphicInlineCachesHead())
  6298. {
  6299. this->GetPolymorphicInlineCachesHead()->Finalize(IsScriptContextShutdown);
  6300. }
  6301. polymorphicInlineCaches.Reset();
  6302. }
  6303. void FunctionBody::CleanupRecyclerData(bool isShutdown, bool doEntryPointCleanupCaptureStack)
  6304. {
  6305. // If we're not shutting down (i.e closing the script context), we need to remove our inline caches from
  6306. // thread context's invalidation lists, and release memory back to the arena. During script context shutdown,
  6307. // we leave everything in place, because the inline cache arena will stay alive until script context is destroyed
  6308. // (i.e it's destructor has been called) and thus the invalidation lists are safe to keep references to caches from this
  6309. // script context. We will, however, zero all inline caches so that we don't have to process them on subsequent
  6310. // collections, which may still happen from other script contexts.
  6311. if (isShutdown)
  6312. {
  6313. CleanUpInlineCaches<true>();
  6314. }
  6315. else
  6316. {
  6317. CleanUpInlineCaches<false>();
  6318. }
  6319. if (this->entryPoints)
  6320. {
  6321. #if defined(ENABLE_DEBUG_CONFIG_OPTIONS) && !(DBG)
  6322. // On fretest builds, capture the stack only if the FreTestDiagMode switch is on
  6323. doEntryPointCleanupCaptureStack = doEntryPointCleanupCaptureStack && Js::Configuration::Global.flags.FreTestDiagMode;
  6324. #endif
  6325. this->MapEntryPoints([=](int index, FunctionEntryPointInfo* entryPoint)
  6326. {
  6327. if (nullptr != entryPoint)
  6328. {
  6329. // Finalize = Free up work item if it hasn't been released yet + entry point clean up
  6330. // isShutdown is false because cleanup is called only in the !isShutdown case
  6331. entryPoint->Finalize(isShutdown);
  6332. #if ENABLE_DEBUG_STACK_BACK_TRACE
  6333. // Do this separately since calling EntryPoint::Finalize doesn't capture the stack trace
  6334. // and in some calls to CleanupRecyclerData, we do want the stack trace captured.
  6335. if (doEntryPointCleanupCaptureStack)
  6336. {
  6337. entryPoint->CaptureCleanupStackTrace();
  6338. }
  6339. #endif
  6340. }
  6341. });
  6342. this->MapLoopHeaders([=](uint loopNumber, LoopHeader* header)
  6343. {
  6344. bool shuttingDown = isShutdown;
  6345. header->MapEntryPoints([=](int index, LoopEntryPointInfo* entryPoint)
  6346. {
  6347. entryPoint->Cleanup(shuttingDown, doEntryPointCleanupCaptureStack);
  6348. });
  6349. });
  6350. }
  6351. #ifdef PERF_COUNTERS
  6352. this->CleanupPerfCounter();
  6353. #endif
  6354. }
  6355. //
  6356. // Removes all references of the function body and causes clean up of entry points.
  6357. // If the cleanup has already occurred before this would be a no-op.
  6358. //
  6359. void FunctionBody::Cleanup(bool isScriptContextClosing)
  6360. {
  6361. if (cleanedUp)
  6362. {
  6363. return;
  6364. }
  6365. DebugOnly(this->UnlockCounters());
  6366. CleanupRecyclerData(isScriptContextClosing, false /* capture entry point cleanup stack trace */);
  6367. CleanUpForInCache(isScriptContextClosing);
  6368. this->SetObjLiteralCount(0);
  6369. this->SetScopeSlotArraySizes(0, 0);
  6370. // Manually clear these values to break any circular references
  6371. // that might prevent the script context from being disposed
  6372. this->auxPtrs = nullptr;
  6373. AssertMsg(isScriptContextClosing || !m_hasActiveReference || !this->byteCodeBlock || !this->IsWasmFunction(), "We should never reset the bytecode block for Wasm when still referenced");
  6374. this->byteCodeBlock = nullptr;
  6375. this->entryPoints = nullptr;
  6376. this->inlineCaches = nullptr;
  6377. this->cacheIdToPropertyIdMap = nullptr;
  6378. this->polymorphicInlineCaches.Reset();
  6379. this->SetConstTable(nullptr);
  6380. #if DYNAMIC_INTERPRETER_THUNK
  6381. if (this->HasInterpreterThunkGenerated())
  6382. {
  6383. JS_ETW(EtwTrace::LogMethodInterpreterThunkUnloadEvent(this));
  6384. if (!isScriptContextClosing)
  6385. {
  6386. if (m_isAsmJsFunction)
  6387. {
  6388. m_scriptContext->ReleaseDynamicAsmJsInterpreterThunk((BYTE*)this->m_dynamicInterpreterThunk, /*addtoFreeList*/ true);
  6389. }
  6390. else
  6391. {
  6392. m_scriptContext->ReleaseDynamicInterpreterThunk((BYTE*)this->m_dynamicInterpreterThunk, /*addtoFreeList*/ true);
  6393. }
  6394. }
  6395. }
  6396. #endif
  6397. this->cleanedUp = true;
  6398. DebugOnly(this->LockDownCounters());
  6399. }
  6400. #ifdef PERF_COUNTERS
  6401. void FunctionBody::CleanupPerfCounter()
  6402. {
  6403. // We might not have the byte code block yet if we defer parsed.
  6404. DWORD byteCodeSize = (this->byteCodeBlock? this->byteCodeBlock->GetLength() : 0)
  6405. + (this->GetAuxiliaryData() ? this->GetAuxiliaryData()->GetLength() : 0)
  6406. + (this->GetAuxiliaryContextData() ? this->GetAuxiliaryContextData()->GetLength() : 0);
  6407. PERF_COUNTER_SUB(Code, DynamicByteCodeSize, byteCodeSize);
  6408. if (this->m_isDeserializedFunction)
  6409. {
  6410. PERF_COUNTER_DEC(Code, DeserializedFunctionBody);
  6411. }
  6412. PERF_COUNTER_SUB(Code, TotalByteCodeSize, byteCodeSize);
  6413. }
  6414. #endif
  6415. void FunctionBody::CaptureDynamicProfileState(FunctionEntryPointInfo* entryPointInfo)
  6416. {
  6417. // DisableJIT-TODO: Move this to be under if DYNAMIC_PROFILE
  6418. #if ENABLE_NATIVE_CODEGEN
  6419. // (See also the FunctionBody member written in CaptureDynamicProfileState.)
  6420. this->SetSavedPolymorphicCacheState(entryPointInfo->GetPendingPolymorphicCacheState());
  6421. this->savedInlinerVersion = entryPointInfo->GetPendingInlinerVersion();
  6422. this->savedImplicitCallsFlags = entryPointInfo->GetPendingImplicitCallFlags();
  6423. #endif
  6424. }
  6425. #if ENABLE_NATIVE_CODEGEN
  6426. BYTE FunctionBody::GetSavedInlinerVersion() const
  6427. {
  6428. Assert(this->dynamicProfileInfo != nullptr);
  6429. return this->savedInlinerVersion;
  6430. }
  6431. uint32 FunctionBody::GetSavedPolymorphicCacheState() const
  6432. {
  6433. Assert(this->dynamicProfileInfo != nullptr);
  6434. return this->savedPolymorphicCacheState;
  6435. }
  6436. void FunctionBody::SetSavedPolymorphicCacheState(uint32 state)
  6437. {
  6438. this->savedPolymorphicCacheState = state;
  6439. }
  6440. #endif
  6441. void FunctionBody::SetHasHotLoop()
  6442. {
  6443. if(hasHotLoop)
  6444. {
  6445. return;
  6446. }
  6447. hasHotLoop = true;
  6448. if(Configuration::Global.flags.EnforceExecutionModeLimits)
  6449. {
  6450. return;
  6451. }
  6452. executionState.CommitExecutedIterations();
  6453. TraceExecutionMode("HasHotLoop (before)");
  6454. if(executionState.GetFullJitThreshold() > 1)
  6455. {
  6456. executionState.SetFullJitThreshold(1, true);
  6457. }
  6458. TraceExecutionMode("HasHotLoop");
  6459. }
  6460. bool FunctionBody::IsInlineApplyDisabled()
  6461. {
  6462. return this->disableInlineApply;
  6463. }
  6464. void FunctionBody::SetDisableInlineApply(bool set)
  6465. {
  6466. this->disableInlineApply = set;
  6467. }
  6468. void FunctionBody::InitDisableInlineApply()
  6469. {
  6470. SetDisableInlineApply(
  6471. (this->GetLocalFunctionId() != Js::Constants::NoFunctionId && PHASE_OFF(Js::InlinePhase, this)) ||
  6472. PHASE_OFF(Js::InlineApplyPhase, this));
  6473. }
  6474. bool FunctionBody::CheckCalleeContextForInlining(FunctionProxy* calleeFunctionProxy)
  6475. {
  6476. return this->GetScriptContext() == calleeFunctionProxy->GetScriptContext();
  6477. }
  6478. #if ENABLE_NATIVE_CODEGEN
  6479. ImplicitCallFlags FunctionBody::GetSavedImplicitCallsFlags() const
  6480. {
  6481. Assert(this->dynamicProfileInfo != nullptr);
  6482. return this->savedImplicitCallsFlags;
  6483. }
  6484. bool FunctionBody::HasNonBuiltInCallee()
  6485. {
  6486. for (ProfileId i = 0; i < profiledCallSiteCount; i++)
  6487. {
  6488. Assert(HasDynamicProfileInfo());
  6489. bool ctor;
  6490. bool isPolymorphic;
  6491. FunctionInfo *info = dynamicProfileInfo->GetCallSiteInfo(this, i, &ctor, &isPolymorphic);
  6492. if (info == nullptr || info->HasBody())
  6493. {
  6494. return true;
  6495. }
  6496. }
  6497. return false;
  6498. }
  6499. #endif
  6500. #ifdef ENABLE_SCRIPT_DEBUGGING
  6501. void FunctionBody::CheckAndRegisterFuncToDiag(ScriptContext *scriptContext)
  6502. {
  6503. // We will register function if, this is not host managed and it was not registered before.
  6504. if (GetHostSourceContext() == Js::Constants::NoHostSourceContext
  6505. && !m_isFuncRegisteredToDiag
  6506. && !scriptContext->GetDebugContext()->GetProbeContainer()->IsContextRegistered(GetSecondaryHostSourceContext()))
  6507. {
  6508. FunctionBody *pFunc = scriptContext->GetDebugContext()->GetProbeContainer()->GetGlobalFunc(scriptContext, GetSecondaryHostSourceContext());
  6509. if (pFunc)
  6510. {
  6511. // Existing behavior here is to ignore the OOM and since RegisterFuncToDiag
  6512. // can throw now, we simply ignore the OOM here
  6513. try
  6514. {
  6515. // Register the function to the PDM as eval code (the debugger app will show file as 'eval code')
  6516. pFunc->RegisterFuncToDiag(scriptContext, Constants::EvalCode);
  6517. }
  6518. catch (Js::OutOfMemoryException)
  6519. {
  6520. }
  6521. scriptContext->GetDebugContext()->GetProbeContainer()->RegisterContextToDiag(GetSecondaryHostSourceContext(), scriptContext->AllocatorForDiagnostics());
  6522. m_isFuncRegisteredToDiag = true;
  6523. }
  6524. }
  6525. else
  6526. {
  6527. m_isFuncRegisteredToDiag = true;
  6528. }
  6529. }
  6530. #endif
  6531. DebuggerScope* FunctionBody::RecordStartScopeObject(DiagExtraScopesType scopeType, int start, RegSlot scopeLocation, int* index)
  6532. {
  6533. Recycler* recycler = m_scriptContext->GetRecycler();
  6534. if (!GetScopeObjectChain())
  6535. {
  6536. SetScopeObjectChain(RecyclerNew(recycler, ScopeObjectChain, recycler));
  6537. }
  6538. // Check if we need to create the scope object or if it already exists from a previous bytecode
  6539. // generator pass.
  6540. DebuggerScope* debuggerScope = nullptr;
  6541. int currentDebuggerScopeIndex = this->GetNextDebuggerScopeIndex();
  6542. if (!this->TryGetDebuggerScopeAt(currentDebuggerScopeIndex, debuggerScope))
  6543. {
  6544. // Create a new debugger scope.
  6545. debuggerScope = AddScopeObject(scopeType, start, scopeLocation);
  6546. }
  6547. else
  6548. {
  6549. debuggerScope->UpdateDueToByteCodeRegeneration(scopeType, start, scopeLocation);
  6550. }
  6551. if(index)
  6552. {
  6553. *index = currentDebuggerScopeIndex;
  6554. }
  6555. return debuggerScope;
  6556. }
  6557. void FunctionBody::RecordEndScopeObject(DebuggerScope* currentScope, int end)
  6558. {
  6559. AssertMsg(currentScope, "No current debugger scope passed in.");
  6560. currentScope->SetEnd(end);
  6561. }
  6562. DebuggerScope * FunctionBody::AddScopeObject(DiagExtraScopesType scopeType, int start, RegSlot scopeLocation)
  6563. {
  6564. Assert(GetScopeObjectChain());
  6565. DebuggerScope *scopeObject = RecyclerNew(m_scriptContext->GetRecycler(), DebuggerScope, m_scriptContext->GetRecycler(), scopeType, scopeLocation, start);
  6566. GetScopeObjectChain()->pScopeChain->Add(scopeObject);
  6567. return scopeObject;
  6568. }
  6569. // Tries to retrieve the debugger scope at the specified index. If the index is out of range, nullptr
  6570. // is returned.
  6571. bool FunctionBody::TryGetDebuggerScopeAt(int index, DebuggerScope*& debuggerScope)
  6572. {
  6573. AssertMsg(this->GetScopeObjectChain(), "TryGetDebuggerScopeAt should only be called with a valid scope chain in place.");
  6574. Assert(index >= 0);
  6575. const Js::ScopeObjectChain::ScopeObjectChainList* scopeChain = this->GetScopeObjectChain()->pScopeChain;
  6576. if (index < scopeChain->Count())
  6577. {
  6578. debuggerScope = scopeChain->Item(index);
  6579. return true;
  6580. }
  6581. return false;
  6582. }
  6583. #if DYNAMIC_INTERPRETER_THUNK
  6584. DWORD FunctionBody::GetDynamicInterpreterThunkSize() const
  6585. {
  6586. return InterpreterThunkEmitter::ThunkSize;
  6587. }
  6588. #endif
  6589. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  6590. void
  6591. FunctionBody::DumpFullFunctionName()
  6592. {
  6593. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  6594. Output::Print(_u("Function %s (%s)"), this->GetDisplayName(), this->GetDebugNumberSet(debugStringBuffer));
  6595. }
  6596. void FunctionBody::DumpFunctionId(bool pad)
  6597. {
  6598. uint sourceContextId = this->GetSourceContextInfo()->sourceContextId;
  6599. if (sourceContextId == Js::Constants::NoSourceContext)
  6600. {
  6601. if (this->IsDynamicScript())
  6602. {
  6603. Output::Print(pad? _u("Dy.%-3d") : _u("Dyn#%d"), this->GetLocalFunctionId());
  6604. }
  6605. else
  6606. {
  6607. // Function from LoadFile
  6608. Output::Print(pad? _u("%-5d") : _u("#%d"), this->GetLocalFunctionId());
  6609. }
  6610. }
  6611. else
  6612. {
  6613. Output::Print(pad? _u("%2d.%-3d") : _u("#%d.%d"), sourceContextId, this->GetLocalFunctionId());
  6614. }
  6615. }
  6616. #endif
  6617. void FunctionBody::EnsureAuxStatementData()
  6618. {
  6619. if (m_sourceInfo.m_auxStatementData == nullptr)
  6620. {
  6621. Recycler* recycler = m_scriptContext->GetRecycler();
  6622. // Note: allocating must be consistent with clean up in CleanupToReparse.
  6623. m_sourceInfo.m_auxStatementData = RecyclerNew(recycler, AuxStatementData);
  6624. }
  6625. }
  6626. /*static*/
  6627. void FunctionBody::GetShortNameFromUrl(__in LPCWSTR pchUrl, _Out_writes_z_(cchBuffer) LPWSTR pchShortName, __in size_t cchBuffer)
  6628. {
  6629. LPCWSTR pchFile = wcsrchr(pchUrl, _u('/'));
  6630. if (pchFile == nullptr)
  6631. {
  6632. pchFile = wcsrchr(pchUrl, _u('\\'));
  6633. }
  6634. LPCWSTR pchToCopy = pchUrl;
  6635. if (pchFile != nullptr)
  6636. {
  6637. pchToCopy = pchFile + 1;
  6638. }
  6639. wcscpy_s(pchShortName, cchBuffer, pchToCopy);
  6640. }
  6641. FunctionBody::StatementAdjustmentRecordList* FunctionBody::GetStatementAdjustmentRecords()
  6642. {
  6643. if (m_sourceInfo.m_auxStatementData)
  6644. {
  6645. return m_sourceInfo.m_auxStatementData->m_statementAdjustmentRecords;
  6646. }
  6647. return nullptr;
  6648. }
  6649. FunctionBody::CrossFrameEntryExitRecordList* FunctionBody::GetCrossFrameEntryExitRecords()
  6650. {
  6651. if (m_sourceInfo.m_auxStatementData)
  6652. {
  6653. return m_sourceInfo.m_auxStatementData->m_crossFrameBlockEntryExisRecords;
  6654. }
  6655. return nullptr;
  6656. }
  6657. void FunctionBody::RecordCrossFrameEntryExitRecord(uint byteCodeOffset, bool isEnterBlock)
  6658. {
  6659. this->EnsureAuxStatementData();
  6660. Recycler* recycler = this->m_scriptContext->GetRecycler();
  6661. if (this->GetCrossFrameEntryExitRecords() == nullptr)
  6662. {
  6663. m_sourceInfo.m_auxStatementData->m_crossFrameBlockEntryExisRecords = RecyclerNew(recycler, CrossFrameEntryExitRecordList, recycler);
  6664. }
  6665. Assert(this->GetCrossFrameEntryExitRecords());
  6666. CrossFrameEntryExitRecord record(byteCodeOffset, isEnterBlock);
  6667. this->GetCrossFrameEntryExitRecords()->Add(record); // Will copy stack value and put the copy into the container.
  6668. }
  6669. FunctionBody::AuxStatementData::AuxStatementData() : m_statementAdjustmentRecords(nullptr), m_crossFrameBlockEntryExisRecords(nullptr)
  6670. {
  6671. }
  6672. FunctionBody::StatementAdjustmentRecord::StatementAdjustmentRecord() :
  6673. m_byteCodeOffset((uint)Constants::InvalidOffset), m_adjustmentType(SAT_None)
  6674. {
  6675. }
  6676. FunctionBody::StatementAdjustmentRecord::StatementAdjustmentRecord(StatementAdjustmentType type, int byteCodeOffset) :
  6677. m_adjustmentType(type), m_byteCodeOffset(byteCodeOffset)
  6678. {
  6679. Assert(SAT_None <= type && type <= SAT_All);
  6680. }
  6681. FunctionBody::StatementAdjustmentRecord::StatementAdjustmentRecord(const StatementAdjustmentRecord& other) :
  6682. m_byteCodeOffset(other.m_byteCodeOffset), m_adjustmentType(other.m_adjustmentType)
  6683. {
  6684. }
  6685. uint FunctionBody::StatementAdjustmentRecord::GetByteCodeOffset()
  6686. {
  6687. Assert(m_byteCodeOffset != Constants::InvalidOffset);
  6688. return m_byteCodeOffset;
  6689. }
  6690. FunctionBody::StatementAdjustmentType FunctionBody::StatementAdjustmentRecord::GetAdjustmentType()
  6691. {
  6692. Assert(this->m_adjustmentType != SAT_None);
  6693. return m_adjustmentType;
  6694. }
  6695. FunctionBody::CrossFrameEntryExitRecord::CrossFrameEntryExitRecord() :
  6696. m_byteCodeOffset((uint)Constants::InvalidOffset), m_isEnterBlock(false)
  6697. {
  6698. }
  6699. FunctionBody::CrossFrameEntryExitRecord::CrossFrameEntryExitRecord(uint byteCodeOffset, bool isEnterBlock) :
  6700. m_byteCodeOffset(byteCodeOffset), m_isEnterBlock(isEnterBlock)
  6701. {
  6702. }
  6703. FunctionBody::CrossFrameEntryExitRecord::CrossFrameEntryExitRecord(const CrossFrameEntryExitRecord& other) :
  6704. m_byteCodeOffset(other.m_byteCodeOffset), m_isEnterBlock(other.m_isEnterBlock)
  6705. {
  6706. }
  6707. uint FunctionBody::CrossFrameEntryExitRecord::GetByteCodeOffset() const
  6708. {
  6709. Assert(m_byteCodeOffset != Constants::InvalidOffset);
  6710. return m_byteCodeOffset;
  6711. }
  6712. bool FunctionBody::CrossFrameEntryExitRecord::GetIsEnterBlock()
  6713. {
  6714. return m_isEnterBlock;
  6715. }
  6716. EntryPointPolymorphicInlineCacheInfo::EntryPointPolymorphicInlineCacheInfo(FunctionBody * functionBody) :
  6717. selfInfo(functionBody),
  6718. inlineeInfo(functionBody->GetRecycler())
  6719. {
  6720. }
  6721. PolymorphicInlineCacheInfo * EntryPointPolymorphicInlineCacheInfo::GetInlineeInfo(FunctionBody * inlineeFunctionBody)
  6722. {
  6723. SListCounted<PolymorphicInlineCacheInfo*, Recycler>::Iterator iter(&inlineeInfo);
  6724. while (iter.Next())
  6725. {
  6726. PolymorphicInlineCacheInfo * info = iter.Data();
  6727. if (info->GetFunctionBody() == inlineeFunctionBody)
  6728. {
  6729. return info;
  6730. }
  6731. }
  6732. return nullptr;
  6733. }
  6734. PolymorphicInlineCacheInfo * EntryPointPolymorphicInlineCacheInfo::EnsureInlineeInfo(Recycler * recycler, FunctionBody * inlineeFunctionBody)
  6735. {
  6736. PolymorphicInlineCacheInfo * info = GetInlineeInfo(inlineeFunctionBody);
  6737. if (!info)
  6738. {
  6739. info = RecyclerNew(recycler, PolymorphicInlineCacheInfo, inlineeFunctionBody);
  6740. inlineeInfo.Prepend(info);
  6741. }
  6742. return info;
  6743. }
  6744. void EntryPointPolymorphicInlineCacheInfo::SetPolymorphicInlineCache(FunctionBody * functionBody, uint index, PolymorphicInlineCache * polymorphicInlineCache, bool isInlinee, byte polyCacheUtil)
  6745. {
  6746. if (!isInlinee)
  6747. {
  6748. SetPolymorphicInlineCache(&selfInfo, functionBody, index, polymorphicInlineCache, polyCacheUtil);
  6749. Assert(functionBody == selfInfo.GetFunctionBody());
  6750. }
  6751. else
  6752. {
  6753. SetPolymorphicInlineCache(EnsureInlineeInfo(functionBody->GetScriptContext()->GetRecycler(), functionBody), functionBody, index, polymorphicInlineCache, polyCacheUtil);
  6754. Assert(functionBody == GetInlineeInfo(functionBody)->GetFunctionBody());
  6755. }
  6756. }
  6757. void EntryPointPolymorphicInlineCacheInfo::SetPolymorphicInlineCache(PolymorphicInlineCacheInfo * polymorphicInlineCacheInfo, FunctionBody * functionBody, uint index, PolymorphicInlineCache * polymorphicInlineCache, byte polyCacheUtil)
  6758. {
  6759. polymorphicInlineCacheInfo->GetPolymorphicInlineCaches()->SetInlineCache(functionBody->GetScriptContext()->GetRecycler(), functionBody, index, polymorphicInlineCache);
  6760. polymorphicInlineCacheInfo->GetUtilArray()->SetUtil(functionBody, index, polyCacheUtil);
  6761. }
  6762. void PolymorphicCacheUtilizationArray::SetUtil(Js::FunctionBody* functionBody, uint index, byte util)
  6763. {
  6764. Assert(functionBody);
  6765. Assert(index < functionBody->GetInlineCacheCount());
  6766. EnsureUtilArray(functionBody->GetScriptContext()->GetRecycler(), functionBody);
  6767. this->utilArray[index] = util;
  6768. }
  6769. byte PolymorphicCacheUtilizationArray::GetUtil(Js::FunctionBody* functionBody, uint index)
  6770. {
  6771. Assert(index < functionBody->GetInlineCacheCount());
  6772. return this->utilArray[index];
  6773. }
  6774. void PolymorphicCacheUtilizationArray::EnsureUtilArray(Recycler * const recycler, Js::FunctionBody * functionBody)
  6775. {
  6776. Assert(recycler);
  6777. Assert(functionBody);
  6778. Assert(functionBody->GetInlineCacheCount() != 0);
  6779. if(this->utilArray)
  6780. {
  6781. return;
  6782. }
  6783. this->utilArray = RecyclerNewArrayLeafZ(recycler, byte, functionBody->GetInlineCacheCount());
  6784. }
  6785. #if ENABLE_NATIVE_CODEGEN
  6786. void EntryPointInfo::AddWeakFuncRef(RecyclerWeakReference<FunctionBody> *weakFuncRef, Recycler *recycler)
  6787. {
  6788. Assert(this->state == CodeGenPending);
  6789. this->weakFuncRefSet = this->EnsureWeakFuncRefSet(recycler);
  6790. this->weakFuncRefSet->AddNew(weakFuncRef);
  6791. }
  6792. EntryPointInfo::WeakFuncRefSet *
  6793. EntryPointInfo::EnsureWeakFuncRefSet(Recycler *recycler)
  6794. {
  6795. if (this->weakFuncRefSet == nullptr)
  6796. {
  6797. this->weakFuncRefSet = RecyclerNew(recycler, WeakFuncRefSet, recycler);
  6798. }
  6799. return this->weakFuncRefSet;
  6800. }
  6801. void EntryPointInfo::EnsureIsReadyToCall()
  6802. {
  6803. ProcessJitTransferData();
  6804. #if !FLOATVAR
  6805. if (this->numberPageSegments)
  6806. {
  6807. auto numberArray = this->GetScriptContext()->GetThreadContext()
  6808. ->GetXProcNumberPageSegmentManager()->RegisterSegments(this->numberPageSegments);
  6809. this->SetNumberArray(numberArray);
  6810. this->numberPageSegments = nullptr;
  6811. }
  6812. #endif
  6813. }
  6814. void EntryPointInfo::SetCodeGenDone()
  6815. {
  6816. Assert(this->GetState() == CodeGenRecorded);
  6817. this->state = CodeGenDone;
  6818. this->workItem = nullptr;
  6819. if (this->IsLoopBody())
  6820. {
  6821. this->GetFunctionBody()->SetHasDoneLoopBodyCodeGen(true);
  6822. }
  6823. }
  6824. void EntryPointInfo::ProcessJitTransferData()
  6825. {
  6826. Assert(!IsCleanedUp());
  6827. auto jitTransferData = GetJitTransferData();
  6828. if (jitTransferData == nullptr)
  6829. {
  6830. return;
  6831. }
  6832. class AutoCleanup
  6833. {
  6834. EntryPointInfo *entryPointInfo;
  6835. public:
  6836. AutoCleanup(EntryPointInfo *entryPointInfo) : entryPointInfo(entryPointInfo)
  6837. {
  6838. }
  6839. void Done()
  6840. {
  6841. entryPointInfo = nullptr;
  6842. }
  6843. ~AutoCleanup()
  6844. {
  6845. if (entryPointInfo)
  6846. {
  6847. entryPointInfo->OnNativeCodeInstallFailure();
  6848. }
  6849. }
  6850. } autoCleanup(this);
  6851. ScriptContext* scriptContext = GetScriptContext();
  6852. if (jitTransferData->GetIsReady())
  6853. {
  6854. PinTypeRefs(scriptContext);
  6855. InstallGuards(scriptContext);
  6856. FreeJitTransferData();
  6857. }
  6858. autoCleanup.Done();
  6859. }
  6860. EntryPointInfo::JitTransferData* EntryPointInfo::EnsureJitTransferData(Recycler* recycler)
  6861. {
  6862. if (this->jitTransferData == nullptr)
  6863. {
  6864. this->jitTransferData = RecyclerNew(recycler, EntryPointInfo::JitTransferData);
  6865. }
  6866. return this->jitTransferData;
  6867. }
  6868. void EntryPointInfo::OnNativeCodeInstallFailure()
  6869. {
  6870. // If more data is transferred from the background thread to the main thread in ProcessJitTransferData,
  6871. // corresponding fields on the entryPointInfo should be rolled back here.
  6872. this->runtimeTypeRefs = nullptr;
  6873. this->FreePropertyGuards();
  6874. this->equivalentTypeCacheCount = 0;
  6875. this->equivalentTypeCaches = nullptr;
  6876. this->UnregisterEquivalentTypeCaches();
  6877. this->ResetOnNativeCodeInstallFailure();
  6878. }
  6879. #ifdef FIELD_ACCESS_STATS
  6880. FieldAccessStats* EntryPointInfo::EnsureFieldAccessStats(Recycler* recycler)
  6881. {
  6882. if (this->fieldAccessStats == nullptr)
  6883. {
  6884. this->fieldAccessStats = RecyclerNew(recycler, FieldAccessStats);
  6885. }
  6886. return this->fieldAccessStats;
  6887. }
  6888. #endif
  6889. void EntryPointInfo::JitTransferData::AddJitTimeTypeRef(void* typeRef, Recycler* recycler)
  6890. {
  6891. Assert(typeRef != nullptr);
  6892. EnsureJitTimeTypeRefs(recycler);
  6893. this->jitTimeTypeRefs->AddNew(typeRef);
  6894. }
  6895. void EntryPointInfo::JitTransferData::EnsureJitTimeTypeRefs(Recycler* recycler)
  6896. {
  6897. if (this->jitTimeTypeRefs == nullptr)
  6898. {
  6899. this->jitTimeTypeRefs = RecyclerNew(recycler, TypeRefSet, recycler);
  6900. }
  6901. }
  6902. void EntryPointInfo::PinTypeRefs(ScriptContext* scriptContext)
  6903. {
  6904. Assert(this->jitTransferData != nullptr && this->jitTransferData->GetIsReady());
  6905. Recycler* recycler = scriptContext->GetRecycler();
  6906. if (this->jitTransferData->GetRuntimeTypeRefs() != nullptr)
  6907. {
  6908. // Copy pinned types from a heap allocated array created on the background thread
  6909. // to a recycler allocated array which will live as long as this EntryPointInfo.
  6910. // The original heap allocated array will be freed at the end of NativeCodeGenerator::CheckCodeGenDone
  6911. void** jitPinnedTypeRefs = this->jitTransferData->GetRuntimeTypeRefs();
  6912. size_t jitPinnedTypeRefCount = this->jitTransferData->GetRuntimeTypeRefCount();
  6913. this->runtimeTypeRefs = RecyclerNewArray(recycler, Field(void*), jitPinnedTypeRefCount + 1);
  6914. //js_memcpy_s(this->runtimeTypeRefs, jitPinnedTypeRefCount * sizeof(void*), jitPinnedTypeRefs, jitPinnedTypeRefCount * sizeof(void*));
  6915. for (size_t i = 0; i < jitPinnedTypeRefCount; i++)
  6916. {
  6917. this->runtimeTypeRefs[i] = jitPinnedTypeRefs[i];
  6918. }
  6919. this->runtimeTypeRefs[jitPinnedTypeRefCount] = nullptr;
  6920. }
  6921. }
  6922. void EntryPointInfo::InstallGuards(ScriptContext* scriptContext)
  6923. {
  6924. Assert(this->jitTransferData != nullptr && this->jitTransferData->GetIsReady());
  6925. Assert(this->equivalentTypeCacheCount == 0 && this->equivalentTypeCaches == nullptr);
  6926. Assert(this->propertyGuardCount == 0 && this->propertyGuardWeakRefs == nullptr);
  6927. for (int i = 0; i < this->jitTransferData->lazyBailoutPropertyCount; i++)
  6928. {
  6929. Assert(this->jitTransferData->lazyBailoutProperties != nullptr);
  6930. Js::PropertyId propertyId = this->jitTransferData->lazyBailoutProperties[i];
  6931. Js::PropertyGuard* sharedPropertyGuard = nullptr;
  6932. bool hasSharedPropertyGuard = TryGetSharedPropertyGuard(propertyId, sharedPropertyGuard);
  6933. Assert(hasSharedPropertyGuard);
  6934. bool isValid = hasSharedPropertyGuard ? sharedPropertyGuard->IsValid() : false;
  6935. if (isValid)
  6936. {
  6937. scriptContext->GetThreadContext()->RegisterLazyBailout(propertyId, this);
  6938. }
  6939. else
  6940. {
  6941. OUTPUT_TRACE2(Js::LazyBailoutPhase, this->GetFunctionBody(), _u("Lazy bailout - Invalidation due to property: %s \n"), scriptContext->GetPropertyName(propertyId)->GetBuffer());
  6942. this->Invalidate(true);
  6943. return;
  6944. }
  6945. }
  6946. // in-proc JIT
  6947. if (this->jitTransferData->equivalentTypeGuardCount > 0)
  6948. {
  6949. Assert(jitTransferData->equivalentTypeGuardOffsets == nullptr);
  6950. Assert(this->jitTransferData->equivalentTypeGuards != nullptr);
  6951. Recycler* recycler = scriptContext->GetRecycler();
  6952. int guardCount = this->jitTransferData->equivalentTypeGuardCount;
  6953. JitEquivalentTypeGuard** guards = this->jitTransferData->equivalentTypeGuards;
  6954. // Create an array of equivalent type caches on the entry point info to ensure they are kept
  6955. // alive for the lifetime of the entry point.
  6956. this->equivalentTypeCacheCount = guardCount;
  6957. // No need to zero-initialize, since we will populate all data slots.
  6958. // We used to let the recycler scan the types in the cache, but we no longer do. See
  6959. // ThreadContext::ClearEquivalentTypeCaches for an explanation.
  6960. this->equivalentTypeCaches = RecyclerNewArrayLeafZ(recycler, EquivalentTypeCache, guardCount);
  6961. this->RegisterEquivalentTypeCaches();
  6962. EquivalentTypeCache* cache = this->equivalentTypeCaches;
  6963. for (JitEquivalentTypeGuard** guard = guards; guard < guards + guardCount; guard++)
  6964. {
  6965. EquivalentTypeCache* oldCache = (*guard)->GetCache();
  6966. // Copy the contents of the heap-allocated cache to the recycler-allocated version to make sure the types are
  6967. // kept alive. Allow the properties pointer to refer to the heap-allocated arrays. It will stay alive as long
  6968. // as the entry point is alive, and property entries contain no pointers to other recycler allocated objects.
  6969. (*cache) = (*oldCache);
  6970. // Set the recycler-allocated cache on the (heap-allocated) guard.
  6971. (*guard)->SetCache(cache);
  6972. for (uint i = 0; i < EQUIVALENT_TYPE_CACHE_SIZE; i++)
  6973. {
  6974. if((*cache).types[i] != nullptr)
  6975. {
  6976. (*cache).types[i]->SetHasBeenCached();
  6977. }
  6978. else
  6979. {
  6980. #ifdef DEBUG
  6981. for (uint __i = i; __i < EQUIVALENT_TYPE_CACHE_SIZE; __i++)
  6982. { Assert((*cache).types[__i] == nullptr); }
  6983. #endif
  6984. break; // type array must be shrinked.
  6985. }
  6986. }
  6987. cache++;
  6988. }
  6989. }
  6990. if (jitTransferData->equivalentTypeGuardOffsets)
  6991. {
  6992. Recycler* recycler = scriptContext->GetRecycler();
  6993. // InstallGuards
  6994. int guardCount = jitTransferData->equivalentTypeGuardOffsets->count;
  6995. // Create an array of equivalent type caches on the entry point info to ensure they are kept
  6996. // alive for the lifetime of the entry point.
  6997. this->equivalentTypeCacheCount = guardCount;
  6998. // No need to zero-initialize, since we will populate all data slots.
  6999. // We used to let the recycler scan the types in the cache, but we no longer do. See
  7000. // ThreadContext::ClearEquivalentTypeCaches for an explanation.
  7001. this->equivalentTypeCaches = RecyclerNewArrayLeafZ(recycler, EquivalentTypeCache, guardCount);
  7002. this->RegisterEquivalentTypeCaches();
  7003. EquivalentTypeCache* cache = this->equivalentTypeCaches;
  7004. for (int i = 0; i < guardCount; i++)
  7005. {
  7006. auto& cacheIDL = jitTransferData->equivalentTypeGuardOffsets->guards[i].cache;
  7007. auto guardOffset = jitTransferData->equivalentTypeGuardOffsets->guards[i].offset;
  7008. JitEquivalentTypeGuard* guard = (JitEquivalentTypeGuard*)(this->GetNativeDataBuffer() + guardOffset);
  7009. cache[i].guard = guard;
  7010. cache[i].hasFixedValue = cacheIDL.hasFixedValue != 0;
  7011. cache[i].isLoadedFromProto = cacheIDL.isLoadedFromProto != 0;
  7012. cache[i].nextEvictionVictim = cacheIDL.nextEvictionVictim;
  7013. cache[i].record.propertyCount = cacheIDL.record.propertyCount;
  7014. cache[i].record.properties = (EquivalentPropertyEntry*)(this->GetNativeDataBuffer() + cacheIDL.record.propertyOffset);
  7015. for (int j = 0; j < EQUIVALENT_TYPE_CACHE_SIZE; j++)
  7016. {
  7017. cache[i].types[j] = (Js::Type*)cacheIDL.types[j];
  7018. }
  7019. guard->SetCache(&cache[i]);
  7020. }
  7021. }
  7022. // OOP JIT
  7023. if (jitTransferData->typeGuardTransferData.entries != nullptr)
  7024. {
  7025. this->propertyGuardCount = jitTransferData->typeGuardTransferData.propertyGuardCount;
  7026. this->propertyGuardWeakRefs = RecyclerNewArrayZ(scriptContext->GetRecycler(), Field(FakePropertyGuardWeakReference*), this->propertyGuardCount);
  7027. ThreadContext* threadContext = scriptContext->GetThreadContext();
  7028. auto next = &jitTransferData->typeGuardTransferData.entries;
  7029. while (*next)
  7030. {
  7031. Js::PropertyId propertyId = (*next)->propId;
  7032. Js::PropertyGuard* sharedPropertyGuard = nullptr;
  7033. // We use the shared guard created during work item creation to ensure that the condition we assumed didn't change while
  7034. // we were JIT-ing. If we don't have a shared property guard for this property then we must not need to protect it,
  7035. // because it exists on the instance. Unfortunately, this means that if we have a bug and fail to create a shared
  7036. // guard for some property during work item creation, we won't find out about it here.
  7037. bool isNeeded = TryGetSharedPropertyGuard(propertyId, sharedPropertyGuard);
  7038. bool isValid = isNeeded ? sharedPropertyGuard->IsValid() : false;
  7039. if (isNeeded)
  7040. {
  7041. for (unsigned int i = 0; i < (*next)->guardsCount; i++)
  7042. {
  7043. Js::JitIndexedPropertyGuard* guard = (Js::JitIndexedPropertyGuard*)(this->nativeDataBuffer + (*next)->guardOffsets[i]);
  7044. int guardIndex = guard->GetIndex();
  7045. Assert(guardIndex >= 0 && guardIndex < this->propertyGuardCount);
  7046. // We use the shared guard here to make sure the conditions we assumed didn't change while we were JIT-ing.
  7047. // If they did, we proactively invalidate the guard here, so that we bail out if we try to call this code.
  7048. if (isValid)
  7049. {
  7050. auto propertyGuardWeakRef = this->propertyGuardWeakRefs[guardIndex];
  7051. if (propertyGuardWeakRef == nullptr)
  7052. {
  7053. propertyGuardWeakRef = Js::FakePropertyGuardWeakReference::New(scriptContext->GetRecycler(), guard);
  7054. this->propertyGuardWeakRefs[guardIndex] = propertyGuardWeakRef;
  7055. }
  7056. Assert(propertyGuardWeakRef->Get() == guard);
  7057. threadContext->RegisterUniquePropertyGuard(propertyId, propertyGuardWeakRef);
  7058. }
  7059. else
  7060. {
  7061. guard->Invalidate();
  7062. }
  7063. }
  7064. }
  7065. *next = (*next)->next;
  7066. }
  7067. }
  7068. // in-proc JIT
  7069. // The propertyGuardsByPropertyId structure is temporary and serves only to register the type guards for the correct
  7070. // properties. If we've done code gen for this EntryPointInfo, typePropertyGuardsByPropertyId will have been used and nulled out.
  7071. if (this->jitTransferData->propertyGuardsByPropertyId != nullptr)
  7072. {
  7073. this->propertyGuardCount = this->jitTransferData->propertyGuardCount;
  7074. this->propertyGuardWeakRefs = RecyclerNewArrayZ(scriptContext->GetRecycler(), Field(FakePropertyGuardWeakReference*), this->propertyGuardCount);
  7075. ThreadContext* threadContext = scriptContext->GetThreadContext();
  7076. Js::TypeGuardTransferEntry* entry = this->jitTransferData->propertyGuardsByPropertyId;
  7077. while (entry->propertyId != Js::Constants::NoProperty)
  7078. {
  7079. Js::PropertyId propertyId = entry->propertyId;
  7080. Js::PropertyGuard* sharedPropertyGuard = nullptr;
  7081. // We use the shared guard created during work item creation to ensure that the condition we assumed didn't change while
  7082. // we were JIT-ing. If we don't have a shared property guard for this property then we must not need to protect it,
  7083. // because it exists on the instance. Unfortunately, this means that if we have a bug and fail to create a shared
  7084. // guard for some property during work item creation, we won't find out about it here.
  7085. bool isNeeded = TryGetSharedPropertyGuard(propertyId, sharedPropertyGuard);
  7086. bool isValid = isNeeded ? sharedPropertyGuard->IsValid() : false;
  7087. int entryGuardIndex = 0;
  7088. while (entry->guards[entryGuardIndex] != nullptr)
  7089. {
  7090. if (isNeeded)
  7091. {
  7092. Js::JitIndexedPropertyGuard* guard = entry->guards[entryGuardIndex];
  7093. int guardIndex = guard->GetIndex();
  7094. Assert(guardIndex >= 0 && guardIndex < this->propertyGuardCount);
  7095. // We use the shared guard here to make sure the conditions we assumed didn't change while we were JIT-ing.
  7096. // If they did, we proactively invalidate the guard here, so that we bail out if we try to call this code.
  7097. if (isValid)
  7098. {
  7099. auto propertyGuardWeakRef = this->propertyGuardWeakRefs[guardIndex];
  7100. if (propertyGuardWeakRef == nullptr)
  7101. {
  7102. propertyGuardWeakRef = Js::FakePropertyGuardWeakReference::New(scriptContext->GetRecycler(), guard);
  7103. this->propertyGuardWeakRefs[guardIndex] = propertyGuardWeakRef;
  7104. }
  7105. Assert(propertyGuardWeakRef->Get() == guard);
  7106. threadContext->RegisterUniquePropertyGuard(propertyId, propertyGuardWeakRef);
  7107. }
  7108. else
  7109. {
  7110. guard->Invalidate();
  7111. }
  7112. }
  7113. entryGuardIndex++;
  7114. }
  7115. entry = reinterpret_cast<Js::TypeGuardTransferEntry*>(&entry->guards[++entryGuardIndex]);
  7116. }
  7117. }
  7118. // The ctorCacheGuardsByPropertyId structure is temporary and serves only to register the constructor cache guards for the correct
  7119. // properties. If we've done code gen for this EntryPointInfo, ctorCacheGuardsByPropertyId will have been used and nulled out.
  7120. // Unlike type property guards, constructor cache guards use the live constructor caches associated with function objects. These are
  7121. // recycler allocated and are kept alive by the constructorCaches field, where they were inserted during work item creation.
  7122. // OOP JIT
  7123. if (jitTransferData->ctorCacheTransferData.entries != nullptr)
  7124. {
  7125. ThreadContext* threadContext = scriptContext->GetThreadContext();
  7126. CtorCacheTransferEntryIDL ** entries = this->jitTransferData->ctorCacheTransferData.entries;
  7127. for (uint i = 0; i < this->jitTransferData->ctorCacheTransferData.ctorCachesCount; ++i)
  7128. {
  7129. Js::PropertyId propertyId = entries[i]->propId;
  7130. Js::PropertyGuard* sharedPropertyGuard = nullptr;
  7131. // We use the shared guard created during work item creation to ensure that the condition we assumed didn't change while
  7132. // we were JIT-ing. If we don't have a shared property guard for this property then we must not need to protect it,
  7133. // because it exists on the instance. Unfortunately, this means that if we have a bug and fail to create a shared
  7134. // guard for some property during work item creation, we won't find out about it here.
  7135. bool isNeeded = TryGetSharedPropertyGuard(propertyId, sharedPropertyGuard);
  7136. bool isValid = isNeeded ? sharedPropertyGuard->IsValid() : false;
  7137. if (isNeeded)
  7138. {
  7139. for (uint j = 0; j < entries[i]->cacheCount; ++j)
  7140. {
  7141. Js::ConstructorCache* cache = (Js::ConstructorCache*)(entries[i]->caches[j]);
  7142. // We use the shared cache here to make sure the conditions we assumed didn't change while we were JIT-ing.
  7143. // If they did, we proactively invalidate the cache here, so that we bail out if we try to call this code.
  7144. if (isValid)
  7145. {
  7146. threadContext->RegisterConstructorCache(propertyId, cache);
  7147. }
  7148. else
  7149. {
  7150. cache->InvalidateAsGuard();
  7151. }
  7152. }
  7153. }
  7154. }
  7155. }
  7156. if (this->jitTransferData->ctorCacheGuardsByPropertyId != nullptr)
  7157. {
  7158. ThreadContext* threadContext = scriptContext->GetThreadContext();
  7159. Js::CtorCacheGuardTransferEntry* entry = this->jitTransferData->ctorCacheGuardsByPropertyId;
  7160. while (entry->propertyId != Js::Constants::NoProperty)
  7161. {
  7162. Js::PropertyId propertyId = entry->propertyId;
  7163. Js::PropertyGuard* sharedPropertyGuard = nullptr;
  7164. // We use the shared guard created during work item creation to ensure that the condition we assumed didn't change while
  7165. // we were JIT-ing. If we don't have a shared property guard for this property then we must not need to protect it,
  7166. // because it exists on the instance. Unfortunately, this means that if we have a bug and fail to create a shared
  7167. // guard for some property during work item creation, we won't find out about it here.
  7168. bool isNeeded = TryGetSharedPropertyGuard(propertyId, sharedPropertyGuard);
  7169. bool isValid = isNeeded ? sharedPropertyGuard->IsValid() : false;
  7170. int entryCacheIndex = 0;
  7171. while (entry->caches[entryCacheIndex] != 0)
  7172. {
  7173. if (isNeeded)
  7174. {
  7175. Js::ConstructorCache* cache = (Js::ConstructorCache*)(entry->caches[entryCacheIndex]);
  7176. // We use the shared cache here to make sure the conditions we assumed didn't change while we were JIT-ing.
  7177. // If they did, we proactively invalidate the cache here, so that we bail out if we try to call this code.
  7178. if (isValid)
  7179. {
  7180. threadContext->RegisterConstructorCache(propertyId, cache);
  7181. }
  7182. else
  7183. {
  7184. cache->InvalidateAsGuard();
  7185. }
  7186. }
  7187. entryCacheIndex++;
  7188. }
  7189. entry = reinterpret_cast<Js::CtorCacheGuardTransferEntry*>(&entry->caches[++entryCacheIndex]);
  7190. }
  7191. }
  7192. if (PHASE_ON(Js::FailNativeCodeInstallPhase, this->GetFunctionBody()))
  7193. {
  7194. Js::Throw::OutOfMemory();
  7195. }
  7196. }
  7197. PropertyGuard* EntryPointInfo::RegisterSharedPropertyGuard(Js::PropertyId propertyId, ScriptContext* scriptContext)
  7198. {
  7199. if (this->sharedPropertyGuards == nullptr)
  7200. {
  7201. Recycler* recycler = scriptContext->GetRecycler();
  7202. this->sharedPropertyGuards = RecyclerNew(recycler, SharedPropertyGuardDictionary, recycler);
  7203. }
  7204. PropertyGuard* guard = nullptr;
  7205. if (!this->sharedPropertyGuards->TryGetValue(propertyId, &guard))
  7206. {
  7207. ThreadContext* threadContext = scriptContext->GetThreadContext();
  7208. guard = threadContext->RegisterSharedPropertyGuard(propertyId);
  7209. this->sharedPropertyGuards->Add(propertyId, guard);
  7210. }
  7211. return guard;
  7212. }
  7213. Js::PropertyId* EntryPointInfo::GetSharedPropertyGuards(_Out_ unsigned int& count)
  7214. {
  7215. Js::PropertyId* sharedPropertyGuards = nullptr;
  7216. unsigned int guardCount = 0;
  7217. if (this->sharedPropertyGuards != nullptr)
  7218. {
  7219. const unsigned int sharedPropertyGuardsCount = (unsigned int)this->sharedPropertyGuards->Count();
  7220. Js::PropertyId* guards = RecyclerNewArray(this->GetScriptContext()->GetRecycler(), Js::PropertyId, sharedPropertyGuardsCount);
  7221. auto sharedGuardIter = this->sharedPropertyGuards->GetIterator();
  7222. while (sharedGuardIter.IsValid())
  7223. {
  7224. AnalysisAssert(guardCount < sharedPropertyGuardsCount);
  7225. guards[guardCount] = sharedGuardIter.CurrentKey();
  7226. sharedGuardIter.MoveNext();
  7227. ++guardCount;
  7228. }
  7229. AnalysisAssert(guardCount == sharedPropertyGuardsCount);
  7230. sharedPropertyGuards = guards;
  7231. }
  7232. count = guardCount;
  7233. return sharedPropertyGuards;
  7234. }
  7235. bool EntryPointInfo::TryGetSharedPropertyGuard(Js::PropertyId propertyId, Js::PropertyGuard*& guard)
  7236. {
  7237. return this->sharedPropertyGuards != nullptr ? this->sharedPropertyGuards->TryGetValue(propertyId, &guard) : false;
  7238. }
  7239. void EntryPointInfo::RecordTypeGuards(int typeGuardCount, TypeGuardTransferEntry* typeGuardTransferRecord, size_t typeGuardTransferPlusSize)
  7240. {
  7241. Assert(this->jitTransferData != nullptr);
  7242. this->jitTransferData->propertyGuardCount = typeGuardCount;
  7243. this->jitTransferData->propertyGuardsByPropertyId = typeGuardTransferRecord;
  7244. this->jitTransferData->propertyGuardsByPropertyIdPlusSize = typeGuardTransferPlusSize;
  7245. }
  7246. void EntryPointInfo::RecordCtorCacheGuards(CtorCacheGuardTransferEntry* ctorCacheTransferRecord, size_t ctorCacheTransferPlusSize)
  7247. {
  7248. Assert(this->jitTransferData != nullptr);
  7249. this->jitTransferData->ctorCacheGuardsByPropertyId = ctorCacheTransferRecord;
  7250. this->jitTransferData->ctorCacheGuardsByPropertyIdPlusSize = ctorCacheTransferPlusSize;
  7251. }
  7252. void EntryPointInfo::FreePropertyGuards()
  7253. {
  7254. // While typePropertyGuardWeakRefs are allocated via NativeCodeData::Allocator and will be automatically freed to the heap,
  7255. // we must zero out the fake weak references so that property guard invalidation doesn't access freed memory.
  7256. if (this->propertyGuardWeakRefs != nullptr)
  7257. {
  7258. for (int i = 0; i < this->propertyGuardCount; i++)
  7259. {
  7260. if (this->propertyGuardWeakRefs[i] != nullptr)
  7261. {
  7262. this->propertyGuardWeakRefs[i]->Zero();
  7263. }
  7264. }
  7265. this->propertyGuardCount = 0;
  7266. this->propertyGuardWeakRefs = nullptr;
  7267. }
  7268. }
  7269. void EntryPointInfo::RecordBailOutMap(JsUtil::List<LazyBailOutRecord, ArenaAllocator>* bailoutMap)
  7270. {
  7271. Assert(this->bailoutRecordMap == nullptr);
  7272. this->bailoutRecordMap = HeapNew(BailOutRecordMap, &HeapAllocator::Instance);
  7273. this->bailoutRecordMap->Copy(bailoutMap);
  7274. }
  7275. void EntryPointInfo::RecordInlineeFrameMap(JsUtil::List<NativeOffsetInlineeFramePair, ArenaAllocator>* tempInlineeFrameMap)
  7276. {
  7277. Assert(this->inlineeFrameMap == nullptr);
  7278. if (tempInlineeFrameMap->Count() > 0)
  7279. {
  7280. this->inlineeFrameMap = HeapNew(InlineeFrameMap, &HeapAllocator::Instance);
  7281. this->inlineeFrameMap->Copy(tempInlineeFrameMap);
  7282. }
  7283. }
  7284. void EntryPointInfo::RecordInlineeFrameOffsetsInfo(unsigned int offsetsArrayOffset, unsigned int offsetsArrayCount)
  7285. {
  7286. this->inlineeFrameOffsetArrayOffset = offsetsArrayOffset;
  7287. this->inlineeFrameOffsetArrayCount = offsetsArrayCount;
  7288. }
  7289. InlineeFrameRecord* EntryPointInfo::FindInlineeFrame(void* returnAddress)
  7290. {
  7291. if (this->nativeDataBuffer == nullptr) // in-proc JIT
  7292. {
  7293. if (this->inlineeFrameMap == nullptr)
  7294. {
  7295. return nullptr;
  7296. }
  7297. size_t offset = (size_t)((BYTE*)returnAddress - (BYTE*)this->GetNativeAddress());
  7298. int index = this->inlineeFrameMap->BinarySearch([=](const NativeOffsetInlineeFramePair& pair, int index) {
  7299. if (pair.offset >= offset)
  7300. {
  7301. if (index == 0 || (index > 0 && this->inlineeFrameMap->Item(index - 1).offset < offset))
  7302. {
  7303. return 0;
  7304. }
  7305. else
  7306. {
  7307. return 1;
  7308. }
  7309. }
  7310. return -1;
  7311. });
  7312. if (index == -1)
  7313. {
  7314. return nullptr;
  7315. }
  7316. return this->inlineeFrameMap->Item(index).record;
  7317. }
  7318. else // OOP JIT
  7319. {
  7320. NativeOffsetInlineeFrameRecordOffset* offsets = (NativeOffsetInlineeFrameRecordOffset*)(this->nativeDataBuffer + this->inlineeFrameOffsetArrayOffset);
  7321. size_t offset = (size_t)((BYTE*)returnAddress - (BYTE*)this->GetNativeAddress());
  7322. if (this->inlineeFrameOffsetArrayCount == 0)
  7323. {
  7324. return nullptr;
  7325. }
  7326. uint fromIndex = 0;
  7327. uint toIndex = this->inlineeFrameOffsetArrayCount - 1;
  7328. while (fromIndex <= toIndex)
  7329. {
  7330. uint midIndex = fromIndex + (toIndex - fromIndex) / 2;
  7331. auto item = offsets[midIndex];
  7332. if (item.offset >= offset)
  7333. {
  7334. if (midIndex == 0 || (midIndex > 0 && offsets[midIndex - 1].offset < offset))
  7335. {
  7336. if (offsets[midIndex].recordOffset == NativeOffsetInlineeFrameRecordOffset::InvalidRecordOffset)
  7337. {
  7338. return nullptr;
  7339. }
  7340. else
  7341. {
  7342. return (InlineeFrameRecord*)(this->nativeDataBuffer + offsets[midIndex].recordOffset);
  7343. }
  7344. }
  7345. else
  7346. {
  7347. toIndex = midIndex - 1;
  7348. }
  7349. }
  7350. else
  7351. {
  7352. fromIndex = midIndex + 1;
  7353. }
  7354. }
  7355. return nullptr;
  7356. }
  7357. }
  7358. void EntryPointInfo::DoLazyBailout(BYTE** addressOfInstructionPointer, Js::FunctionBody* functionBody, const PropertyRecord* propertyRecord)
  7359. {
  7360. BYTE* instructionPointer = *addressOfInstructionPointer;
  7361. Assert(instructionPointer > (BYTE*)this->nativeAddress && instructionPointer < ((BYTE*)this->nativeAddress + this->codeSize));
  7362. size_t offset = instructionPointer - (BYTE*)this->nativeAddress;
  7363. int found = this->bailoutRecordMap->BinarySearch([=](const LazyBailOutRecord& record, int index)
  7364. {
  7365. // find the closest entry which is greater than the current offset.
  7366. if (record.offset >= offset)
  7367. {
  7368. if (index == 0 || (index > 0 && this->bailoutRecordMap->Item(index - 1).offset < offset))
  7369. {
  7370. return 0;
  7371. }
  7372. else
  7373. {
  7374. return 1;
  7375. }
  7376. }
  7377. return -1;
  7378. });
  7379. if (found != -1)
  7380. {
  7381. LazyBailOutRecord& record = this->bailoutRecordMap->Item(found);
  7382. *addressOfInstructionPointer = record.instructionPointer;
  7383. record.SetBailOutKind();
  7384. if (PHASE_TRACE1(Js::LazyBailoutPhase))
  7385. {
  7386. Output::Print(_u("On stack lazy bailout. Property: %s Old IP: 0x%x New IP: 0x%x "), propertyRecord->GetBuffer(), instructionPointer, record.instructionPointer);
  7387. #if DBG
  7388. record.Dump(functionBody);
  7389. #endif
  7390. Output::Print(_u("\n"));
  7391. }
  7392. }
  7393. else
  7394. {
  7395. AssertMsg(false, "Lazy Bailout address mapping missing");
  7396. }
  7397. }
  7398. void EntryPointInfo::FreeJitTransferData()
  7399. {
  7400. JitTransferData* jitTransferData = this->jitTransferData;
  7401. this->jitTransferData = nullptr;
  7402. if (jitTransferData != nullptr)
  7403. {
  7404. // This dictionary is recycler allocated so it doesn't need to be explicitly freed.
  7405. jitTransferData->jitTimeTypeRefs = nullptr;
  7406. if (jitTransferData->lazyBailoutProperties != nullptr)
  7407. {
  7408. HeapDeleteArray(jitTransferData->lazyBailoutPropertyCount, jitTransferData->lazyBailoutProperties);
  7409. jitTransferData->lazyBailoutProperties = nullptr;
  7410. }
  7411. // All structures below are heap allocated and need to be freed explicitly.
  7412. if (jitTransferData->runtimeTypeRefs != nullptr)
  7413. {
  7414. if (jitTransferData->runtimeTypeRefs->isOOPJIT)
  7415. {
  7416. midl_user_free(jitTransferData->runtimeTypeRefs);
  7417. }
  7418. else
  7419. {
  7420. HeapDeletePlus(offsetof(PinnedTypeRefsIDL, typeRefs) + sizeof(void*)*jitTransferData->runtimeTypeRefs->count - sizeof(PinnedTypeRefsIDL),
  7421. PointerValue(jitTransferData->runtimeTypeRefs));
  7422. }
  7423. jitTransferData->runtimeTypeRefs = nullptr;
  7424. }
  7425. if (jitTransferData->propertyGuardsByPropertyId != nullptr)
  7426. {
  7427. HeapDeletePlus(jitTransferData->propertyGuardsByPropertyIdPlusSize, jitTransferData->propertyGuardsByPropertyId);
  7428. jitTransferData->propertyGuardsByPropertyId = nullptr;
  7429. }
  7430. jitTransferData->propertyGuardCount = 0;
  7431. jitTransferData->propertyGuardsByPropertyIdPlusSize = 0;
  7432. if (jitTransferData->ctorCacheGuardsByPropertyId != nullptr)
  7433. {
  7434. HeapDeletePlus(jitTransferData->ctorCacheGuardsByPropertyIdPlusSize, jitTransferData->ctorCacheGuardsByPropertyId);
  7435. jitTransferData->ctorCacheGuardsByPropertyId = nullptr;
  7436. }
  7437. jitTransferData->ctorCacheGuardsByPropertyIdPlusSize = 0;
  7438. if (jitTransferData->equivalentTypeGuards != nullptr)
  7439. {
  7440. HeapDeleteArray(jitTransferData->equivalentTypeGuardCount, jitTransferData->equivalentTypeGuards);
  7441. jitTransferData->equivalentTypeGuards = nullptr;
  7442. }
  7443. jitTransferData->equivalentTypeGuardCount = 0;
  7444. if (jitTransferData->jitTransferRawData != nullptr)
  7445. {
  7446. HeapDelete(jitTransferData->jitTransferRawData);
  7447. jitTransferData->jitTransferRawData = nullptr;
  7448. }
  7449. if (jitTransferData->equivalentTypeGuardOffsets)
  7450. {
  7451. midl_user_free(jitTransferData->equivalentTypeGuardOffsets);
  7452. }
  7453. if (jitTransferData->typeGuardTransferData.entries != nullptr)
  7454. {
  7455. auto next = &jitTransferData->typeGuardTransferData.entries;
  7456. while (*next)
  7457. {
  7458. auto current = (*next);
  7459. *next = (*next)->next;
  7460. midl_user_free(current);
  7461. }
  7462. }
  7463. if (jitTransferData->ctorCacheTransferData.entries != nullptr)
  7464. {
  7465. CtorCacheTransferEntryIDL ** entries = jitTransferData->ctorCacheTransferData.entries;
  7466. for (uint i = 0; i < jitTransferData->ctorCacheTransferData.ctorCachesCount; ++i)
  7467. {
  7468. midl_user_free(entries[i]);
  7469. }
  7470. midl_user_free(entries);
  7471. }
  7472. jitTransferData = nullptr;
  7473. }
  7474. }
  7475. void EntryPointInfo::RegisterEquivalentTypeCaches()
  7476. {
  7477. Assert(this->registeredEquivalentTypeCacheRef == nullptr);
  7478. this->registeredEquivalentTypeCacheRef =
  7479. GetScriptContext()->GetThreadContext()->RegisterEquivalentTypeCacheEntryPoint(this);
  7480. }
  7481. void EntryPointInfo::UnregisterEquivalentTypeCaches()
  7482. {
  7483. if (this->registeredEquivalentTypeCacheRef != nullptr)
  7484. {
  7485. ScriptContext *scriptContext = GetScriptContext();
  7486. if (scriptContext != nullptr)
  7487. {
  7488. scriptContext->GetThreadContext()->UnregisterEquivalentTypeCacheEntryPoint(
  7489. this->registeredEquivalentTypeCacheRef);
  7490. }
  7491. this->registeredEquivalentTypeCacheRef = nullptr;
  7492. }
  7493. }
  7494. bool EntryPointInfo::ClearEquivalentTypeCaches()
  7495. {
  7496. Assert(this->equivalentTypeCaches != nullptr);
  7497. Assert(this->equivalentTypeCacheCount > 0);
  7498. bool isAnyCacheLive = false;
  7499. Recycler *recycler = GetScriptContext()->GetRecycler();
  7500. for (EquivalentTypeCache *cache = this->equivalentTypeCaches;
  7501. cache < this->equivalentTypeCaches + this->equivalentTypeCacheCount;
  7502. cache++)
  7503. {
  7504. bool isCacheLive = cache->ClearUnusedTypes(recycler);
  7505. if (isCacheLive)
  7506. {
  7507. isAnyCacheLive = true;
  7508. }
  7509. }
  7510. if (!isAnyCacheLive)
  7511. {
  7512. // The caller must take care of unregistering this entry point. We may be in the middle of
  7513. // walking the list of registered entry points.
  7514. this->equivalentTypeCaches = nullptr;
  7515. this->equivalentTypeCacheCount = 0;
  7516. this->registeredEquivalentTypeCacheRef = nullptr;
  7517. }
  7518. return isAnyCacheLive;
  7519. }
  7520. bool EquivalentTypeCache::ClearUnusedTypes(Recycler *recycler)
  7521. {
  7522. bool isAnyTypeLive = false;
  7523. Assert(this->guard);
  7524. if (this->guard->IsValid())
  7525. {
  7526. Type *type = reinterpret_cast<Type*>(this->guard->GetValue());
  7527. if (!recycler->IsObjectMarked(type))
  7528. {
  7529. this->guard->InvalidateDuringSweep();
  7530. }
  7531. else
  7532. {
  7533. isAnyTypeLive = true;
  7534. }
  7535. }
  7536. uint16 nonNullIndex = 0;
  7537. #if DBG
  7538. bool isGuardValuePresent = false;
  7539. #endif
  7540. for (int i = 0; i < EQUIVALENT_TYPE_CACHE_SIZE; i++)
  7541. {
  7542. Type *type = this->types[i];
  7543. if (type != nullptr)
  7544. {
  7545. this->types[i] = nullptr;
  7546. if (recycler->IsObjectMarked(type))
  7547. {
  7548. // compact the types array by moving non-null types
  7549. // at the beginning.
  7550. this->types[nonNullIndex++] = type;
  7551. #if DBG
  7552. isGuardValuePresent = this->guard->GetValue() == reinterpret_cast<intptr_t>(type) ? true : isGuardValuePresent;
  7553. #endif
  7554. }
  7555. }
  7556. else
  7557. {
  7558. #ifdef DEBUG
  7559. for (int __i = i; __i < EQUIVALENT_TYPE_CACHE_SIZE; __i++)
  7560. { Assert(this->types[__i] == nullptr); }
  7561. #endif
  7562. break; // array must be shrinked already
  7563. }
  7564. }
  7565. if (nonNullIndex > 0)
  7566. {
  7567. isAnyTypeLive = true;
  7568. }
  7569. else
  7570. {
  7571. if (guard->IsInvalidatedDuringSweep())
  7572. {
  7573. // just mark this as actual invalidated since there are no types
  7574. // present
  7575. guard->Invalidate();
  7576. }
  7577. }
  7578. // verify if guard value is valid, it is present in one of the types
  7579. AssertMsg(!this->guard->IsValid() || isGuardValuePresent || nonNullIndex == 0,
  7580. "After ClearUnusedTypes, valid guard value should be one of the cached equivalent types.");
  7581. return isAnyTypeLive;
  7582. }
  7583. void EntryPointInfo::RegisterConstructorCache(Js::ConstructorCache* constructorCache, Recycler* recycler)
  7584. {
  7585. Assert(constructorCache != nullptr);
  7586. if (!this->constructorCaches)
  7587. {
  7588. this->constructorCaches = RecyclerNew(recycler, ConstructorCacheList, recycler);
  7589. }
  7590. this->constructorCaches->Prepend(constructorCache);
  7591. }
  7592. #endif
  7593. #if ENABLE_DEBUG_STACK_BACK_TRACE
  7594. void EntryPointInfo::CaptureCleanupStackTrace()
  7595. {
  7596. if (this->cleanupStack != nullptr)
  7597. {
  7598. this->cleanupStack->Delete(&NoCheckHeapAllocator::Instance);
  7599. this->cleanupStack = nullptr;
  7600. }
  7601. this->cleanupStack = StackBackTrace::Capture(&NoCheckHeapAllocator::Instance);
  7602. }
  7603. #endif
  7604. void EntryPointInfo::Finalize(bool isShutdown)
  7605. {
  7606. __super::Finalize(isShutdown);
  7607. if (!isShutdown)
  7608. {
  7609. ReleasePendingWorkItem();
  7610. }
  7611. #if ENABLE_DEBUG_CONFIG_OPTIONS
  7612. this->SetCleanupReason(CleanupReason::CleanUpForFinalize);
  7613. #endif
  7614. this->Cleanup(isShutdown, false);
  7615. #if ENABLE_DEBUG_STACK_BACK_TRACE
  7616. if (this->cleanupStack != nullptr)
  7617. {
  7618. this->cleanupStack->Delete(&NoCheckHeapAllocator::Instance);
  7619. this->cleanupStack = nullptr;
  7620. }
  7621. #endif
  7622. this->library = nullptr;
  7623. }
  7624. #if ENABLE_NATIVE_CODEGEN
  7625. EntryPointPolymorphicInlineCacheInfo * EntryPointInfo::EnsurePolymorphicInlineCacheInfo(Recycler * recycler, FunctionBody * functionBody)
  7626. {
  7627. if (!polymorphicInlineCacheInfo)
  7628. {
  7629. polymorphicInlineCacheInfo = RecyclerNew(recycler, EntryPointPolymorphicInlineCacheInfo, functionBody);
  7630. }
  7631. return polymorphicInlineCacheInfo;
  7632. }
  7633. #endif
  7634. void EntryPointInfo::Cleanup(bool isShutdown, bool captureCleanupStack)
  7635. {
  7636. if (this->GetState() != CleanedUp)
  7637. {
  7638. #if ENABLE_NATIVE_CODEGEN
  7639. #if PDATA_ENABLED
  7640. if (this->xdataInfo != nullptr)
  7641. {
  7642. #ifdef _WIN32
  7643. PHASE_PRINT_TESTTRACE1(Js::XDataPhase, _u("EntryPointInfo::Cleanup: Freeing: function table: %llx, codeAddress: %%llx\n"), this->xdataInfo->functionTable, this->GetNativeEntrypoint());
  7644. if (this->xdataInfo->functionTable
  7645. && !DelayDeletingFunctionTable::AddEntry(this->xdataInfo->functionTable))
  7646. {
  7647. PHASE_PRINT_TESTTRACE1(Js::XDataPhase, _u("EntryPointInfo::Cleanup: Failed to add to slist, table: %llx, address: %%llx\n"), this->xdataInfo->functionTable, this->GetNativeEntrypoint());
  7648. DelayDeletingFunctionTable::DeleteFunctionTable(this->xdataInfo->functionTable);
  7649. }
  7650. #endif
  7651. XDataAllocator::Unregister(this->xdataInfo);
  7652. #if defined(_M_ARM)
  7653. if (JITManager::GetJITManager()->IsOOPJITEnabled())
  7654. #endif
  7655. {
  7656. HeapDelete(this->xdataInfo);
  7657. }
  7658. this->xdataInfo = nullptr;
  7659. }
  7660. #endif //PDATA_ENABLED
  7661. this->OnCleanup(isShutdown);
  7662. FreeJitTransferData();
  7663. if (this->bailoutRecordMap != nullptr)
  7664. {
  7665. HeapDelete(this->bailoutRecordMap);
  7666. bailoutRecordMap = nullptr;
  7667. }
  7668. if (this->sharedPropertyGuards != nullptr)
  7669. {
  7670. sharedPropertyGuards->Clear();
  7671. sharedPropertyGuards = nullptr;
  7672. }
  7673. FreePropertyGuards();
  7674. if (this->equivalentTypeCaches != nullptr)
  7675. {
  7676. this->UnregisterEquivalentTypeCaches();
  7677. this->equivalentTypeCacheCount = 0;
  7678. this->equivalentTypeCaches = nullptr;
  7679. }
  7680. if (this->constructorCaches != nullptr)
  7681. {
  7682. this->constructorCaches->Clear();
  7683. }
  7684. #endif
  7685. // This is how we set the CleanedUp state
  7686. this->workItem = nullptr;
  7687. this->nativeAddress = nullptr;
  7688. #if ENABLE_NATIVE_CODEGEN
  7689. this->weakFuncRefSet = nullptr;
  7690. this->runtimeTypeRefs = nullptr;
  7691. #endif
  7692. this->codeSize = -1;
  7693. this->library = nullptr;
  7694. #if ENABLE_NATIVE_CODEGEN
  7695. DeleteNativeCodeData(this->inProcJITNaticeCodedata);
  7696. this->inProcJITNaticeCodedata = nullptr;
  7697. this->numberChunks = nullptr;
  7698. if (this->nativeDataBuffer)
  7699. {
  7700. NativeDataBuffer* buffer = (NativeDataBuffer*)(this->nativeDataBuffer - offsetof(NativeDataBuffer, data));
  7701. midl_user_free(buffer);
  7702. }
  7703. #endif
  7704. this->state = CleanedUp;
  7705. #if ENABLE_DEBUG_CONFIG_OPTIONS
  7706. #if !DBG
  7707. captureCleanupStack = captureCleanupStack && Js::Configuration::Global.flags.FreTestDiagMode;
  7708. #endif
  7709. #if ENABLE_DEBUG_STACK_BACK_TRACE
  7710. if (captureCleanupStack)
  7711. {
  7712. this->CaptureCleanupStackTrace();
  7713. }
  7714. #endif
  7715. #endif
  7716. #if ENABLE_NATIVE_CODEGEN
  7717. if (nullptr != this->nativeThrowSpanSequence)
  7718. {
  7719. HeapDelete(this->nativeThrowSpanSequence);
  7720. this->nativeThrowSpanSequence = nullptr;
  7721. }
  7722. this->polymorphicInlineCacheInfo = nullptr;
  7723. #endif
  7724. #if DBG_DUMP | defined(VTUNE_PROFILING)
  7725. this->nativeOffsetMaps.Reset();
  7726. #endif
  7727. #if DEBUG
  7728. const unsigned char* rpcData = serializedRpcData;
  7729. HeapDeleteArray(serializedRpcDataSize, rpcData);
  7730. serializedRpcDataSize = 0;
  7731. serializedRpcData = nullptr;
  7732. #endif
  7733. }
  7734. }
  7735. void EntryPointInfo::Reset(bool resetStateToNotScheduled)
  7736. {
  7737. Assert(this->GetState() != CleanedUp);
  7738. this->nativeAddress = nullptr;
  7739. this->workItem = nullptr;
  7740. #if ENABLE_NATIVE_CODEGEN
  7741. if (nullptr != this->nativeThrowSpanSequence)
  7742. {
  7743. HeapDelete(this->nativeThrowSpanSequence);
  7744. this->nativeThrowSpanSequence = nullptr;
  7745. }
  7746. #endif
  7747. this->codeSize = 0;
  7748. #if ENABLE_NATIVE_CODEGEN
  7749. this->weakFuncRefSet = nullptr;
  7750. this->sharedPropertyGuards = nullptr;
  7751. FreePropertyGuards();
  7752. FreeJitTransferData();
  7753. if (this->inProcJITNaticeCodedata != nullptr)
  7754. {
  7755. DeleteNativeCodeData(this->inProcJITNaticeCodedata);
  7756. this->inProcJITNaticeCodedata = nullptr;
  7757. }
  7758. #endif
  7759. // Set the state to NotScheduled only if the call to Reset is not because of JIT cap being reached
  7760. if (resetStateToNotScheduled)
  7761. {
  7762. this->state = NotScheduled;
  7763. }
  7764. }
  7765. #if ENABLE_NATIVE_CODEGEN
  7766. // This function needs review when we enable lazy bailouts-
  7767. // Is calling Reset enough? Does Reset sufficiently resets the state of the entryPointInfo?
  7768. void EntryPointInfo::ResetOnLazyBailoutFailure()
  7769. {
  7770. Assert(PHASE_ON1(Js::LazyBailoutPhase));
  7771. // Reset the entry point upon a lazy bailout.
  7772. this->Reset(true);
  7773. Assert(this->nativeAddress != nullptr);
  7774. #if PDATA_ENABLED && defined(_WIN32)
  7775. if (this->xdataInfo)
  7776. {
  7777. if (this->xdataInfo->functionTable
  7778. && !DelayDeletingFunctionTable::AddEntry(this->xdataInfo->functionTable))
  7779. {
  7780. PHASE_PRINT_TESTTRACE1(Js::XDataPhase, _u("EntryPointInfo::ResetOnLazyBailoutFailure: Failed to add to slist, table: %llx, address: %llx\n"), this->xdataInfo->functionTable, this->nativeAddress);
  7781. DelayDeletingFunctionTable::DeleteFunctionTable(this->xdataInfo->functionTable);
  7782. }
  7783. }
  7784. #endif
  7785. FreeNativeCodeGenAllocation(GetScriptContext(), this->nativeAddress, this->thunkAddress);
  7786. this->nativeAddress = nullptr;
  7787. this->jsMethod = nullptr;
  7788. }
  7789. #endif
  7790. #ifdef PERF_COUNTERS
  7791. void FunctionEntryPointInfo::OnRecorded()
  7792. {
  7793. PERF_COUNTER_ADD(Code, TotalNativeCodeSize, GetCodeSize());
  7794. PERF_COUNTER_ADD(Code, FunctionNativeCodeSize, GetCodeSize());
  7795. PERF_COUNTER_ADD(Code, DynamicNativeCodeSize, GetCodeSize());
  7796. }
  7797. #endif
  7798. FunctionEntryPointInfo::FunctionEntryPointInfo(FunctionProxy * functionProxy, Js::JavascriptMethod method, ThreadContext* context, void* cookie) :
  7799. EntryPointInfo(method, functionProxy->GetScriptContext()->GetLibrary(), cookie, context),
  7800. localVarSlotsOffset(Js::Constants::InvalidOffset),
  7801. localVarChangedOffset(Js::Constants::InvalidOffset),
  7802. callsCount(0),
  7803. jitMode(ExecutionMode::Interpreter),
  7804. functionProxy(functionProxy),
  7805. nextEntryPoint(nullptr),
  7806. mIsTemplatizedJitMode(false)
  7807. {
  7808. }
  7809. #ifdef ASMJS_PLAT
  7810. void FunctionEntryPointInfo::SetIsTJMode(bool value)
  7811. {
  7812. Assert(this->GetIsAsmJSFunction());
  7813. mIsTemplatizedJitMode = value;
  7814. }
  7815. bool FunctionEntryPointInfo::GetIsTJMode()const
  7816. {
  7817. return mIsTemplatizedJitMode;
  7818. };
  7819. #endif
  7820. //End AsmJS Support
  7821. #if ENABLE_NATIVE_CODEGEN
  7822. ExecutionMode FunctionEntryPointInfo::GetJitMode() const
  7823. {
  7824. return jitMode;
  7825. }
  7826. void FunctionEntryPointInfo::SetJitMode(const ExecutionMode jitMode)
  7827. {
  7828. Assert(jitMode == ExecutionMode::SimpleJit || jitMode == ExecutionMode::FullJit);
  7829. this->jitMode = jitMode;
  7830. }
  7831. #endif
  7832. bool FunctionEntryPointInfo::ExecutedSinceCallCountCollection() const
  7833. {
  7834. return this->callsCount != this->lastCallsCount;
  7835. }
  7836. void FunctionEntryPointInfo::CollectCallCounts()
  7837. {
  7838. this->lastCallsCount = this->callsCount;
  7839. }
  7840. void FunctionEntryPointInfo::ReleasePendingWorkItem()
  7841. {
  7842. // Do this outside of Cleanup since cleanup can be called from the background thread
  7843. // We remove any work items corresponding to the function body being reclaimed
  7844. // so that the background thread doesn't try to use them. ScriptContext != null => this
  7845. // is a function entry point
  7846. // In general this is not needed for loop bodies since loop bodies aren't in the low priority
  7847. // queue, they should be jitted before the entry point is finalized
  7848. if (!this->IsNotScheduled() && !this->IsCleanedUp())
  7849. {
  7850. #if defined(_M_ARM32_OR_ARM64)
  7851. // On ARM machines, order of writes is not guaranteed while reading data from another processor
  7852. // So we need to have a memory barrier here in order to make sure that the work item is consistent
  7853. MemoryBarrier();
  7854. #endif
  7855. CodeGenWorkItem* workItem = this->GetWorkItem();
  7856. if (workItem != nullptr)
  7857. {
  7858. Assert(this->library != nullptr);
  7859. #if ENABLE_NATIVE_CODEGEN
  7860. TryReleaseNonHiPriWorkItem(this->library->GetScriptContext(), workItem);
  7861. #endif
  7862. }
  7863. }
  7864. }
  7865. FunctionBody *FunctionEntryPointInfo::GetFunctionBody() const
  7866. {
  7867. return functionProxy->GetFunctionBody();
  7868. }
  7869. void FunctionEntryPointInfo::OnCleanup(bool isShutdown)
  7870. {
  7871. if (this->IsCodeGenDone())
  7872. {
  7873. Assert(this->functionProxy->GetFunctionInfo()->HasBody());
  7874. #if ENABLE_NATIVE_CODEGEN
  7875. if (nullptr != this->inlineeFrameMap)
  7876. {
  7877. HeapDelete(this->inlineeFrameMap);
  7878. this->inlineeFrameMap = nullptr;
  7879. }
  7880. #endif
  7881. if(nativeEntryPointProcessed)
  7882. {
  7883. JS_ETW(EtwTrace::LogMethodNativeUnloadEvent(this->functionProxy->GetFunctionBody(), this));
  7884. }
  7885. FunctionBody* functionBody = this->functionProxy->GetFunctionBody();
  7886. #ifdef ASMJS_PLAT
  7887. if (this->GetIsTJMode())
  7888. {
  7889. // release LoopHeaders here if the entrypointInfo is TJ
  7890. this->GetFunctionBody()->ReleaseLoopHeaders();
  7891. }
  7892. #endif
  7893. if(functionBody->GetSimpleJitEntryPointInfo() == this)
  7894. {
  7895. functionBody->SetSimpleJitEntryPointInfo(nullptr);
  7896. }
  7897. // If we're shutting down, the script context might be gone
  7898. if (!isShutdown)
  7899. {
  7900. ScriptContext* scriptContext = this->functionProxy->GetScriptContext();
  7901. void* currentCookie = nullptr;
  7902. #if ENABLE_NATIVE_CODEGEN
  7903. // In the debugger case, we might call cleanup after the native code gen that
  7904. // allocated this entry point has already shutdown. In that case, the validation
  7905. // check below should fail and we should not try to free this entry point
  7906. // since it's already been freed
  7907. NativeCodeGenerator* currentNativeCodegen = scriptContext->GetNativeCodeGenerator();
  7908. Assert(this->validationCookie != nullptr);
  7909. currentCookie = (void*)currentNativeCodegen;
  7910. #endif
  7911. if (this->jsMethod == this->GetNativeEntrypoint())
  7912. {
  7913. #if DBG
  7914. // tag the jsMethod in case the native address is reused in recycler and create a false positive
  7915. // not checking validationCookie because this can happen while debugger attaching, native address
  7916. // are batch freed through deleting NativeCodeGenerator
  7917. this->jsMethod = (Js::JavascriptMethod)((intptr_t)this->jsMethod | 1);
  7918. #else
  7919. this->jsMethod = nullptr;
  7920. #endif
  7921. }
  7922. if (validationCookie == currentCookie)
  7923. {
  7924. scriptContext->FreeFunctionEntryPoint((Js::JavascriptMethod)this->GetNativeAddress(), this->GetThunkAddress());
  7925. }
  7926. #if PDATA_ENABLED && defined(_WIN32)
  7927. else
  7928. {
  7929. // in case of debugger attaching, we have a new code generator and when deleting old code generator,
  7930. // the xData is not put in the delay list yet. clear the list now so the code addresses are ready to reuse
  7931. DelayDeletingFunctionTable::Clear();
  7932. }
  7933. #endif
  7934. }
  7935. #ifdef PERF_COUNTERS
  7936. PERF_COUNTER_SUB(Code, TotalNativeCodeSize, GetCodeSize());
  7937. PERF_COUNTER_SUB(Code, FunctionNativeCodeSize, GetCodeSize());
  7938. PERF_COUNTER_SUB(Code, DynamicNativeCodeSize, GetCodeSize());
  7939. #endif
  7940. }
  7941. this->functionProxy = nullptr;
  7942. }
  7943. #if ENABLE_NATIVE_CODEGEN
  7944. void FunctionEntryPointInfo::ResetOnNativeCodeInstallFailure()
  7945. {
  7946. this->functionProxy->MapFunctionObjectTypes([&](ScriptFunctionType* functionType)
  7947. {
  7948. Assert(functionType->GetTypeId() == TypeIds_Function);
  7949. if (functionType->GetEntryPointInfo() == this)
  7950. {
  7951. if (!this->GetIsAsmJSFunction())
  7952. {
  7953. functionType->SetEntryPoint(GetCheckCodeGenThunk());
  7954. }
  7955. #ifdef ASMJS_PLAT
  7956. else
  7957. {
  7958. functionType->SetEntryPoint(GetCheckAsmJsCodeGenThunk());
  7959. }
  7960. #endif
  7961. }
  7962. });
  7963. }
  7964. void FunctionEntryPointInfo::EnterExpirableCollectMode()
  7965. {
  7966. this->lastCallsCount = this->callsCount;
  7967. // For code that is not jitted yet we don't want to expire since there is nothing to free here
  7968. if (this->IsCodeGenPending())
  7969. {
  7970. this->SetIsObjectUsed();
  7971. }
  7972. }
  7973. void FunctionEntryPointInfo::Invalidate(bool prolongEntryPoint)
  7974. {
  7975. Assert(!this->functionProxy->IsDeferred());
  7976. FunctionBody* functionBody = this->functionProxy->GetFunctionBody();
  7977. Assert(this != functionBody->GetSimpleJitEntryPointInfo());
  7978. // We may have got here following OOM in ProcessJitTransferData. Free any data we have
  7979. // to reduce the chance of another OOM below.
  7980. this->FreeJitTransferData();
  7981. FunctionEntryPointInfo* entryPoint = functionBody->GetDefaultFunctionEntryPointInfo();
  7982. if (entryPoint->IsCodeGenPending())
  7983. {
  7984. OUTPUT_TRACE(Js::LazyBailoutPhase, _u("Skipping creating new entrypoint as one is already pending\n"));
  7985. }
  7986. else
  7987. {
  7988. class AutoCleanup
  7989. {
  7990. EntryPointInfo *entryPointInfo;
  7991. public:
  7992. AutoCleanup(EntryPointInfo *entryPointInfo) : entryPointInfo(entryPointInfo)
  7993. {
  7994. }
  7995. void Done()
  7996. {
  7997. entryPointInfo = nullptr;
  7998. }
  7999. ~AutoCleanup()
  8000. {
  8001. if (entryPointInfo)
  8002. {
  8003. entryPointInfo->ResetOnLazyBailoutFailure();
  8004. }
  8005. }
  8006. } autoCleanup(this);
  8007. entryPoint = functionBody->CreateNewDefaultEntryPoint();
  8008. GenerateFunction(functionBody->GetScriptContext()->GetNativeCodeGenerator(), functionBody, /*function*/ nullptr);
  8009. autoCleanup.Done();
  8010. }
  8011. this->functionProxy->MapFunctionObjectTypes([&](ScriptFunctionType* functionType)
  8012. {
  8013. Assert(functionType->GetTypeId() == TypeIds_Function);
  8014. if (functionType->GetEntryPointInfo() == this)
  8015. {
  8016. functionType->SetEntryPointInfo(entryPoint);
  8017. functionType->SetEntryPoint(this->functionProxy->GetDirectEntryPoint(entryPoint));
  8018. }
  8019. });
  8020. if (!prolongEntryPoint)
  8021. {
  8022. ThreadContext* threadContext = this->functionProxy->GetScriptContext()->GetThreadContext();
  8023. threadContext->QueueFreeOldEntryPointInfoIfInScript(this);
  8024. }
  8025. }
  8026. void FunctionEntryPointInfo::Expire()
  8027. {
  8028. if (this->lastCallsCount != this->callsCount || !this->nativeEntryPointProcessed || this->IsCleanedUp())
  8029. {
  8030. return;
  8031. }
  8032. ThreadContext* threadContext = this->functionProxy->GetScriptContext()->GetThreadContext();
  8033. Assert(!this->functionProxy->IsDeferred());
  8034. FunctionBody* functionBody = this->functionProxy->GetFunctionBody();
  8035. FunctionEntryPointInfo *simpleJitEntryPointInfo = functionBody->GetSimpleJitEntryPointInfo();
  8036. const bool expiringSimpleJitEntryPointInfo = simpleJitEntryPointInfo == this;
  8037. if(expiringSimpleJitEntryPointInfo)
  8038. {
  8039. if(functionBody->GetExecutionMode() != ExecutionMode::FullJit)
  8040. {
  8041. // Don't expire simple JIT code until the transition to full JIT
  8042. return;
  8043. }
  8044. simpleJitEntryPointInfo = nullptr;
  8045. functionBody->SetSimpleJitEntryPointInfo(nullptr);
  8046. }
  8047. try
  8048. {
  8049. AUTO_NESTED_HANDLED_EXCEPTION_TYPE(ExceptionType_OutOfMemory);
  8050. FunctionEntryPointInfo* newEntryPoint = nullptr;
  8051. FunctionEntryPointInfo *const defaultEntryPointInfo = functionBody->GetDefaultFunctionEntryPointInfo();
  8052. if(this == defaultEntryPointInfo)
  8053. {
  8054. if(simpleJitEntryPointInfo)
  8055. {
  8056. newEntryPoint = simpleJitEntryPointInfo;
  8057. functionBody->SetDefaultFunctionEntryPointInfo(simpleJitEntryPointInfo, newEntryPoint->GetNativeEntrypoint());
  8058. functionBody->ResetSimpleJitLimitAndCallCount();
  8059. }
  8060. #ifdef ASMJS_PLAT
  8061. else if (functionBody->GetIsAsmJsFunction())
  8062. {
  8063. // the new entrypoint will be set to interpreter
  8064. newEntryPoint = functionBody->CreateNewDefaultEntryPoint();
  8065. newEntryPoint->SetIsAsmJSFunction(true);
  8066. newEntryPoint->jsMethod = AsmJsDefaultEntryThunk;
  8067. functionBody->SetIsAsmJsFullJitScheduled(false);
  8068. functionBody->SetDefaultInterpreterExecutionMode();
  8069. this->functionProxy->SetOriginalEntryPoint(AsmJsDefaultEntryThunk);
  8070. }
  8071. #endif
  8072. else
  8073. {
  8074. newEntryPoint = functionBody->CreateNewDefaultEntryPoint();
  8075. functionBody->ReinitializeExecutionModeAndLimits();
  8076. #if ENABLE_NATIVE_CODEGEN
  8077. // In order for the function to ever get JIT again, we need to call GenerateFunction now
  8078. if (!PHASE_OFF(Js::BackEndPhase, functionBody) && !functionBody->GetScriptContext()->GetConfig()->IsNoNative())
  8079. {
  8080. GenerateFunction(functionBody->GetScriptContext()->GetNativeCodeGenerator(), functionBody);
  8081. }
  8082. #endif
  8083. }
  8084. functionBody->TraceExecutionMode("JitCodeExpired");
  8085. }
  8086. else
  8087. {
  8088. newEntryPoint = defaultEntryPointInfo;
  8089. }
  8090. OUTPUT_TRACE(Js::ExpirableCollectPhase, _u("Expiring 0x%p\n"), this);
  8091. this->functionProxy->MapFunctionObjectTypes([&] (ScriptFunctionType* functionType)
  8092. {
  8093. Assert(functionType->GetTypeId() == TypeIds_Function);
  8094. if (functionType->GetEntryPointInfo() == this)
  8095. {
  8096. OUTPUT_TRACE(Js::ExpirableCollectPhase, _u("Type 0x%p uses this entry point- switching to default entry point\n"), this);
  8097. functionType->SetEntryPointInfo(newEntryPoint);
  8098. // we are allowed to replace the entry point on the type only if it's
  8099. // directly using the jitted code or a type is referencing this entry point
  8100. // but the entry point hasn't been called since the codegen thunk was installed on it
  8101. if (functionType->GetEntryPoint() == functionProxy->GetDirectEntryPoint(this) || IsIntermediateCodeGenThunk(functionType->GetEntryPoint()))
  8102. {
  8103. functionType->SetEntryPoint(this->functionProxy->GetDirectEntryPoint(newEntryPoint));
  8104. }
  8105. }
  8106. else
  8107. {
  8108. Assert(!functionType->GetEntryPointInfo()->IsFunctionEntryPointInfo() ||
  8109. ((FunctionEntryPointInfo*)functionType->GetEntryPointInfo())->IsCleanedUp()
  8110. || functionType->GetEntryPoint() != this->GetNativeEntrypoint());
  8111. }
  8112. });
  8113. if(expiringSimpleJitEntryPointInfo)
  8114. {
  8115. // We could have just created a new entry point info that is using the simple JIT code. An allocation may have
  8116. // triggered shortly after, resulting in expiring the simple JIT entry point info. Update any entry point infos
  8117. // that are using the simple JIT code, and update the original entry point as necessary as well.
  8118. const JavascriptMethod newOriginalEntryPoint =
  8119. functionBody->GetDynamicInterpreterEntryPoint()
  8120. ? reinterpret_cast<JavascriptMethod>(
  8121. InterpreterThunkEmitter::ConvertToEntryPoint(functionBody->GetDynamicInterpreterEntryPoint()))
  8122. : DefaultEntryThunk;
  8123. const JavascriptMethod currentThunk = functionBody->GetScriptContext()->CurrentThunk;
  8124. const JavascriptMethod newDirectEntryPoint =
  8125. currentThunk == DefaultEntryThunk ? newOriginalEntryPoint : currentThunk;
  8126. const JavascriptMethod simpleJitNativeAddress = GetNativeEntrypoint();
  8127. functionBody->MapEntryPoints([&](const int entryPointIndex, FunctionEntryPointInfo *const entryPointInfo)
  8128. {
  8129. if(entryPointInfo != this && entryPointInfo->jsMethod == simpleJitNativeAddress)
  8130. {
  8131. entryPointInfo->jsMethod = newDirectEntryPoint;
  8132. }
  8133. });
  8134. if(functionBody->GetOriginalEntryPoint_Unchecked() == simpleJitNativeAddress)
  8135. {
  8136. functionBody->SetOriginalEntryPoint(newOriginalEntryPoint);
  8137. functionBody->VerifyOriginalEntryPoint();
  8138. }
  8139. }
  8140. threadContext->QueueFreeOldEntryPointInfoIfInScript(this);
  8141. }
  8142. catch (Js::OutOfMemoryException)
  8143. {
  8144. // If we can't allocate a new entry point, skip expiring this object
  8145. if(expiringSimpleJitEntryPointInfo)
  8146. {
  8147. simpleJitEntryPointInfo = this;
  8148. functionBody->SetSimpleJitEntryPointInfo(this);
  8149. }
  8150. }
  8151. }
  8152. #endif
  8153. #ifdef PERF_COUNTERS
  8154. void LoopEntryPointInfo::OnRecorded()
  8155. {
  8156. PERF_COUNTER_ADD(Code, TotalNativeCodeSize, GetCodeSize());
  8157. PERF_COUNTER_ADD(Code, LoopNativeCodeSize, GetCodeSize());
  8158. PERF_COUNTER_ADD(Code, DynamicNativeCodeSize, GetCodeSize());
  8159. }
  8160. #endif
  8161. FunctionBody *LoopEntryPointInfo::GetFunctionBody() const
  8162. {
  8163. return loopHeader->functionBody;
  8164. }
  8165. //End AsmJs Support
  8166. void LoopEntryPointInfo::OnCleanup(bool isShutdown)
  8167. {
  8168. #ifdef ASMJS_PLAT
  8169. if (this->IsCodeGenDone() && !this->GetIsTJMode())
  8170. #else
  8171. if (this->IsCodeGenDone())
  8172. #endif
  8173. {
  8174. JS_ETW(EtwTrace::LogLoopBodyUnloadEvent(this->loopHeader->functionBody, this,
  8175. this->loopHeader->functionBody->GetLoopNumber(this->loopHeader)));
  8176. #if ENABLE_NATIVE_CODEGEN
  8177. if (nullptr != this->inlineeFrameMap)
  8178. {
  8179. HeapDelete(this->inlineeFrameMap);
  8180. this->inlineeFrameMap = nullptr;
  8181. }
  8182. #endif
  8183. if (!isShutdown)
  8184. {
  8185. void* currentCookie = nullptr;
  8186. ScriptContext* scriptContext = this->loopHeader->functionBody->GetScriptContext();
  8187. #if ENABLE_NATIVE_CODEGEN
  8188. // In the debugger case, we might call cleanup after the native code gen that
  8189. // allocated this entry point has already shutdown. In that case, the validation
  8190. // check below should fail and we should not try to free this entry point
  8191. // since it's already been freed
  8192. NativeCodeGenerator* currentNativeCodegen = scriptContext->GetNativeCodeGenerator();
  8193. Assert(this->validationCookie != nullptr);
  8194. currentCookie = (void*)currentNativeCodegen;
  8195. #endif
  8196. if (this->jsMethod == this->GetNativeEntrypoint())
  8197. {
  8198. #if DBG
  8199. // tag the jsMethod in case the native address is reused in recycler and create a false positive
  8200. // not checking validationCookie because this can happen while debugger attaching, native address
  8201. // are batch freed through deleting NativeCodeGenerator
  8202. this->jsMethod = (Js::JavascriptMethod)((intptr_t)this->jsMethod | 1);
  8203. #else
  8204. this->jsMethod = nullptr;
  8205. #endif
  8206. }
  8207. if (validationCookie == currentCookie)
  8208. {
  8209. scriptContext->FreeFunctionEntryPoint(reinterpret_cast<Js::JavascriptMethod>(this->GetNativeAddress()), this->GetThunkAddress());
  8210. }
  8211. }
  8212. #ifdef PERF_COUNTERS
  8213. PERF_COUNTER_SUB(Code, TotalNativeCodeSize, GetCodeSize());
  8214. PERF_COUNTER_SUB(Code, LoopNativeCodeSize, GetCodeSize());
  8215. PERF_COUNTER_SUB(Code, DynamicNativeCodeSize, GetCodeSize());
  8216. #endif
  8217. }
  8218. }
  8219. #if ENABLE_NATIVE_CODEGEN
  8220. void LoopEntryPointInfo::ResetOnNativeCodeInstallFailure()
  8221. {
  8222. // Since we call the address on the entryPointInfo for loop bodies, all we need to do is to roll back
  8223. // the fields on the entryPointInfo related to transferring data from jit thread to main thread (already
  8224. // being done in EntryPointInfo::OnNativeCodeInstallFailure). On the next loop iteration, the interpreter
  8225. // will call EntryPointInfo::EnsureIsReadyToCall and we'll try to process jit transfer data again.
  8226. }
  8227. #endif
  8228. void LoopHeader::Init( FunctionBody * functionBody )
  8229. {
  8230. // DisableJIT-TODO: Should this entire class be ifdefed out?
  8231. #if ENABLE_NATIVE_CODEGEN
  8232. this->functionBody = functionBody;
  8233. Recycler* recycler = functionBody->GetScriptContext()->GetRecycler();
  8234. // Sync entryPoints changes to etw rundown lock
  8235. auto syncObj = functionBody->GetScriptContext()->GetThreadContext()->GetFunctionBodyLock();
  8236. this->entryPoints = RecyclerNew(recycler, LoopEntryPointList, recycler, syncObj);
  8237. this->CreateEntryPoint();
  8238. #endif
  8239. }
  8240. #if ENABLE_NATIVE_CODEGEN
  8241. int LoopHeader::CreateEntryPoint()
  8242. {
  8243. ScriptContext* scriptContext = this->functionBody->GetScriptContext();
  8244. Recycler* recycler = scriptContext->GetRecycler();
  8245. LoopEntryPointInfo* entryPoint = RecyclerNew(recycler, LoopEntryPointInfo, this, scriptContext->GetLibrary(), scriptContext->GetNativeCodeGenerator());
  8246. return this->entryPoints->Add(entryPoint);
  8247. }
  8248. void LoopHeader::ReleaseEntryPoints()
  8249. {
  8250. for (int iEntryPoint = 0; iEntryPoint < this->entryPoints->Count(); iEntryPoint++)
  8251. {
  8252. LoopEntryPointInfo * entryPoint = this->entryPoints->Item(iEntryPoint);
  8253. if (entryPoint != nullptr && entryPoint->IsCodeGenDone())
  8254. {
  8255. // ReleaseEntryPoints is not called during recycler shutdown scenarios
  8256. // We also don't capture the cleanup stack since we've not seen cleanup bugs affect
  8257. // loop entry points so far. We can pass true here if this is no longer the case.
  8258. entryPoint->Cleanup(false /* isShutdown */, false /* capture cleanup stack */);
  8259. this->entryPoints->Item(iEntryPoint, nullptr);
  8260. }
  8261. }
  8262. }
  8263. #endif
  8264. #if ENABLE_DEBUG_CONFIG_OPTIONS
  8265. void FunctionBody::DumpRegStats(FunctionBody *funcBody)
  8266. {
  8267. if (funcBody->callCountStats == 0)
  8268. {
  8269. return;
  8270. }
  8271. uint loads = funcBody->regAllocLoadCount;
  8272. uint stores = funcBody->regAllocStoreCount;
  8273. if (Js::Configuration::Global.flags.NormalizeStats)
  8274. {
  8275. loads /= this->callCountStats;
  8276. stores /= this->callCountStats;
  8277. }
  8278. funcBody->DumpFullFunctionName();
  8279. Output::SkipToColumn(55);
  8280. Output::Print(_u("Calls:%6d Loads:%9d Stores:%9d Total refs:%9d\n"), this->callCountStats,
  8281. loads, stores, loads + stores);
  8282. }
  8283. #endif
  8284. Js::RegSlot FunctionBody::GetRestParamRegSlot()
  8285. {
  8286. Js::RegSlot dstRegSlot = GetConstantCount();
  8287. if (GetHasImplicitArgIns())
  8288. {
  8289. dstRegSlot += GetInParamsCount() - 1;
  8290. }
  8291. return dstRegSlot;
  8292. }
  8293. uint FunctionBody::GetNumberOfRecursiveCallSites()
  8294. {
  8295. uint recursiveInlineSpan = 0;
  8296. uint recursiveCallSiteInlineInfo = 0;
  8297. #if ENABLE_PROFILE_INFO
  8298. if (this->HasDynamicProfileInfo())
  8299. {
  8300. recursiveCallSiteInlineInfo = this->dynamicProfileInfo->GetRecursiveInlineInfo();
  8301. }
  8302. #endif
  8303. while (recursiveCallSiteInlineInfo)
  8304. {
  8305. recursiveInlineSpan += (recursiveCallSiteInlineInfo & 1);
  8306. recursiveCallSiteInlineInfo >>= 1;
  8307. }
  8308. return recursiveInlineSpan;
  8309. }
  8310. bool FunctionBody::CanInlineRecursively(uint depth, bool tryAggressive)
  8311. {
  8312. uint recursiveInlineSpan = this->GetNumberOfRecursiveCallSites();
  8313. uint minRecursiveInlineDepth = (uint)CONFIG_FLAG(RecursiveInlineDepthMin);
  8314. if (recursiveInlineSpan != this->GetProfiledCallSiteCount() || tryAggressive == false)
  8315. {
  8316. return depth < minRecursiveInlineDepth;
  8317. }
  8318. uint maxRecursiveInlineDepth = (uint)CONFIG_FLAG(RecursiveInlineDepthMax);
  8319. uint maxRecursiveBytecodeBudget = (uint)CONFIG_FLAG(RecursiveInlineThreshold);
  8320. uint numberOfAllowedFuncs = maxRecursiveBytecodeBudget / this->GetByteCodeWithoutLDACount();
  8321. uint maxDepth;
  8322. if (recursiveInlineSpan == 1)
  8323. {
  8324. maxDepth = numberOfAllowedFuncs;
  8325. }
  8326. else
  8327. {
  8328. maxDepth = (uint)ceil(log((double)((double)numberOfAllowedFuncs) / log((double)recursiveInlineSpan)));
  8329. }
  8330. maxDepth = maxDepth < minRecursiveInlineDepth ? minRecursiveInlineDepth : maxDepth;
  8331. maxDepth = maxDepth < maxRecursiveInlineDepth ? maxDepth : maxRecursiveInlineDepth;
  8332. return depth < maxDepth;
  8333. }
  8334. static const char16 LoopWStr[] = _u("Loop");
  8335. size_t FunctionBody::GetLoopBodyName(uint loopNumber, _Out_writes_opt_z_(sizeInChars) WCHAR* displayName, _In_ size_t sizeInChars)
  8336. {
  8337. const char16* functionName = this->GetExternalDisplayName();
  8338. size_t length = wcslen(functionName) + /*length of largest int32*/ 10 + _countof(LoopWStr) + /*null*/ 1;
  8339. if (sizeInChars < length || displayName == nullptr)
  8340. {
  8341. return length;
  8342. }
  8343. int charsWritten = swprintf_s(displayName, length, _u("%s%s%u"), functionName, LoopWStr, loopNumber + 1);
  8344. Assert(charsWritten != -1);
  8345. return charsWritten + /*nullptr*/ 1;
  8346. }
  8347. void FunctionBody::MapAndSetEnvRegister(RegSlot reg)
  8348. {
  8349. Assert(!m_hasEnvRegister);
  8350. SetEnvRegister(this->MapRegSlot(reg));
  8351. }
  8352. void FunctionBody::SetEnvRegister(RegSlot reg)
  8353. {
  8354. if (reg == Constants::NoRegister)
  8355. {
  8356. m_hasEnvRegister = false;
  8357. }
  8358. else
  8359. {
  8360. m_hasEnvRegister = true;
  8361. SetCountField(CounterFields::EnvRegister, reg);
  8362. }
  8363. }
  8364. RegSlot FunctionBody::GetEnvRegister() const
  8365. {
  8366. return m_hasEnvRegister ? GetCountField(CounterFields::EnvRegister) : Constants::NoRegister;
  8367. }
  8368. void FunctionBody::MapAndSetThisRegisterForEventHandler(RegSlot reg)
  8369. {
  8370. Assert(!m_hasThisRegisterForEventHandler);
  8371. SetThisRegisterForEventHandler(this->MapRegSlot(reg));
  8372. }
  8373. void FunctionBody::SetThisRegisterForEventHandler(RegSlot reg)
  8374. {
  8375. if (reg == Constants::NoRegister)
  8376. {
  8377. m_hasThisRegisterForEventHandler = false;
  8378. }
  8379. else
  8380. {
  8381. m_hasThisRegisterForEventHandler = true;
  8382. SetCountField(CounterFields::ThisRegisterForEventHandler, reg);
  8383. }
  8384. }
  8385. RegSlot FunctionBody::GetThisRegisterForEventHandler() const
  8386. {
  8387. return m_hasThisRegisterForEventHandler ? GetCountField(CounterFields::ThisRegisterForEventHandler) : Constants::NoRegister;
  8388. }
  8389. void FunctionBody::SetLocalClosureRegister(RegSlot reg)
  8390. {
  8391. if (reg == Constants::NoRegister)
  8392. {
  8393. m_hasLocalClosureRegister = false;
  8394. }
  8395. else
  8396. {
  8397. m_hasLocalClosureRegister = true;
  8398. SetCountField(CounterFields::LocalClosureRegister, reg);
  8399. }
  8400. }
  8401. void FunctionBody::MapAndSetLocalClosureRegister(RegSlot reg)
  8402. {
  8403. Assert(!m_hasLocalClosureRegister);
  8404. SetLocalClosureRegister(this->MapRegSlot(reg));
  8405. }
  8406. RegSlot FunctionBody::GetLocalClosureRegister() const
  8407. {
  8408. return m_hasLocalClosureRegister ? GetCountField(CounterFields::LocalClosureRegister) : Constants::NoRegister;
  8409. }
  8410. void FunctionBody::SetParamClosureRegister(RegSlot reg)
  8411. {
  8412. if (reg == Constants::NoRegister)
  8413. {
  8414. m_hasParamClosureRegister = false;
  8415. }
  8416. else
  8417. {
  8418. m_hasParamClosureRegister = true;
  8419. SetCountField(CounterFields::ParamClosureRegister, reg);
  8420. }
  8421. }
  8422. void FunctionBody::MapAndSetParamClosureRegister(RegSlot reg)
  8423. {
  8424. Assert(!m_hasParamClosureRegister);
  8425. SetParamClosureRegister(this->MapRegSlot(reg));
  8426. }
  8427. RegSlot FunctionBody::GetParamClosureRegister() const
  8428. {
  8429. return m_hasParamClosureRegister ? GetCountField(CounterFields::ParamClosureRegister) : Constants::NoRegister;
  8430. }
  8431. void FunctionBody::MapAndSetLocalFrameDisplayRegister(RegSlot reg)
  8432. {
  8433. Assert(!m_hasLocalFrameDisplayRegister);
  8434. SetLocalFrameDisplayRegister(this->MapRegSlot(reg));
  8435. }
  8436. void FunctionBody::SetLocalFrameDisplayRegister(RegSlot reg)
  8437. {
  8438. if (reg == Constants::NoRegister)
  8439. {
  8440. m_hasLocalFrameDisplayRegister = false;
  8441. }
  8442. else
  8443. {
  8444. m_hasLocalFrameDisplayRegister = true;
  8445. SetCountField(CounterFields::LocalFrameDisplayRegister, reg);
  8446. }
  8447. }
  8448. RegSlot FunctionBody::GetLocalFrameDisplayRegister() const
  8449. {
  8450. return m_hasLocalFrameDisplayRegister ? GetCountField(CounterFields::LocalFrameDisplayRegister) : Constants::NoRegister;
  8451. }
  8452. void FunctionBody::MapAndSetFirstInnerScopeRegister(RegSlot reg)
  8453. {
  8454. Assert(!m_hasFirstInnerScopeRegister);
  8455. SetFirstInnerScopeRegister(this->MapRegSlot(reg));
  8456. }
  8457. void FunctionBody::SetFirstInnerScopeRegister(RegSlot reg)
  8458. {
  8459. if (reg == Constants::NoRegister)
  8460. {
  8461. m_hasFirstInnerScopeRegister = false;
  8462. }
  8463. else
  8464. {
  8465. m_hasFirstInnerScopeRegister = true;
  8466. SetCountField(CounterFields::FirstInnerScopeRegister, reg);
  8467. }
  8468. }
  8469. RegSlot FunctionBody::GetFirstInnerScopeRegister() const
  8470. {
  8471. return m_hasFirstInnerScopeRegister ? GetCountField(CounterFields::FirstInnerScopeRegister) : Constants::NoRegister;
  8472. }
  8473. void FunctionBody::MapAndSetFuncExprScopeRegister(RegSlot reg)
  8474. {
  8475. Assert(!m_hasFuncExprScopeRegister);
  8476. SetFuncExprScopeRegister(this->MapRegSlot(reg));
  8477. }
  8478. void FunctionBody::SetFuncExprScopeRegister(RegSlot reg)
  8479. {
  8480. if (reg == Constants::NoRegister)
  8481. {
  8482. m_hasFuncExprScopeRegister = false;
  8483. }
  8484. else
  8485. {
  8486. m_hasFuncExprScopeRegister = true;
  8487. SetCountField(CounterFields::FuncExprScopeRegister, reg);
  8488. }
  8489. }
  8490. RegSlot FunctionBody::GetFuncExprScopeRegister() const
  8491. {
  8492. return m_hasFuncExprScopeRegister ? GetCountField(CounterFields::FuncExprScopeRegister) : Constants::NoRegister;
  8493. }
  8494. void FunctionBody::SetFirstTmpRegister(RegSlot reg)
  8495. {
  8496. if (reg == Constants::NoRegister)
  8497. {
  8498. m_hasFirstTmpRegister = false;
  8499. }
  8500. else
  8501. {
  8502. m_hasFirstTmpRegister = true;
  8503. SetCountField(CounterFields::FirstTmpRegister, reg);
  8504. }
  8505. }
  8506. RegSlot FunctionBody::GetFirstTmpRegister() const
  8507. {
  8508. return m_hasFirstTmpRegister ? this->GetCountField(CounterFields::FirstTmpRegister) : Constants::NoRegister;
  8509. }
  8510. }