FunctionBody.cpp 387 KB

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