FunctionBody.cpp 363 KB

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