ByteCodeEmitter.cpp 494 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Copyright (c) ChakraCore Project Contributors. All rights reserved.
  4. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  5. //-------------------------------------------------------------------------------------------------------
  6. #include "RuntimeByteCodePch.h"
  7. #include "FormalsUtil.h"
  8. #include "Language/AsmJs.h"
  9. #include "ConfigFlagsList.h"
  10. void EmitReference(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  11. void EmitAssignment(ParseNode *asgnNode, ParseNode *lhs, Js::RegSlot rhsLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  12. void EmitLoad(ParseNode *rhs, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  13. void EmitCall(ParseNodeCall* pnodeCall, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue, BOOL fEvaluateComponents, Js::RegSlot overrideThisLocation = Js::Constants::NoRegister, Js::RegSlot newTargetLocation = Js::Constants::NoRegister);
  14. void EmitStartupYield(ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  15. void EmitYield(Js::RegSlot resultReg, Js::RegSlot inputReg, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  16. void EmitAwait(Js::RegSlot resultReg, Js::RegSlot inputReg, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  17. void EmitUseBeforeDeclaration(Symbol *sym, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  18. void EmitUseBeforeDeclarationRuntimeError(ByteCodeGenerator *byteCodeGenerator, Js::RegSlot location);
  19. void VisitClearTmpRegs(ParseNode * pnode, ByteCodeGenerator * byteCodeGenerator, FuncInfo * funcInfo);
  20. bool CallTargetIsArray(ParseNode *pnode)
  21. {
  22. return pnode->nop == knopName && pnode->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::Array;
  23. }
  24. #define STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode) \
  25. if ((isTopLevel)) \
  26. { \
  27. byteCodeGenerator->StartStatement(pnode); \
  28. }
  29. #define ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode) \
  30. if ((isTopLevel)) \
  31. { \
  32. byteCodeGenerator->EndStatement(pnode); \
  33. }
  34. DynamicLoadRecord::DynamicLoadRecord() : kind(DynamicLoadKind::Invalid), label(Js::Constants::NoByteCodeOffset), instance(Js::Constants::NoSlot) {}
  35. BOOL MayHaveSideEffectOnNode(ParseNode *pnode, ParseNode *pnodeSE, ByteCodeGenerator *byteCodeGenerator)
  36. {
  37. // Try to determine whether pnodeSE (SE = side effect) may kill the named var represented by pnode.
  38. if (pnode->nop == knopComputedName)
  39. {
  40. pnode = pnode->AsParseNodeUni()->pnode1;
  41. }
  42. if (pnode->nop != knopName)
  43. {
  44. // Only investigating named vars here.
  45. return false;
  46. }
  47. ArenaAllocator *alloc = byteCodeGenerator->GetAllocator();
  48. SList<ParseNode*> pNodeSEStack(alloc);
  49. pNodeSEStack.Push(pnodeSE);
  50. // A pnodeSE can have children that can cause a side effect on pnode. A stack is used to check
  51. // pnodeSE and all potential pnodeSE children that could cause a side effect on pnode. When a
  52. // child pnodeSE can cause a side effect on pnode, immediately return true. Otherwise continue
  53. // checking children of pnodeSE until none exist
  54. while (!pNodeSEStack.Empty())
  55. {
  56. ParseNode *currPnodeSE = pNodeSEStack.Pop();
  57. uint fnop = ParseNode::Grfnop(currPnodeSE->nop);
  58. if (fnop & fnopLeaf)
  59. {
  60. // pnodeSE is a leaf and can't kill anything.
  61. continue;
  62. }
  63. else if (fnop & fnopAsg)
  64. {
  65. // pnodeSE is an assignment (=, ++, +=, etc.)
  66. // Trying to examine the LHS of pnodeSE caused small perf regressions,
  67. // maybe because of code layout or some other subtle effect.
  68. return true;
  69. }
  70. else if (fnop & fnopUni)
  71. {
  72. // pnodeSE is a unary op, so recurse to the source (if present - e.g., [] may have no opnd).
  73. if (currPnodeSE->nop == knopTempRef)
  74. {
  75. continue;
  76. }
  77. else if (currPnodeSE->AsParseNodeUni()->pnode1)
  78. {
  79. pNodeSEStack.Push(currPnodeSE->AsParseNodeUni()->pnode1);
  80. }
  81. }
  82. else if (fnop & fnopBin)
  83. {
  84. // currPnodeSE is a binary (or ternary) op, so check sources (if present).
  85. pNodeSEStack.Push(currPnodeSE->AsParseNodeBin()->pnode1);
  86. if (currPnodeSE->AsParseNodeBin()->pnode2)
  87. {
  88. pNodeSEStack.Push(currPnodeSE->AsParseNodeBin()->pnode2);
  89. }
  90. }
  91. else if (currPnodeSE->nop == knopQmark)
  92. {
  93. ParseNodeTri * pnodeTriSE = currPnodeSE->AsParseNodeTri();
  94. pNodeSEStack.Push(pnodeTriSE->pnode1);
  95. pNodeSEStack.Push(pnodeTriSE->pnode2);
  96. pNodeSEStack.Push(pnodeTriSE->pnode3);
  97. }
  98. else if (currPnodeSE->nop == knopCall || currPnodeSE->nop == knopNew)
  99. {
  100. pNodeSEStack.Push(currPnodeSE->AsParseNodeCall()->pnodeTarget);
  101. if (currPnodeSE->AsParseNodeCall()->pnodeArgs)
  102. {
  103. pNodeSEStack.Push(currPnodeSE->AsParseNodeCall()->pnodeArgs);
  104. }
  105. }
  106. else if (currPnodeSE->nop == knopList)
  107. {
  108. return true;
  109. }
  110. }
  111. return false;
  112. }
  113. bool IsCallOfConstants(ParseNode *pnode);
  114. bool BlockHasOwnScope(ParseNodeBlock * pnodeBlock, ByteCodeGenerator *byteCodeGenerator);
  115. bool CreateNativeArrays(ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  116. bool IsArguments(ParseNode *pnode)
  117. {
  118. for (;;)
  119. {
  120. switch (pnode->nop)
  121. {
  122. case knopName:
  123. return pnode->AsParseNodeName()->sym && pnode->AsParseNodeName()->sym->IsArguments();
  124. case knopCall:
  125. case knopNew:
  126. if (IsArguments(pnode->AsParseNodeCall()->pnodeTarget))
  127. {
  128. return true;
  129. }
  130. if (pnode->AsParseNodeCall()->pnodeArgs)
  131. {
  132. ParseNode *pnodeArg = pnode->AsParseNodeCall()->pnodeArgs;
  133. while (pnodeArg->nop == knopList)
  134. {
  135. if (IsArguments(pnodeArg->AsParseNodeBin()->pnode1))
  136. return true;
  137. pnodeArg = pnodeArg->AsParseNodeBin()->pnode2;
  138. }
  139. pnode = pnodeArg;
  140. break;
  141. }
  142. return false;
  143. case knopArray:
  144. if (pnode->AsParseNodeArrLit()->arrayOfNumbers || pnode->AsParseNodeArrLit()->count == 0)
  145. {
  146. return false;
  147. }
  148. pnode = pnode->AsParseNodeUni()->pnode1;
  149. break;
  150. case knopQmark:
  151. if (IsArguments(pnode->AsParseNodeTri()->pnode1) || IsArguments(pnode->AsParseNodeTri()->pnode2))
  152. {
  153. return true;
  154. }
  155. pnode = pnode->AsParseNodeTri()->pnode3;
  156. break;
  157. //
  158. // Cases where we don't check for "arguments" yet.
  159. // Assume that they might have it. Disable the optimization in such scenarios
  160. //
  161. case knopList:
  162. case knopObject:
  163. case knopVarDecl:
  164. case knopConstDecl:
  165. case knopLetDecl:
  166. case knopFncDecl:
  167. case knopClassDecl:
  168. case knopFor:
  169. case knopIf:
  170. case knopDoWhile:
  171. case knopWhile:
  172. case knopForIn:
  173. case knopForOf:
  174. case knopForAwaitOf:
  175. case knopReturn:
  176. case knopBlock:
  177. case knopBreak:
  178. case knopContinue:
  179. case knopTypeof:
  180. case knopThrow:
  181. case knopWith:
  182. case knopFinally:
  183. case knopTry:
  184. case knopTryCatch:
  185. case knopTryFinally:
  186. case knopArrayPattern:
  187. case knopObjectPattern:
  188. case knopParamPattern:
  189. return true;
  190. default:
  191. {
  192. uint flags = ParseNode::Grfnop(pnode->nop);
  193. if (flags&fnopUni)
  194. {
  195. ParseNodeUni * pnodeUni = pnode->AsParseNodeUni();
  196. Assert(pnodeUni->pnode1);
  197. pnode = pnodeUni->pnode1;
  198. break;
  199. }
  200. else if (flags&fnopBin)
  201. {
  202. ParseNodeBin * pnodeBin = pnode->AsParseNodeBin();
  203. Assert(pnodeBin->pnode1 && pnodeBin->pnode2);
  204. if (IsArguments(pnodeBin->pnode1))
  205. {
  206. return true;
  207. }
  208. pnode = pnodeBin->pnode2;
  209. break;
  210. }
  211. return false;
  212. }
  213. }
  214. }
  215. }
  216. bool ApplyEnclosesArgs(ParseNode* fncDecl, ByteCodeGenerator* byteCodeGenerator);
  217. void Emit(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue, bool isConstructorCall = false, bool isTopLevel = false);
  218. void EmitBinaryOpnds(ParseNode* pnode1, ParseNode* pnode2, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot computedPropertyLocation = Js::Constants::NoRegister);
  219. bool IsExpressionStatement(ParseNode* stmt, const Js::ScriptContext *const scriptContext);
  220. void EmitInvoke(Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  221. void EmitInvoke(Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot arg1Location);
  222. static const Js::OpCode nopToOp[knopLim] =
  223. {
  224. #define OP(x) Br##x##_A
  225. #define PTNODE(nop,sn,pc,nk,grfnop,json) Js::OpCode::pc,
  226. #include "ptlist.h"
  227. };
  228. static const Js::OpCode nopToCMOp[knopLim] =
  229. {
  230. #define OP(x) Cm##x##_A
  231. #define PTNODE(nop,sn,pc,nk,grfnop,json) Js::OpCode::pc,
  232. #include "ptlist.h"
  233. };
  234. Js::OpCode ByteCodeGenerator::ToChkUndeclOp(Js::OpCode op) const
  235. {
  236. switch (op)
  237. {
  238. case Js::OpCode::StLocalSlot:
  239. return Js::OpCode::StLocalSlotChkUndecl;
  240. case Js::OpCode::StParamSlot:
  241. return Js::OpCode::StParamSlotChkUndecl;
  242. case Js::OpCode::StInnerSlot:
  243. return Js::OpCode::StInnerSlotChkUndecl;
  244. case Js::OpCode::StEnvSlot:
  245. return Js::OpCode::StEnvSlotChkUndecl;
  246. case Js::OpCode::StObjSlot:
  247. return Js::OpCode::StObjSlotChkUndecl;
  248. case Js::OpCode::StLocalObjSlot:
  249. return Js::OpCode::StLocalObjSlotChkUndecl;
  250. case Js::OpCode::StParamObjSlot:
  251. return Js::OpCode::StParamObjSlotChkUndecl;
  252. case Js::OpCode::StInnerObjSlot:
  253. return Js::OpCode::StInnerObjSlotChkUndecl;
  254. case Js::OpCode::StEnvObjSlot:
  255. return Js::OpCode::StEnvObjSlotChkUndecl;
  256. default:
  257. AssertMsg(false, "Unknown opcode for chk undecl mapping");
  258. return Js::OpCode::InvalidOpCode;
  259. }
  260. }
  261. // Tracks a register slot let/const property for the passed in debugger block/catch scope.
  262. // debuggerScope - The scope to add the variable to.
  263. // symbol - The symbol that represents the register property.
  264. // funcInfo - The function info used to store the property into the tracked debugger register slot list.
  265. // flags - The flags to assign to the property.
  266. // isFunctionDeclaration - Whether or not the register is a function declaration, which requires that its byte code offset be updated immediately.
  267. void ByteCodeGenerator::TrackRegisterPropertyForDebugger(
  268. Js::DebuggerScope *debuggerScope,
  269. Symbol *symbol,
  270. FuncInfo *funcInfo,
  271. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  272. bool isFunctionDeclaration /*= false*/)
  273. {
  274. Assert(debuggerScope);
  275. Assert(symbol);
  276. Assert(funcInfo);
  277. Js::RegSlot location = symbol->GetLocation();
  278. Js::DebuggerScope *correctDebuggerScope = debuggerScope;
  279. if (debuggerScope->scopeType != Js::DiagExtraScopesType::DiagBlockScopeDirect && debuggerScope->scopeType != Js::DiagExtraScopesType::DiagCatchScopeDirect)
  280. {
  281. // We have to get the appropriate scope and add property over there.
  282. // Make sure the scope is created whether we're in debug mode or not, because we
  283. // need the empty scopes present during reparsing for debug mode.
  284. correctDebuggerScope = debuggerScope->GetSiblingScope(location, Writer()->GetFunctionWrite());
  285. }
  286. if (this->ShouldTrackDebuggerMetadata() && !symbol->GetIsTrackedForDebugger())
  287. {
  288. // Only track the property if we're in debug mode since it's only needed by the debugger.
  289. Js::PropertyId propertyId = symbol->EnsurePosition(this);
  290. this->Writer()->AddPropertyToDebuggerScope(
  291. correctDebuggerScope,
  292. location,
  293. propertyId,
  294. /*shouldConsumeRegister*/ true,
  295. flags,
  296. isFunctionDeclaration);
  297. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  298. byteCodeFunction->InsertSymbolToRegSlotList(location, propertyId, funcInfo->varRegsCount);
  299. symbol->SetIsTrackedForDebugger(true);
  300. }
  301. }
  302. void ByteCodeGenerator::TrackActivationObjectPropertyForDebugger(
  303. Js::DebuggerScope *debuggerScope,
  304. Symbol *symbol,
  305. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  306. bool isFunctionDeclaration /*= false*/)
  307. {
  308. Assert(debuggerScope);
  309. Assert(symbol);
  310. // Only need to track activation object properties in debug mode.
  311. if (ShouldTrackDebuggerMetadata() && !symbol->GetIsTrackedForDebugger())
  312. {
  313. Js::RegSlot location = symbol->GetLocation();
  314. Js::PropertyId propertyId = symbol->EnsurePosition(this);
  315. this->Writer()->AddPropertyToDebuggerScope(
  316. debuggerScope,
  317. location,
  318. propertyId,
  319. /*shouldConsumeRegister*/ false,
  320. flags,
  321. isFunctionDeclaration);
  322. symbol->SetIsTrackedForDebugger(true);
  323. }
  324. }
  325. void ByteCodeGenerator::TrackSlotArrayPropertyForDebugger(
  326. Js::DebuggerScope *debuggerScope,
  327. Symbol* symbol,
  328. Js::PropertyId propertyId,
  329. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  330. bool isFunctionDeclaration /*= false*/)
  331. {
  332. // Note: Slot array properties are tracked even in non-debug mode in order to support slot array serialization
  333. // of let/const variables between non-debug and debug mode (for example, when a slot array var escapes and is retrieved
  334. // after a debugger attach or for WWA apps). They are also needed for heap enumeration.
  335. Assert(debuggerScope);
  336. Assert(symbol);
  337. if (!symbol->GetIsTrackedForDebugger())
  338. {
  339. Js::RegSlot location = symbol->GetScopeSlot();
  340. Assert(location != Js::Constants::NoRegister);
  341. Assert(propertyId != Js::Constants::NoProperty);
  342. this->Writer()->AddPropertyToDebuggerScope(
  343. debuggerScope,
  344. location,
  345. propertyId,
  346. /*shouldConsumeRegister*/ false,
  347. flags,
  348. isFunctionDeclaration);
  349. symbol->SetIsTrackedForDebugger(true);
  350. }
  351. }
  352. // Tracks a function declaration inside a block scope for the debugger metadata's current scope (let binding).
  353. void ByteCodeGenerator::TrackFunctionDeclarationPropertyForDebugger(Symbol *functionDeclarationSymbol, FuncInfo *funcInfoParent)
  354. {
  355. Assert(functionDeclarationSymbol);
  356. Assert(funcInfoParent);
  357. AssertMsg(functionDeclarationSymbol->GetIsBlockVar(), "We should only track inner function let bindings for the debugger.");
  358. // Note: we don't have to check symbol->GetIsTrackedForDebugger, as we are not doing actual work here,
  359. // which is done in other Track* functions that we call.
  360. if (functionDeclarationSymbol->IsInSlot(this, funcInfoParent))
  361. {
  362. if (functionDeclarationSymbol->GetScope()->GetIsObject())
  363. {
  364. this->TrackActivationObjectPropertyForDebugger(
  365. this->Writer()->GetCurrentDebuggerScope(),
  366. functionDeclarationSymbol,
  367. Js::DebuggerScopePropertyFlags_None,
  368. true /*isFunctionDeclaration*/);
  369. }
  370. else
  371. {
  372. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  373. // Note that slot array inner function bindings are tracked even in non-debug mode in order
  374. // to keep the lifetime of the closure binding that could escape around for heap enumeration.
  375. functionDeclarationSymbol->EnsureScopeSlot(this, funcInfoParent);
  376. functionDeclarationSymbol->EnsurePosition(this);
  377. this->TrackSlotArrayPropertyForDebugger(
  378. this->Writer()->GetCurrentDebuggerScope(),
  379. functionDeclarationSymbol,
  380. functionDeclarationSymbol->GetPosition(),
  381. Js::DebuggerScopePropertyFlags_None,
  382. true /*isFunctionDeclaration*/);
  383. }
  384. }
  385. else
  386. {
  387. this->TrackRegisterPropertyForDebugger(
  388. this->Writer()->GetCurrentDebuggerScope(),
  389. functionDeclarationSymbol,
  390. funcInfoParent,
  391. Js::DebuggerScopePropertyFlags_None,
  392. true /*isFunctionDeclaration*/);
  393. }
  394. }
  395. // Updates the byte code offset of the property with the passed in location and ID.
  396. // Used to track let/const variables that are in the dead zone debugger side.
  397. // location - The activation object, scope slot index, or register location for the property.
  398. // propertyId - The ID of the property to update.
  399. // shouldConsumeRegister - Whether or not the a register should be consumed (used for reg slot locations).
  400. void ByteCodeGenerator::UpdateDebuggerPropertyInitializationOffset(Js::RegSlot location, Js::PropertyId propertyId, bool shouldConsumeRegister)
  401. {
  402. Assert(this->Writer());
  403. Js::DebuggerScope* currentDebuggerScope = this->Writer()->GetCurrentDebuggerScope();
  404. Assert(currentDebuggerScope);
  405. if (currentDebuggerScope != nullptr)
  406. {
  407. this->Writer()->UpdateDebuggerPropertyInitializationOffset(
  408. currentDebuggerScope,
  409. location,
  410. propertyId,
  411. shouldConsumeRegister);
  412. }
  413. }
  414. void ByteCodeGenerator::LoadHeapArguments(FuncInfo *funcInfo)
  415. {
  416. if (funcInfo->GetHasCachedScope())
  417. {
  418. this->LoadCachedHeapArguments(funcInfo);
  419. }
  420. else
  421. {
  422. this->LoadUncachedHeapArguments(funcInfo);
  423. }
  424. }
  425. void GetFormalArgsArray(ByteCodeGenerator *byteCodeGenerator, FuncInfo * funcInfo, Js::PropertyIdArray *propIds)
  426. {
  427. Assert(funcInfo);
  428. Assert(propIds);
  429. Assert(byteCodeGenerator);
  430. bool hadDuplicates = false;
  431. Js::ArgSlot i = 0;
  432. auto processArg = [&](ParseNode *pnode)
  433. {
  434. if (pnode->IsVarLetOrConst())
  435. {
  436. Assert(i < propIds->count);
  437. Symbol *sym = pnode->AsParseNodeVar()->sym;
  438. Assert(sym);
  439. Js::PropertyId symPos = sym->EnsurePosition(byteCodeGenerator);
  440. //
  441. // Check if the function has any same name parameters
  442. // For the same name param, only the last one will be passed the correct propertyid
  443. // For remaining dup param names, pass Constants::NoProperty
  444. //
  445. for (Js::ArgSlot j = 0; j < i; j++)
  446. {
  447. if (propIds->elements[j] == symPos)
  448. {
  449. // Found a dup parameter name
  450. propIds->elements[j] = Js::Constants::NoProperty;
  451. hadDuplicates = true;
  452. break;
  453. }
  454. }
  455. propIds->elements[i] = symPos;
  456. }
  457. else
  458. {
  459. propIds->elements[i] = Js::Constants::NoProperty;
  460. }
  461. ++i;
  462. };
  463. MapFormals(funcInfo->root, processArg);
  464. propIds->hadDuplicates = hadDuplicates;
  465. }
  466. void ByteCodeGenerator::LoadUncachedHeapArguments(FuncInfo *funcInfo)
  467. {
  468. Assert(funcInfo->GetHasHeapArguments());
  469. Scope *scope = funcInfo->GetBodyScope();
  470. Assert(scope);
  471. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  472. Assert(argSym && argSym->IsArguments());
  473. Js::RegSlot argumentsLoc = argSym->GetLocation();
  474. Js::OpCode opcode = !funcInfo->root->HasNonSimpleParameterList() ? Js::OpCode::LdHeapArguments : Js::OpCode::LdLetHeapArguments;
  475. bool hasRest = funcInfo->root->pnodeRest != nullptr;
  476. uint count = funcInfo->inArgsCount + (hasRest ? 1 : 0) - 1;
  477. if (count == 0)
  478. {
  479. // If no formals to function (only "this"), then no need to create the scope object.
  480. // Leave both the arguments location and the propertyIds location as null.
  481. Assert(funcInfo->root->pnodeParams == nullptr && !hasRest);
  482. }
  483. else if (!NeedScopeObjectForArguments(funcInfo, funcInfo->root))
  484. {
  485. // We may not need a scope object for arguments, e.g. strict mode with no eval.
  486. }
  487. else if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  488. {
  489. // Pass the frame object and ID array to the runtime, and put the resulting Arguments object
  490. // at the expected location.
  491. Js::PropertyIdArray *propIds = funcInfo->GetParsedFunctionBody()->AllocatePropertyIdArrayForFormals(UInt32Math::Mul(count, sizeof(Js::PropertyId)), count, 0);
  492. GetFormalArgsArray(this, funcInfo, propIds);
  493. }
  494. this->m_writer.Reg1(opcode, argumentsLoc);
  495. EmitLocalPropInit(argSym->GetLocation(), argSym, funcInfo);
  496. }
  497. void ByteCodeGenerator::LoadCachedHeapArguments(FuncInfo *funcInfo)
  498. {
  499. Assert(funcInfo->GetHasHeapArguments());
  500. Scope *scope = funcInfo->GetBodyScope();
  501. Assert(scope);
  502. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  503. Assert(argSym && argSym->IsArguments());
  504. Js::RegSlot argumentsLoc = argSym->GetLocation();
  505. Js::OpCode op = !funcInfo->root->HasNonSimpleParameterList() ? Js::OpCode::LdHeapArgsCached : Js::OpCode::LdLetHeapArgsCached;
  506. this->m_writer.Reg1(op, argumentsLoc);
  507. EmitLocalPropInit(argumentsLoc, argSym, funcInfo);
  508. }
  509. Js::JavascriptArray* ByteCodeGenerator::BuildArrayFromStringList(ParseNode* stringNodeList, uint arrayLength, Js::ScriptContext* scriptContext)
  510. {
  511. Assert(stringNodeList);
  512. uint index = 0;
  513. Js::Var str;
  514. IdentPtr pid;
  515. Js::JavascriptArray* pArr = scriptContext->GetLibrary()->CreateArray(arrayLength);
  516. while (stringNodeList->nop == knopList)
  517. {
  518. Assert(stringNodeList->AsParseNodeBin()->pnode1->nop == knopStr);
  519. pid = stringNodeList->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid;
  520. str = Js::JavascriptString::NewCopyBuffer(pid->Psz(), pid->Cch(), scriptContext);
  521. pArr->SetItemWithAttributes(index, str, PropertyEnumerable);
  522. stringNodeList = stringNodeList->AsParseNodeBin()->pnode2;
  523. index++;
  524. }
  525. Assert(stringNodeList->nop == knopStr);
  526. pid = stringNodeList->AsParseNodeStr()->pid;
  527. str = Js::JavascriptString::NewCopyBuffer(pid->Psz(), pid->Cch(), scriptContext);
  528. pArr->SetItemWithAttributes(index, str, PropertyEnumerable);
  529. return pArr;
  530. }
  531. // For now, this just assigns field ids for the current script.
  532. // Later, we will combine this information with the global field id map.
  533. // This temporary code will not work if a global member is accessed both with and without a LHS.
  534. void ByteCodeGenerator::AssignPropertyIds(Js::ParseableFunctionInfo* functionInfo)
  535. {
  536. globalScope->ForEachSymbol([this, functionInfo](Symbol * sym)
  537. {
  538. this->AssignPropertyId(sym, functionInfo);
  539. });
  540. }
  541. void ByteCodeGenerator::InitBlockScopedContent(ParseNodeBlock *pnodeBlock, Js::DebuggerScope* debuggerScope, FuncInfo *funcInfo)
  542. {
  543. Assert(pnodeBlock->nop == knopBlock);
  544. auto genBlockInit = [this, debuggerScope, funcInfo](ParseNode *pnode)
  545. {
  546. // Only check if the scope is valid when let/const vars are in the scope. If there are no let/const vars,
  547. // the debugger scope will not be created.
  548. AssertMsg(debuggerScope, "Missing a case of scope tracking in BeginEmitBlock.");
  549. FuncInfo *funcInfo = this->TopFuncInfo();
  550. Symbol *sym = pnode->AsParseNodeVar()->sym;
  551. Scope *scope = sym->GetScope();
  552. if (sym->GetIsGlobal())
  553. {
  554. Js::PropertyId propertyId = sym->EnsurePosition(this);
  555. if (this->flags & fscrEval)
  556. {
  557. AssertMsg(this->IsConsoleScopeEval(), "Let/Consts cannot be in global scope outside of console eval");
  558. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ? Js::OpCode::InitUndeclConsoleConstFld : Js::OpCode::InitUndeclConsoleLetFld;
  559. this->m_writer.ElementScopedU(op, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  560. }
  561. else
  562. {
  563. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  564. Js::OpCode::InitUndeclRootConstFld : Js::OpCode::InitUndeclRootLetFld;
  565. this->m_writer.ElementRootU(op, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  566. }
  567. }
  568. else if (sym->IsInSlot(this, funcInfo) || (scope->GetIsObject() && sym->NeedsSlotAlloc(this, funcInfo)))
  569. {
  570. if (scope->GetIsObject())
  571. {
  572. Js::RegSlot scopeLocation = scope->GetLocation();
  573. Js::PropertyId propertyId = sym->EnsurePosition(this);
  574. if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  575. {
  576. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  577. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  578. Js::OpCode::InitUndeclLocalConstFld : Js::OpCode::InitUndeclLocalLetFld;
  579. this->m_writer.ElementP(op, ByteCodeGenerator::ReturnRegister, cacheId);
  580. }
  581. else
  582. {
  583. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
  584. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  585. Js::OpCode::InitUndeclConstFld : Js::OpCode::InitUndeclLetFld;
  586. this->m_writer.ElementPIndexed(op, ByteCodeGenerator::ReturnRegister, scope->GetInnerScopeIndex(), cacheId);
  587. }
  588. TrackActivationObjectPropertyForDebugger(debuggerScope, sym, pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  589. }
  590. else
  591. {
  592. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  593. this->m_writer.Reg1(Js::OpCode::InitUndecl, tmpReg);
  594. this->EmitLocalPropInit(tmpReg, sym, funcInfo);
  595. funcInfo->ReleaseTmpRegister(tmpReg);
  596. // Slot array properties are tracked in non-debug mode as well because they need to stay
  597. // around for heap enumeration and escaping during attach/detach.
  598. TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(this), pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  599. }
  600. }
  601. else if (!sym->GetIsModuleExportStorage())
  602. {
  603. if (sym->GetDecl()->AsParseNodeVar()->isSwitchStmtDecl)
  604. {
  605. // let/const declared in a switch is the only case of a variable that must be checked for
  606. // use-before-declaration dynamically within its own function.
  607. this->m_writer.Reg1(Js::OpCode::InitUndecl, sym->GetLocation());
  608. }
  609. // Syms that begin in register may be delay-captured. In debugger mode, such syms
  610. // will live only in slots, so tell the debugger to find them there.
  611. if (sym->NeedsSlotAlloc(this, funcInfo))
  612. {
  613. TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(this), pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  614. }
  615. else
  616. {
  617. TrackRegisterPropertyForDebugger(debuggerScope, sym, funcInfo, pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  618. }
  619. }
  620. };
  621. IterateBlockScopedVariables(pnodeBlock, genBlockInit);
  622. }
  623. // Records the start of a debugger scope if the passed in node has any let/const variables (or is not a block node).
  624. // If it has no let/const variables, nullptr will be returned as no scope will be created.
  625. Js::DebuggerScope* ByteCodeGenerator::RecordStartScopeObject(ParseNode * pnode, Js::DiagExtraScopesType scopeType, Js::RegSlot scopeLocation /*= Js::Constants::NoRegister*/, int* index /*= nullptr*/)
  626. {
  627. Assert(pnode);
  628. if (pnode->nop == knopBlock && !pnode->AsParseNodeBlock()->HasBlockScopedContent())
  629. {
  630. // In order to reduce allocations now that we track debugger scopes in non-debug mode,
  631. // don't add a block to the chain if it has no let/const variables at all.
  632. return nullptr;
  633. }
  634. return this->Writer()->RecordStartScopeObject(scopeType, scopeLocation, index);
  635. }
  636. // Records the end of the current scope, but only if the current block has block scoped content.
  637. // Otherwise, a scope would not have been added (see ByteCodeGenerator::RecordStartScopeObject()).
  638. void ByteCodeGenerator::RecordEndScopeObject(ParseNode *pnodeBlock)
  639. {
  640. Assert(pnodeBlock);
  641. if (pnodeBlock->nop == knopBlock && !pnodeBlock->AsParseNodeBlock()->HasBlockScopedContent())
  642. {
  643. return;
  644. }
  645. this->Writer()->RecordEndScopeObject();
  646. }
  647. void BeginEmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  648. {
  649. Js::DebuggerScope* debuggerScope = nullptr;
  650. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  651. {
  652. Scope *scope = pnodeBlock->scope;
  653. byteCodeGenerator->PushScope(scope);
  654. Js::RegSlot scopeLocation = scope->GetLocation();
  655. if (scope->GetMustInstantiate())
  656. {
  657. Assert(scopeLocation == Js::Constants::NoRegister);
  658. scopeLocation = funcInfo->FirstInnerScopeReg() + scope->GetInnerScopeIndex();
  659. if (scope->GetIsObject())
  660. {
  661. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInObject, scopeLocation);
  662. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::NewBlockScope, scope->GetInnerScopeIndex());
  663. }
  664. else
  665. {
  666. int scopeIndex = Js::DebuggerScope::InvalidScopeIndex;
  667. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInSlot, scopeLocation, &scopeIndex);
  668. // TODO: Handle heap enumeration
  669. int scopeSlotCount = scope->GetScopeSlotCount();
  670. byteCodeGenerator->Writer()->Num3(Js::OpCode::NewInnerScopeSlots, scope->GetInnerScopeIndex(), scopeSlotCount + Js::ScopeSlots::FirstSlotIndex, scopeIndex);
  671. }
  672. }
  673. else
  674. {
  675. // In the direct register access case, there is no block scope emitted but we can still track
  676. // the start and end offset of the block. The location registers for let/const variables will still be
  677. // captured along with this range in InitBlockScopedContent().
  678. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeDirect);
  679. }
  680. bool const isGlobalEvalBlockScope = scope->IsGlobalEvalBlockScope();
  681. Js::RegSlot frameDisplayLoc = Js::Constants::NoRegister;
  682. Js::RegSlot tmpInnerEnvReg = Js::Constants::NoRegister;
  683. ParseNodePtr pnodeScope;
  684. for (pnodeScope = pnodeBlock->pnodeScopes; pnodeScope;)
  685. {
  686. switch (pnodeScope->nop)
  687. {
  688. case knopFncDecl:
  689. if (pnodeScope->AsParseNodeFnc()->IsDeclaration())
  690. {
  691. // The frameDisplayLoc register's lifetime has to be controlled by this function. We can't let
  692. // it be released by DefineOneFunction, because further iterations of this loop can allocate
  693. // temps, and we can't let frameDisplayLoc be re-purposed until this loop completes.
  694. // So we'll supply a temp that we allocate and release here.
  695. if (frameDisplayLoc == Js::Constants::NoRegister)
  696. {
  697. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  698. {
  699. frameDisplayLoc = funcInfo->frameDisplayRegister;
  700. }
  701. else
  702. {
  703. frameDisplayLoc = funcInfo->GetEnvRegister();
  704. }
  705. tmpInnerEnvReg = funcInfo->AcquireTmpRegister();
  706. frameDisplayLoc = byteCodeGenerator->PrependLocalScopes(frameDisplayLoc, tmpInnerEnvReg, funcInfo);
  707. }
  708. byteCodeGenerator->DefineOneFunction(pnodeScope->AsParseNodeFnc(), funcInfo, true, frameDisplayLoc);
  709. }
  710. // If this is the global eval block scope, the function is actually assigned to the global
  711. // so we don't need to keep the registers.
  712. if (isGlobalEvalBlockScope)
  713. {
  714. funcInfo->ReleaseLoc(pnodeScope);
  715. pnodeScope->location = Js::Constants::NoRegister;
  716. }
  717. pnodeScope = pnodeScope->AsParseNodeFnc()->pnodeNext;
  718. break;
  719. case knopBlock:
  720. pnodeScope = pnodeScope->AsParseNodeBlock()->pnodeNext;
  721. break;
  722. case knopCatch:
  723. pnodeScope = pnodeScope->AsParseNodeCatch()->pnodeNext;
  724. break;
  725. case knopWith:
  726. pnodeScope = pnodeScope->AsParseNodeWith()->pnodeNext;
  727. break;
  728. }
  729. }
  730. if (tmpInnerEnvReg != Js::Constants::NoRegister)
  731. {
  732. funcInfo->ReleaseTmpRegister(tmpInnerEnvReg);
  733. }
  734. }
  735. else
  736. {
  737. Scope *scope = pnodeBlock->scope;
  738. if (scope)
  739. {
  740. if (scope->GetMustInstantiate())
  741. {
  742. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInObject);
  743. }
  744. else
  745. {
  746. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeDirect);
  747. }
  748. }
  749. else
  750. {
  751. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInSlot);
  752. }
  753. }
  754. byteCodeGenerator->InitBlockScopedContent(pnodeBlock, debuggerScope, funcInfo);
  755. }
  756. void EndEmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  757. {
  758. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  759. {
  760. Scope *scope = pnodeBlock->scope;
  761. Assert(scope);
  762. Assert(scope == byteCodeGenerator->GetCurrentScope());
  763. byteCodeGenerator->PopScope();
  764. }
  765. byteCodeGenerator->RecordEndScopeObject(pnodeBlock);
  766. }
  767. void CloneEmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  768. {
  769. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  770. {
  771. // Only let variables have observable behavior when there are per iteration
  772. // bindings. const variables do not since they are immutable. Therefore,
  773. // (and the spec agrees), only create new scope clones if the loop variable
  774. // is a let declaration.
  775. bool isConst = false;
  776. pnodeBlock->scope->ForEachSymbolUntil([&isConst](Symbol * const sym) {
  777. // Exploit the fact that a for loop sxBlock can only have let and const
  778. // declarations, and can only have one or the other, regardless of how
  779. // many syms there might be. Thus only check the first sym.
  780. isConst = sym->GetDecl()->nop == knopConstDecl;
  781. return true;
  782. });
  783. if (!isConst)
  784. {
  785. Scope *scope = pnodeBlock->scope;
  786. Assert(scope == byteCodeGenerator->GetCurrentScope());
  787. if (scope->GetMustInstantiate())
  788. {
  789. Js::OpCode op = scope->GetIsObject() ? Js::OpCode::CloneBlockScope : Js::OpCode::CloneInnerScopeSlots;
  790. byteCodeGenerator->Writer()->Unsigned1(op, scope->GetInnerScopeIndex());
  791. }
  792. }
  793. }
  794. }
  795. void EmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue)
  796. {
  797. Assert(pnodeBlock->nop == knopBlock);
  798. ParseNode *pnode = pnodeBlock->pnodeStmt;
  799. if (pnode == nullptr)
  800. {
  801. return;
  802. }
  803. BeginEmitBlock(pnodeBlock, byteCodeGenerator, funcInfo);
  804. ParseNode *pnodeLastValStmt = pnodeBlock->pnodeLastValStmt;
  805. while (pnode->nop == knopList)
  806. {
  807. ParseNode* stmt = pnode->AsParseNodeBin()->pnode1;
  808. if (stmt == pnodeLastValStmt)
  809. {
  810. // This is the last guaranteed return value, so any potential return values have to be
  811. // copied to the return register from this point forward.
  812. pnodeLastValStmt = nullptr;
  813. }
  814. byteCodeGenerator->EmitTopLevelStatement(stmt, funcInfo, fReturnValue && (pnodeLastValStmt == nullptr));
  815. pnode = pnode->AsParseNodeBin()->pnode2;
  816. }
  817. if (pnode == pnodeLastValStmt)
  818. {
  819. pnodeLastValStmt = nullptr;
  820. }
  821. byteCodeGenerator->EmitTopLevelStatement(pnode, funcInfo, fReturnValue && (pnodeLastValStmt == nullptr));
  822. EndEmitBlock(pnodeBlock, byteCodeGenerator, funcInfo);
  823. }
  824. void ClearTmpRegs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* emitFunc)
  825. {
  826. if (emitFunc->IsTmpReg(pnode->location))
  827. {
  828. pnode->location = Js::Constants::NoRegister;
  829. }
  830. }
  831. void ByteCodeGenerator::EmitTopLevelStatement(ParseNode *stmt, FuncInfo *funcInfo, BOOL fReturnValue)
  832. {
  833. if (stmt->nop == knopFncDecl && stmt->AsParseNodeFnc()->IsDeclaration())
  834. {
  835. // Function declarations (not function-declaration RHS's) are already fully processed.
  836. // Skip them here so the temp registers don't get messed up.
  837. return;
  838. }
  839. if (stmt->nop == knopName || stmt->nop == knopDot)
  840. {
  841. // Generating span for top level names are mostly useful in debugging mode, because user can debug it even though no side-effect expected.
  842. // But the name can have runtime error, e.g., foo.bar; // where foo is not defined.
  843. // At this time we need to throw proper line number and offset. so recording on all modes will be useful.
  844. StartStatement(stmt);
  845. Writer()->Empty(Js::OpCode::Nop);
  846. EndStatement(stmt);
  847. }
  848. Emit(stmt, this, funcInfo, fReturnValue, false/*isConstructorCall*/, true/*isTopLevel*/);
  849. if (funcInfo->IsTmpReg(stmt->location))
  850. {
  851. funcInfo->ReleaseLoc(stmt);
  852. }
  853. }
  854. // ByteCodeGenerator::DefineFunctions
  855. //
  856. // Emit byte code for scope-wide function definitions before any calls in the scope, regardless of lexical
  857. // order. Note that stores to the closure array are not emitted until we see the knopFncDecl in the tree
  858. // to make sure that sources of the stores have been defined.
  859. void ByteCodeGenerator::DefineFunctions(FuncInfo *funcInfoParent)
  860. {
  861. // DefineCachedFunctions doesn't depend on whether the user vars are declared or not, so
  862. // we'll just overload this variable to mean that the functions getting called again and we don't need to do anything
  863. if (funcInfoParent->GetHasCachedScope())
  864. {
  865. this->DefineCachedFunctions(funcInfoParent);
  866. }
  867. else
  868. {
  869. this->DefineUncachedFunctions(funcInfoParent);
  870. }
  871. }
  872. // Iterate over all child functions in a function's parameter and body scopes.
  873. template<typename Fn>
  874. void MapContainerScopeFunctions(ParseNode* pnodeScope, Fn fn)
  875. {
  876. auto mapFncDeclsInScopeList = [&](ParseNode *pnodeHead)
  877. {
  878. for (ParseNode *pnode = pnodeHead; pnode != nullptr;)
  879. {
  880. switch (pnode->nop)
  881. {
  882. case knopFncDecl:
  883. fn(pnode);
  884. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  885. break;
  886. case knopBlock:
  887. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  888. break;
  889. case knopCatch:
  890. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  891. break;
  892. case knopWith:
  893. pnode = pnode->AsParseNodeWith()->pnodeNext;
  894. break;
  895. default:
  896. AssertMsg(false, "Unexpected opcode in tree of scopes");
  897. return;
  898. }
  899. }
  900. };
  901. pnodeScope->AsParseNodeFnc()->MapContainerScopes(mapFncDeclsInScopeList);
  902. }
  903. void ByteCodeGenerator::DefineCachedFunctions(FuncInfo *funcInfoParent)
  904. {
  905. ParseNode *pnodeParent = funcInfoParent->root;
  906. uint slotCount = 0;
  907. auto countFncSlots = [&](ParseNode *pnodeFnc)
  908. {
  909. if (pnodeFnc->AsParseNodeFnc()->GetFuncSymbol() != nullptr && pnodeFnc->AsParseNodeFnc()->IsDeclaration())
  910. {
  911. slotCount++;
  912. }
  913. };
  914. MapContainerScopeFunctions(pnodeParent, countFncSlots);
  915. if (slotCount == 0)
  916. {
  917. return;
  918. }
  919. size_t extraBytesActual = AllocSizeMath::Mul(slotCount, sizeof(Js::FuncInfoEntry));
  920. // Reg2Aux takes int for byteCount so we need to convert to int. OOM if we can't because it would truncate data.
  921. if (extraBytesActual > INT_MAX)
  922. {
  923. Js::Throw::OutOfMemory();
  924. }
  925. int extraBytes = (int)extraBytesActual;
  926. Js::FuncInfoArray *info = AnewPlus(alloc, extraBytes, Js::FuncInfoArray, slotCount);
  927. // slotCount is guaranteed to be non-zero here.
  928. Js::AuxArray<uint32> * slotIdInCachedScopeToNestedIndexArray = funcInfoParent->GetParsedFunctionBody()->AllocateSlotIdInCachedScopeToNestedIndexArray(slotCount);
  929. slotCount = 0;
  930. auto fillEntries = [&](ParseNode *pnodeFnc)
  931. {
  932. Symbol *sym = pnodeFnc->AsParseNodeFnc()->GetFuncSymbol();
  933. if (sym != nullptr && (pnodeFnc->AsParseNodeFnc()->IsDeclaration() || pnodeFnc->AsParseNodeFnc()->IsDefaultModuleExport()))
  934. {
  935. AssertMsg(!pnodeFnc->AsParseNodeFnc()->IsGenerator(), "Generator functions are not supported by InitCachedFuncs but since they always escape they should disable function caching");
  936. Js::FuncInfoEntry *entry = &info->elements[slotCount];
  937. entry->nestedIndex = pnodeFnc->AsParseNodeFnc()->nestedIndex;
  938. entry->scopeSlot = sym->GetScopeSlot();
  939. slotIdInCachedScopeToNestedIndexArray->elements[slotCount] = pnodeFnc->AsParseNodeFnc()->nestedIndex;
  940. slotCount++;
  941. }
  942. };
  943. MapContainerScopeFunctions(pnodeParent, fillEntries);
  944. m_writer.AuxNoReg(Js::OpCode::InitCachedFuncs,
  945. info,
  946. sizeof(Js::FuncInfoArray) + extraBytes,
  947. sizeof(Js::FuncInfoArray) + extraBytes);
  948. slotCount = 0;
  949. auto defineOrGetCachedFunc = [&](ParseNode *pnodeFnc)
  950. {
  951. Symbol *sym = pnodeFnc->AsParseNodeFnc()->GetFuncSymbol();
  952. if (pnodeFnc->AsParseNodeFnc()->IsDeclaration())
  953. {
  954. // Do we need to define the function here (i.e., is it not one of our cached locals)?
  955. // Only happens if the sym is null (e.g., function x.y(){}).
  956. if (sym == nullptr)
  957. {
  958. this->DefineOneFunction(pnodeFnc->AsParseNodeFnc(), funcInfoParent);
  959. }
  960. else if (!sym->IsInSlot(this, funcInfoParent) && sym->GetLocation() != Js::Constants::NoRegister)
  961. {
  962. // If it was defined by InitCachedFuncs, do we need to put it in a register rather than a slot?
  963. m_writer.Reg1Unsigned1(Js::OpCode::GetCachedFunc, sym->GetLocation(), slotCount);
  964. }
  965. // The "x = function() {...}" case is being generated on the fly, during emission,
  966. // so the caller expects to be able to release this register.
  967. funcInfoParent->ReleaseLoc(pnodeFnc);
  968. pnodeFnc->location = Js::Constants::NoRegister;
  969. slotCount++;
  970. }
  971. };
  972. MapContainerScopeFunctions(pnodeParent, defineOrGetCachedFunc);
  973. AdeletePlus(alloc, extraBytes, info);
  974. }
  975. void ByteCodeGenerator::DefineUncachedFunctions(FuncInfo *funcInfoParent)
  976. {
  977. ParseNode *pnodeParent = funcInfoParent->root;
  978. auto defineCheck = [&](ParseNode *pnodeFnc)
  979. {
  980. Assert(pnodeFnc->nop == knopFncDecl);
  981. //
  982. // Don't define the function upfront in following cases
  983. // 1. x = function() {...};
  984. // Don't define the function for all modes.
  985. // Such a function can only be accessed via the LHS, so we define it at the assignment point
  986. // rather than the scope entry to save a register (and possibly save the whole definition).
  987. //
  988. // 2. x = function f() {...};
  989. // f is not visible in the enclosing scope.
  990. // Such function expressions should be emitted only at the assignment point, as can be used only
  991. // after the assignment. Might save register.
  992. //
  993. if (pnodeFnc->AsParseNodeFnc()->IsDeclaration() || pnodeFnc->AsParseNodeFnc()->IsDefaultModuleExport())
  994. {
  995. this->DefineOneFunction(pnodeFnc->AsParseNodeFnc(), funcInfoParent);
  996. // The "x = function() {...}" case is being generated on the fly, during emission,
  997. // so the caller expects to be able to release this register.
  998. funcInfoParent->ReleaseLoc(pnodeFnc);
  999. pnodeFnc->location = Js::Constants::NoRegister;
  1000. }
  1001. };
  1002. MapContainerScopeFunctions(pnodeParent, defineCheck);
  1003. }
  1004. void EmitAssignmentToFuncName(ParseNodeFnc *pnodeFnc, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfoParent)
  1005. {
  1006. // Assign the location holding the func object reference to the given name.
  1007. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  1008. Symbol *sym = pnodeFnc->pnodeName->sym;
  1009. if (sym != nullptr && !sym->GetIsFuncExpr())
  1010. {
  1011. if (sym->GetIsModuleExportStorage())
  1012. {
  1013. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  1014. }
  1015. else if (sym->GetIsGlobal())
  1016. {
  1017. Js::PropertyId propertyId = sym->GetPosition();
  1018. byteCodeGenerator->EmitGlobalFncDeclInit(pnodeFnc->location, propertyId, funcInfoParent);
  1019. if (byteCodeGenerator->GetFlags() & fscrEval && !funcInfoParent->GetIsStrictMode())
  1020. {
  1021. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  1022. }
  1023. }
  1024. else
  1025. {
  1026. if (sym->NeedsSlotAlloc(byteCodeGenerator, funcInfoParent))
  1027. {
  1028. if (!sym->GetHasNonCommittedReference() ||
  1029. (funcInfoParent->GetParsedFunctionBody()->DoStackNestedFunc()))
  1030. {
  1031. // No point in trying to optimize if there are no references before we have to commit to slot.
  1032. // And not safe to delay putting a stack function in the slot, since we may miss boxing.
  1033. sym->SetIsCommittedToSlot();
  1034. }
  1035. }
  1036. if (sym->GetScope()->GetFunc() != byteCodeGenerator->TopFuncInfo())
  1037. {
  1038. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  1039. }
  1040. else
  1041. {
  1042. byteCodeGenerator->EmitLocalPropInit(pnodeFnc->location, sym, funcInfoParent);
  1043. }
  1044. Symbol * fncScopeSym = sym->GetFuncScopeVarSym();
  1045. if (fncScopeSym)
  1046. {
  1047. if (fncScopeSym->GetIsGlobal() && byteCodeGenerator->GetFlags() & fscrEval)
  1048. {
  1049. Js::PropertyId propertyId = fncScopeSym->GetPosition();
  1050. byteCodeGenerator->EmitGlobalFncDeclInit(pnodeFnc->location, propertyId, funcInfoParent);
  1051. }
  1052. else
  1053. {
  1054. byteCodeGenerator->EmitPropStore(pnodeFnc->location, fncScopeSym, nullptr, funcInfoParent, false, false, /* isFncDeclVar */true);
  1055. }
  1056. }
  1057. }
  1058. }
  1059. }
  1060. Js::RegSlot ByteCodeGenerator::DefineOneFunction(ParseNodeFnc *pnodeFnc, FuncInfo *funcInfoParent, bool generateAssignment, Js::RegSlot regEnv, Js::RegSlot frameDisplayTemp)
  1061. {
  1062. Assert(pnodeFnc->nop == knopFncDecl);
  1063. funcInfoParent->AcquireLoc(pnodeFnc);
  1064. if (regEnv == Js::Constants::NoRegister)
  1065. {
  1066. // If the child needs a closure, find a heap-allocated frame to pass to it.
  1067. if (frameDisplayTemp != Js::Constants::NoRegister)
  1068. {
  1069. // We allocated a temp to hold a local frame display value. Use that.
  1070. // It's likely that the FD is on the stack, and we used the temp to load it back.
  1071. regEnv = frameDisplayTemp;
  1072. }
  1073. else if (funcInfoParent->frameDisplayRegister != Js::Constants::NoRegister)
  1074. {
  1075. // This function has built a frame display, so pass it down.
  1076. regEnv = funcInfoParent->frameDisplayRegister;
  1077. }
  1078. else
  1079. {
  1080. // This function has no captured locals but inherits a closure environment, so pass it down.
  1081. regEnv = funcInfoParent->GetEnvRegister();
  1082. }
  1083. regEnv = this->PrependLocalScopes(regEnv, Js::Constants::NoRegister, funcInfoParent);
  1084. }
  1085. // AssertMsg(funcInfo->nonLocalSymbols == 0 || regEnv != funcInfoParent->nullConstantRegister,
  1086. // "We need a closure for the nested function");
  1087. Assert(pnodeFnc->nestedIndex != (uint)-1);
  1088. // If we are in a parameter scope and it is not merged with body scope then we have to create the child function as an inner function
  1089. if (regEnv == funcInfoParent->frameDisplayRegister || regEnv == funcInfoParent->GetEnvRegister())
  1090. {
  1091. m_writer.NewFunction(pnodeFnc->location, pnodeFnc->nestedIndex, pnodeFnc->IsCoroutine(), pnodeFnc->GetHomeObjLocation());
  1092. }
  1093. else
  1094. {
  1095. m_writer.NewInnerFunction(pnodeFnc->location, pnodeFnc->nestedIndex, regEnv, pnodeFnc->IsCoroutine(), pnodeFnc->GetHomeObjLocation());
  1096. }
  1097. if (funcInfoParent->IsGlobalFunction() && (this->flags & fscrEval))
  1098. {
  1099. // A function declared at global scope in eval is untrackable,
  1100. // so make sure the caller's cached scope is invalidated.
  1101. this->funcEscapes = true;
  1102. }
  1103. else
  1104. {
  1105. if (pnodeFnc->IsDeclaration())
  1106. {
  1107. Symbol * funcSymbol = pnodeFnc->GetFuncSymbol();
  1108. if (funcSymbol)
  1109. {
  1110. // In the case where a let/const declaration is the same symbol name
  1111. // as the function declaration (shadowing case), the let/const var and
  1112. // the function declaration symbol are the same and share the same flags
  1113. // (particularly, sym->GetIsBlockVar() for this code path).
  1114. //
  1115. // For example:
  1116. // let a = 0; // <-- sym->GetIsBlockVar() = true
  1117. // function b(){} // <-- sym2->GetIsBlockVar() = false
  1118. //
  1119. // let x = 0; // <-- sym3->GetIsBlockVar() = true
  1120. // function x(){} // <-- sym3->GetIsBlockVar() = true
  1121. //
  1122. // In order to tell if the function is actually part
  1123. // of a block scope, we compare against the function scope here.
  1124. // Note that having a function with the same name as a let/const declaration
  1125. // is a redeclaration error, but we're pushing the fix for this out since it's
  1126. // a bit involved.
  1127. Assert(funcInfoParent->GetBodyScope() != nullptr && funcSymbol->GetScope() != nullptr);
  1128. bool isFunctionDeclarationInBlock = funcSymbol->GetIsBlockVar();
  1129. // Track all vars/lets/consts register slot function declarations.
  1130. if (ShouldTrackDebuggerMetadata()
  1131. // If this is a let binding function declaration at global level, we want to
  1132. // be sure to track the register location as well.
  1133. && !(funcInfoParent->IsGlobalFunction() && !isFunctionDeclarationInBlock))
  1134. {
  1135. if (!funcSymbol->IsInSlot(this, funcInfoParent))
  1136. {
  1137. funcInfoParent->byteCodeFunction->GetFunctionBody()->InsertSymbolToRegSlotList(funcSymbol->GetName(), pnodeFnc->location, funcInfoParent->varRegsCount);
  1138. }
  1139. }
  1140. if (isFunctionDeclarationInBlock)
  1141. {
  1142. // We only track inner let bindings for the debugger side.
  1143. this->TrackFunctionDeclarationPropertyForDebugger(funcSymbol, funcInfoParent);
  1144. }
  1145. }
  1146. }
  1147. }
  1148. if (pnodeFnc->IsDefaultModuleExport())
  1149. {
  1150. this->EmitAssignmentToDefaultModuleExport(pnodeFnc, funcInfoParent);
  1151. }
  1152. if (pnodeFnc->pnodeName == nullptr || !generateAssignment)
  1153. {
  1154. return regEnv;
  1155. }
  1156. EmitAssignmentToFuncName(pnodeFnc, this, funcInfoParent);
  1157. return regEnv;
  1158. }
  1159. void ByteCodeGenerator::DefineUserVars(FuncInfo *funcInfo)
  1160. {
  1161. // Initialize scope-wide variables on entry to the scope. TODO: optimize by detecting uses that are always reached
  1162. // by an existing initialization.
  1163. BOOL fGlobal = funcInfo->IsGlobalFunction();
  1164. ParseNode *pnode;
  1165. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1166. // Global declarations need a temp register to hold the init value, but the node shouldn't get a register.
  1167. // Just assign one on the fly and re-use it for all initializations.
  1168. Js::RegSlot tmpReg = fGlobal ? funcInfo->AcquireTmpRegister() : Js::Constants::NoRegister;
  1169. for (pnode = funcInfo->root->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1170. {
  1171. Symbol* sym = pnode->AsParseNodeVar()->sym;
  1172. if (sym != nullptr && !(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  1173. {
  1174. if (sym->IsSpecialSymbol())
  1175. {
  1176. // Special symbols have already had their initial values stored into their registers.
  1177. // In default-argument case we've stored those values into their slot locations, as well.
  1178. // We must do that because a default parameter may access a special symbol through a scope slot.
  1179. // In the non-default-argument case, though, we didn't yet store the values into the
  1180. // slots so let's do that now.
  1181. if (!funcInfo->root->HasNonSimpleParameterList())
  1182. {
  1183. EmitPropStoreForSpecialSymbol(sym->GetLocation(), sym, sym->GetPid(), funcInfo, true);
  1184. if (ShouldTrackDebuggerMetadata() && !sym->IsInSlot(this, funcInfo))
  1185. {
  1186. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), sym->GetLocation(), funcInfo->varRegsCount);
  1187. }
  1188. }
  1189. continue;
  1190. }
  1191. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  1192. {
  1193. // The init node was bound to the catch object, because it's inside a catch and has the
  1194. // same name as the catch object. But we want to define a user var at function scope,
  1195. // so find the right symbol. (We'll still assign the RHS value to the catch object symbol.)
  1196. // This also applies to a var declaration in the same scope as a let declaration.
  1197. #if DBG
  1198. if (sym->IsArguments())
  1199. {
  1200. // There is a block scoped var named arguments
  1201. Assert(!funcInfo->GetHasArguments());
  1202. continue;
  1203. }
  1204. else if (!sym->GetIsCatch())
  1205. {
  1206. // Assert that catch cannot be at function scope and let and var at function scope is redeclaration error.
  1207. Assert(funcInfo->bodyScope != sym->GetScope());
  1208. }
  1209. #endif
  1210. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  1211. Assert(sym && !sym->GetIsCatch() && !sym->GetIsBlockVar());
  1212. }
  1213. if (sym->GetSymbolType() == STVariable && !sym->GetIsModuleExportStorage())
  1214. {
  1215. if (fGlobal)
  1216. {
  1217. Js::PropertyId propertyId = sym->EnsurePosition(this);
  1218. // We do need to initialize some globals to avoid JS errors on loading undefined variables.
  1219. // But we first need to make sure we're not trashing built-ins.
  1220. if (this->flags & fscrEval)
  1221. {
  1222. if (funcInfo->byteCodeFunction->GetIsStrictMode())
  1223. {
  1224. // Check/Init the property of the frame object
  1225. this->m_writer.ElementRootU(Js::OpCode::LdLocalElemUndef,
  1226. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1227. }
  1228. else
  1229. {
  1230. // The check and the init involve the first element in the scope chain.
  1231. this->m_writer.ElementScopedU(
  1232. Js::OpCode::LdElemUndefScoped, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1233. }
  1234. }
  1235. else
  1236. {
  1237. this->m_writer.ElementU(Js::OpCode::LdElemUndef, ByteCodeGenerator::RootObjectRegister,
  1238. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1239. }
  1240. }
  1241. else if (!sym->IsArguments())
  1242. {
  1243. if (sym->NeedsSlotAlloc(this, funcInfo))
  1244. {
  1245. if (!sym->GetHasNonCommittedReference() ||
  1246. (sym->GetHasFuncAssignment() && funcInfo->GetParsedFunctionBody()->DoStackNestedFunc()))
  1247. {
  1248. // No point in trying to optimize if there are no references before we have to commit to slot.
  1249. // And not safe to delay putting a stack function in the slot, since we may miss boxing.
  1250. sym->SetIsCommittedToSlot();
  1251. }
  1252. }
  1253. // Undef-initialize the home location if it is a register (not closure-captured, or else capture
  1254. // is delayed) or a property of an object.
  1255. if ((!sym->GetHasInit() && !sym->IsInSlot(this, funcInfo)) ||
  1256. (funcInfo->bodyScope->GetIsObject() && !funcInfo->GetHasCachedScope()))
  1257. {
  1258. Js::RegSlot reg = sym->GetLocation();
  1259. if (reg == Js::Constants::NoRegister)
  1260. {
  1261. Assert(sym->IsInSlot(this, funcInfo));
  1262. reg = funcInfo->AcquireTmpRegister();
  1263. }
  1264. this->m_writer.Reg1(Js::OpCode::LdUndef, reg);
  1265. this->EmitLocalPropInit(reg, sym, funcInfo);
  1266. if (ShouldTrackDebuggerMetadata() && !sym->GetHasInit() && !sym->IsInSlot(this, funcInfo))
  1267. {
  1268. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), reg, funcInfo->varRegsCount);
  1269. }
  1270. funcInfo->ReleaseTmpRegister(reg);
  1271. }
  1272. }
  1273. else if (ShouldTrackDebuggerMetadata())
  1274. {
  1275. if (!sym->GetHasInit() && !sym->IsInSlot(this, funcInfo))
  1276. {
  1277. Js::RegSlot reg = sym->GetLocation();
  1278. if (reg != Js::Constants::NoRegister)
  1279. {
  1280. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), reg, funcInfo->varRegsCount);
  1281. }
  1282. }
  1283. }
  1284. sym->SetHasInit(TRUE);
  1285. }
  1286. }
  1287. }
  1288. if (tmpReg != Js::Constants::NoRegister)
  1289. {
  1290. funcInfo->ReleaseTmpRegister(tmpReg);
  1291. }
  1292. for (int i = 0; i < funcInfo->nonUserNonTempRegistersToInitialize.Count(); ++i)
  1293. {
  1294. m_writer.Reg1(Js::OpCode::LdUndef, funcInfo->nonUserNonTempRegistersToInitialize.Item(i));
  1295. }
  1296. }
  1297. void ByteCodeGenerator::InitBlockScopedNonTemps(ParseNode *pnode, FuncInfo *funcInfo)
  1298. {
  1299. // Initialize all non-temp register variables on entry to the enclosing func - in particular,
  1300. // those with lifetimes that begin after the start of user code and may not be initialized normally.
  1301. // This protects us from, for instance, trying to restore garbage on bailout.
  1302. // It was originally done in debugger mode only, but we do it always to avoid issues with boxing
  1303. // garbage on exit from jitted loop bodies.
  1304. while (pnode)
  1305. {
  1306. switch (pnode->nop)
  1307. {
  1308. case knopFncDecl:
  1309. {
  1310. // If this is a block-scoped function, initialize it.
  1311. ParseNodeFnc * pnodeFnc = pnode->AsParseNodeFnc();
  1312. ParseNodeVar *pnodeName = pnodeFnc->pnodeName;
  1313. if (!pnodeFnc->IsMethod() && pnodeName != nullptr)
  1314. {
  1315. Symbol *sym = pnodeName->sym;
  1316. Assert(sym);
  1317. if (sym->GetLocation() != Js::Constants::NoRegister &&
  1318. sym->GetScope()->IsBlockScope(funcInfo) &&
  1319. sym->GetScope()->GetFunc() == funcInfo)
  1320. {
  1321. this->m_writer.Reg1(Js::OpCode::LdUndef, sym->GetLocation());
  1322. }
  1323. }
  1324. // No need to recurse to the nested scopes, as they belong to a nested function.
  1325. pnode = pnodeFnc->pnodeNext;
  1326. break;
  1327. }
  1328. case knopBlock:
  1329. {
  1330. ParseNodeBlock * pnodeBlock = pnode->AsParseNodeBlock();
  1331. Scope *scope = pnodeBlock->scope;
  1332. if (scope)
  1333. {
  1334. if (scope->IsBlockScope(funcInfo))
  1335. {
  1336. Js::RegSlot scopeLoc = scope->GetLocation();
  1337. if (scopeLoc != Js::Constants::NoRegister && !funcInfo->IsTmpReg(scopeLoc))
  1338. {
  1339. this->m_writer.Reg1(Js::OpCode::LdUndef, scopeLoc);
  1340. }
  1341. }
  1342. auto fnInit = [this, funcInfo](ParseNode *pnode)
  1343. {
  1344. Symbol *sym = pnode->AsParseNodeVar()->sym;
  1345. if (!sym->IsInSlot(this, funcInfo) && !sym->GetIsGlobal() && !sym->GetIsModuleImport())
  1346. {
  1347. this->m_writer.Reg1(Js::OpCode::InitUndecl, pnode->AsParseNodeVar()->sym->GetLocation());
  1348. }
  1349. };
  1350. IterateBlockScopedVariables(pnodeBlock, fnInit);
  1351. }
  1352. InitBlockScopedNonTemps(pnodeBlock->pnodeScopes, funcInfo);
  1353. pnode = pnodeBlock->pnodeNext;
  1354. break;
  1355. }
  1356. case knopCatch:
  1357. InitBlockScopedNonTemps(pnode->AsParseNodeCatch()->pnodeScopes, funcInfo);
  1358. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  1359. break;
  1360. case knopWith:
  1361. {
  1362. Js::RegSlot withLoc = pnode->location;
  1363. AssertMsg(withLoc != Js::Constants::NoRegister && !funcInfo->IsTmpReg(withLoc),
  1364. "We should put with objects at known stack locations in debug mode");
  1365. this->m_writer.Reg1(Js::OpCode::LdUndef, withLoc);
  1366. InitBlockScopedNonTemps(pnode->AsParseNodeWith()->pnodeScopes, funcInfo);
  1367. pnode = pnode->AsParseNodeWith()->pnodeNext;
  1368. break;
  1369. }
  1370. default:
  1371. Assert(false);
  1372. return;
  1373. }
  1374. }
  1375. }
  1376. void ByteCodeGenerator::EmitScopeObjectInit(FuncInfo *funcInfo)
  1377. {
  1378. Assert(!funcInfo->byteCodeFunction->GetFunctionBody()->DoStackNestedFunc());
  1379. if (!funcInfo->GetHasCachedScope() /* || forcing scope/inner func caching */)
  1380. {
  1381. return;
  1382. }
  1383. Scope* currentScope = funcInfo->GetCurrentChildScope();
  1384. uint slotCount = currentScope->GetScopeSlotCount();
  1385. uint cachedFuncCount = 0;
  1386. Js::PropertyId firstFuncSlot = Js::Constants::NoProperty;
  1387. Js::PropertyId firstVarSlot = Js::Constants::NoProperty;
  1388. uint extraAlloc = UInt32Math::Add(slotCount, Js::ActivationObjectEx::ExtraSlotCount());
  1389. extraAlloc = UInt32Math::Mul(extraAlloc, sizeof(Js::PropertyId));
  1390. // Create and fill the array of local property ID's.
  1391. // They all have slots assigned to them already (if they need them): see StartEmitFunction.
  1392. Js::PropertyIdArray *propIds = funcInfo->GetParsedFunctionBody()->AllocatePropertyIdArrayForFormals(extraAlloc, slotCount, Js::ActivationObjectEx::ExtraSlotCount());
  1393. ParseNodeFnc *pnodeFnc = funcInfo->root;
  1394. if (funcInfo->GetFuncExprNameReference() && pnodeFnc->GetFuncSymbol()->GetScope() == funcInfo->GetBodyScope())
  1395. {
  1396. Symbol::SaveToPropIdArray(pnodeFnc->GetFuncSymbol(), propIds, this);
  1397. }
  1398. if (funcInfo->GetHasArguments())
  1399. {
  1400. // Because the arguments object can access all instances of same-named formals ("function(x,x){...}"),
  1401. // be sure we initialize any duplicate appearances of a formal parameter to "NoProperty".
  1402. Js::PropertyId slot = 0;
  1403. auto initArg = [&](ParseNode *pnode)
  1404. {
  1405. if (pnode->IsVarLetOrConst())
  1406. {
  1407. Symbol *sym = pnode->AsParseNodeVar()->sym;
  1408. Assert(sym);
  1409. if (sym->GetScopeSlot() == slot)
  1410. {
  1411. // This is the last appearance of the formal, so record the ID.
  1412. Symbol::SaveToPropIdArray(sym, propIds, this);
  1413. }
  1414. else
  1415. {
  1416. // This is an earlier duplicate appearance of the formal, so use NoProperty as a placeholder
  1417. // since this slot can't be accessed by name.
  1418. Assert(sym->GetScopeSlot() != Js::Constants::NoProperty && sym->GetScopeSlot() > slot);
  1419. propIds->elements[slot] = Js::Constants::NoProperty;
  1420. }
  1421. }
  1422. else
  1423. {
  1424. // This is for patterns
  1425. propIds->elements[slot] = Js::Constants::NoProperty;
  1426. }
  1427. slot++;
  1428. };
  1429. MapFormalsWithoutRest(pnodeFnc, initArg);
  1430. ParseNodePtr rest = pnodeFnc->pnodeRest;
  1431. if (rest != nullptr && rest->IsVarLetOrConst())
  1432. {
  1433. // If the rest is in the slot - we need to keep that slot.
  1434. Symbol *sym = rest->AsParseNodeVar()->sym;
  1435. if (sym->IsInSlot(this, funcInfo))
  1436. {
  1437. Symbol::SaveToPropIdArray(sym, propIds, this);
  1438. }
  1439. }
  1440. }
  1441. else
  1442. {
  1443. MapFormals(pnodeFnc, [&](ParseNode *pnode)
  1444. {
  1445. if (pnode->IsVarLetOrConst())
  1446. {
  1447. Symbol::SaveToPropIdArray(pnode->AsParseNodeVar()->sym, propIds, this);
  1448. }
  1449. });
  1450. }
  1451. auto saveFunctionVarsToPropIdArray = [&](ParseNode *pnodeFunction)
  1452. {
  1453. if (pnodeFunction->AsParseNodeFnc()->IsDeclaration())
  1454. {
  1455. ParseNode *pnodeName = pnodeFunction->AsParseNodeFnc()->pnodeName;
  1456. if (pnodeName != nullptr)
  1457. {
  1458. while (pnodeName->nop == knopList)
  1459. {
  1460. if (pnodeName->AsParseNodeBin()->pnode1->nop == knopVarDecl)
  1461. {
  1462. Symbol *sym = pnodeName->AsParseNodeBin()->pnode1->AsParseNodeVar()->sym;
  1463. if (sym)
  1464. {
  1465. Symbol::SaveToPropIdArray(sym, propIds, this, &firstFuncSlot);
  1466. }
  1467. }
  1468. pnodeName = pnodeName->AsParseNodeBin()->pnode2;
  1469. }
  1470. if (pnodeName->nop == knopVarDecl)
  1471. {
  1472. Symbol *sym = pnodeName->AsParseNodeVar()->sym;
  1473. if (sym)
  1474. {
  1475. Symbol::SaveToPropIdArray(sym, propIds, this, &firstFuncSlot);
  1476. cachedFuncCount++;
  1477. }
  1478. }
  1479. }
  1480. }
  1481. };
  1482. MapContainerScopeFunctions(pnodeFnc, saveFunctionVarsToPropIdArray);
  1483. if (currentScope->GetScopeType() != ScopeType_Parameter)
  1484. {
  1485. ParseNode *pnode;
  1486. Symbol *sym;
  1487. for (pnode = pnodeFnc->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1488. {
  1489. sym = pnode->AsParseNodeVar()->sym;
  1490. if (!(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  1491. {
  1492. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  1493. {
  1494. sym = currentScope->FindLocalSymbol(sym->GetName());
  1495. }
  1496. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1497. }
  1498. }
  1499. ParseNodeBlock *pnodeBlock = pnodeFnc->pnodeScopes;
  1500. for (pnode = pnodeBlock->pnodeLexVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1501. {
  1502. sym = pnode->AsParseNodeVar()->sym;
  1503. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1504. }
  1505. pnodeBlock = pnodeFnc->pnodeBodyScope;
  1506. for (pnode = pnodeBlock->pnodeLexVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1507. {
  1508. sym = pnode->AsParseNodeVar()->sym;
  1509. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1510. }
  1511. }
  1512. else
  1513. {
  1514. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  1515. }
  1516. // Write the first func slot and first var slot into the auxiliary data
  1517. Js::PropertyId *slots = propIds->elements + slotCount;
  1518. slots[0] = cachedFuncCount;
  1519. slots[1] = firstFuncSlot;
  1520. slots[2] = firstVarSlot;
  1521. slots[3] = funcInfo->GetParsedFunctionBody()->NewObjectLiteral();
  1522. propIds->hasNonSimpleParams = funcInfo->root->HasNonSimpleParameterList();
  1523. funcInfo->GetParsedFunctionBody()->SetHasCachedScopePropIds(true);
  1524. }
  1525. void ByteCodeGenerator::SetClosureRegisters(FuncInfo* funcInfo, Js::FunctionBody* byteCodeFunction)
  1526. {
  1527. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  1528. {
  1529. byteCodeFunction->MapAndSetLocalFrameDisplayRegister(funcInfo->frameDisplayRegister);
  1530. }
  1531. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  1532. {
  1533. byteCodeFunction->MapAndSetLocalClosureRegister(funcInfo->frameObjRegister);
  1534. byteCodeFunction->SetHasScopeObject(true);
  1535. }
  1536. else if (funcInfo->frameSlotsRegister != Js::Constants::NoRegister)
  1537. {
  1538. byteCodeFunction->MapAndSetLocalClosureRegister(funcInfo->frameSlotsRegister);
  1539. }
  1540. if (funcInfo->paramSlotsRegister != Js::Constants::NoRegister)
  1541. {
  1542. byteCodeFunction->MapAndSetParamClosureRegister(funcInfo->paramSlotsRegister);
  1543. }
  1544. }
  1545. void ByteCodeGenerator::FinalizeRegisters(FuncInfo* funcInfo, Js::FunctionBody* byteCodeFunction)
  1546. {
  1547. if (funcInfo->NeedEnvRegister())
  1548. {
  1549. bool constReg = !funcInfo->GetIsTopLevelEventHandler() && funcInfo->IsGlobalFunction() && !(this->flags & fscrEval);
  1550. funcInfo->AssignEnvRegister(constReg);
  1551. }
  1552. // Set the function body's constant count before emitting anything so that the byte code writer
  1553. // can distinguish constants from variables.
  1554. byteCodeFunction->CheckAndSetConstantCount(funcInfo->constRegsCount);
  1555. this->SetClosureRegisters(funcInfo, byteCodeFunction);
  1556. if (this->IsInDebugMode() || byteCodeFunction->IsCoroutine())
  1557. {
  1558. // Give permanent registers to the inner scopes in debug mode.
  1559. // TODO: We create seperate debuggerscopes for each block which has own scope. These are stored in the var registers
  1560. // allocated below. Ideally we should change this logic to not allocate separate registers for these and save the debug
  1561. // info in corresponding symbols and use it from there. This will also affect the temp register allocation logic in
  1562. // EmitOneFunction.
  1563. uint innerScopeCount = funcInfo->InnerScopeCount();
  1564. byteCodeFunction->SetInnerScopeCount(innerScopeCount);
  1565. if (innerScopeCount)
  1566. {
  1567. funcInfo->SetFirstInnerScopeReg(funcInfo->NextVarRegister());
  1568. for (uint i = 1; i < innerScopeCount; i++)
  1569. {
  1570. funcInfo->NextVarRegister();
  1571. }
  1572. }
  1573. }
  1574. // NOTE: The FunctionBody expects the yield reg to be the final non-temp.
  1575. if (byteCodeFunction->IsCoroutine())
  1576. {
  1577. if (funcInfo->root->IsAsync())
  1578. {
  1579. funcInfo->AssignAwaitRegister();
  1580. }
  1581. funcInfo->AssignYieldRegister();
  1582. }
  1583. Js::RegSlot firstTmpReg = funcInfo->varRegsCount;
  1584. funcInfo->SetFirstTmpReg(firstTmpReg);
  1585. byteCodeFunction->SetFirstTmpReg(funcInfo->RegCount());
  1586. }
  1587. void ByteCodeGenerator::InitScopeSlotArray(FuncInfo * funcInfo)
  1588. {
  1589. // Record slots info for ScopeSlots/ScopeObject.
  1590. uint scopeSlotCount = funcInfo->bodyScope->GetScopeSlotCount();
  1591. bool isSplitScope = !funcInfo->IsBodyAndParamScopeMerged();
  1592. Assert(funcInfo->paramScope == nullptr || funcInfo->paramScope->GetScopeSlotCount() == 0 || isSplitScope);
  1593. uint scopeSlotCountForParamScope = funcInfo->paramScope != nullptr ? funcInfo->paramScope->GetScopeSlotCount() : 0;
  1594. if (scopeSlotCount == 0 && scopeSlotCountForParamScope == 0)
  1595. {
  1596. return;
  1597. }
  1598. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1599. if (scopeSlotCount > 0 || scopeSlotCountForParamScope > 0)
  1600. {
  1601. byteCodeFunction->SetScopeSlotArraySizes(scopeSlotCount, scopeSlotCountForParamScope);
  1602. }
  1603. // TODO: Need to add property ids for the case when scopeSlotCountForParamSCope is non-zero
  1604. if (scopeSlotCount)
  1605. {
  1606. Js::PropertyId *propertyIdsForScopeSlotArray = RecyclerNewArrayLeafZ(scriptContext->GetRecycler(), Js::PropertyId, scopeSlotCount);
  1607. byteCodeFunction->SetPropertyIdsForScopeSlotArray(propertyIdsForScopeSlotArray, scopeSlotCount, scopeSlotCountForParamScope);
  1608. AssertMsg(!byteCodeFunction->IsReparsed() || byteCodeFunction->WasEverAsmJsMode() || byteCodeFunction->scopeSlotArraySize == scopeSlotCount,
  1609. "The slot array size is different between debug and non-debug mode");
  1610. #if DEBUG
  1611. for (UINT i = 0; i < scopeSlotCount; i++)
  1612. {
  1613. propertyIdsForScopeSlotArray[i] = Js::Constants::NoProperty;
  1614. }
  1615. #endif
  1616. auto setPropertyIdForScopeSlotArray =
  1617. [scopeSlotCount, propertyIdsForScopeSlotArray]
  1618. (Js::PropertyId slot, Js::PropertyId propId)
  1619. {
  1620. if (slot < 0 || (uint)slot >= scopeSlotCount)
  1621. {
  1622. Js::Throw::FatalInternalError();
  1623. }
  1624. propertyIdsForScopeSlotArray[slot] = propId;
  1625. };
  1626. auto setPropIdsForScopeSlotArray = [this, funcInfo, setPropertyIdForScopeSlotArray](Symbol *const sym)
  1627. {
  1628. if (sym->NeedsSlotAlloc(this, funcInfo))
  1629. {
  1630. // All properties should get correct propertyId here.
  1631. Assert(sym->HasScopeSlot()); // We can't allocate scope slot now. Any symbol needing scope slot must have allocated it before this point.
  1632. setPropertyIdForScopeSlotArray(sym->GetScopeSlot(), sym->EnsurePosition(funcInfo));
  1633. }
  1634. };
  1635. funcInfo->GetBodyScope()->ForEachSymbol(setPropIdsForScopeSlotArray);
  1636. #if DEBUG
  1637. for (UINT i = 0; i < scopeSlotCount; i++)
  1638. {
  1639. Assert(propertyIdsForScopeSlotArray[i] != Js::Constants::NoProperty
  1640. || funcInfo->frameObjRegister != Js::Constants::NoRegister); // ScopeObject may have unassigned entries, e.g. for same-named parameters
  1641. }
  1642. #endif
  1643. }
  1644. }
  1645. // temporarily load all constants and special registers in a single block
  1646. void ByteCodeGenerator::LoadAllConstants(FuncInfo *funcInfo)
  1647. {
  1648. Symbol *sym;
  1649. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1650. byteCodeFunction->CreateConstantTable();
  1651. if (funcInfo->nullConstantRegister != Js::Constants::NoRegister)
  1652. {
  1653. byteCodeFunction->RecordNullObject(byteCodeFunction->MapRegSlot(funcInfo->nullConstantRegister));
  1654. }
  1655. if (funcInfo->undefinedConstantRegister != Js::Constants::NoRegister)
  1656. {
  1657. byteCodeFunction->RecordUndefinedObject(byteCodeFunction->MapRegSlot(funcInfo->undefinedConstantRegister));
  1658. }
  1659. if (funcInfo->trueConstantRegister != Js::Constants::NoRegister)
  1660. {
  1661. byteCodeFunction->RecordTrueObject(byteCodeFunction->MapRegSlot(funcInfo->trueConstantRegister));
  1662. }
  1663. if (funcInfo->falseConstantRegister != Js::Constants::NoRegister)
  1664. {
  1665. byteCodeFunction->RecordFalseObject(byteCodeFunction->MapRegSlot(funcInfo->falseConstantRegister));
  1666. }
  1667. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  1668. {
  1669. m_writer.RecordObjectRegister(funcInfo->frameObjRegister);
  1670. if (!funcInfo->GetApplyEnclosesArgs())
  1671. {
  1672. this->EmitScopeObjectInit(funcInfo);
  1673. }
  1674. #if DBG
  1675. uint count = 0;
  1676. funcInfo->GetBodyScope()->ForEachSymbol([&](Symbol *const sym)
  1677. {
  1678. if (sym->NeedsSlotAlloc(this, funcInfo))
  1679. {
  1680. // All properties should get correct propertyId here.
  1681. count++;
  1682. }
  1683. });
  1684. if (funcInfo->GetParamScope() != nullptr)
  1685. {
  1686. funcInfo->GetParamScope()->ForEachSymbol([&](Symbol *const sym)
  1687. {
  1688. if (sym->NeedsSlotAlloc(this, funcInfo))
  1689. {
  1690. // All properties should get correct propertyId here.
  1691. count++;
  1692. }
  1693. });
  1694. }
  1695. // A reparse should result in the same size of the activation object.
  1696. // Exclude functions which were created from the ByteCodeCache.
  1697. AssertMsg(!byteCodeFunction->IsReparsed() || byteCodeFunction->HasGeneratedFromByteCodeCache() ||
  1698. byteCodeFunction->scopeObjectSize == count || byteCodeFunction->WasEverAsmJsMode(),
  1699. "The activation object size is different between debug and non-debug mode");
  1700. byteCodeFunction->scopeObjectSize = count;
  1701. #endif
  1702. }
  1703. else if (funcInfo->frameSlotsRegister != Js::Constants::NoRegister)
  1704. {
  1705. int scopeSlotCount = funcInfo->bodyScope->GetScopeSlotCount();
  1706. int paramSlotCount = funcInfo->paramScope->GetScopeSlotCount();
  1707. if (scopeSlotCount == 0 && paramSlotCount == 0)
  1708. {
  1709. AssertMsg(funcInfo->frameDisplayRegister != Js::Constants::NoRegister, "Why do we need scope slots?");
  1710. m_writer.Reg1(Js::OpCode::LdC_A_Null, funcInfo->frameSlotsRegister);
  1711. }
  1712. }
  1713. if (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject())
  1714. {
  1715. byteCodeFunction->MapAndSetFuncExprScopeRegister(funcInfo->funcExprScope->GetLocation());
  1716. byteCodeFunction->SetEnvDepth((uint16)-1);
  1717. }
  1718. bool thisLoadedFromParams = false;
  1719. if (funcInfo->NeedEnvRegister())
  1720. {
  1721. byteCodeFunction->MapAndSetEnvRegister(funcInfo->GetEnvRegister());
  1722. if (funcInfo->GetIsTopLevelEventHandler())
  1723. {
  1724. if (funcInfo->GetThisSymbol())
  1725. {
  1726. byteCodeFunction->MapAndSetThisRegisterForEventHandler(funcInfo->GetThisSymbol()->GetLocation());
  1727. }
  1728. // The environment is the namespace hierarchy starting with "this".
  1729. Assert(!funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1730. thisLoadedFromParams = true;
  1731. this->InvalidateCachedOuterScopes(funcInfo);
  1732. }
  1733. else if (funcInfo->IsGlobalFunction() && !(this->flags & fscrEval))
  1734. {
  1735. Assert(funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1736. if (funcInfo->GetIsStrictMode())
  1737. {
  1738. byteCodeFunction->RecordStrictNullDisplayConstant(byteCodeFunction->MapRegSlot(funcInfo->GetEnvRegister()));
  1739. }
  1740. else
  1741. {
  1742. byteCodeFunction->RecordNullDisplayConstant(byteCodeFunction->MapRegSlot(funcInfo->GetEnvRegister()));
  1743. }
  1744. }
  1745. else
  1746. {
  1747. // environment may be required to load "this"
  1748. Assert(!funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1749. this->InvalidateCachedOuterScopes(funcInfo);
  1750. }
  1751. }
  1752. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  1753. {
  1754. m_writer.RecordFrameDisplayRegister(funcInfo->frameDisplayRegister);
  1755. }
  1756. this->RecordAllIntConstants(funcInfo);
  1757. this->RecordAllStrConstants(funcInfo);
  1758. this->RecordAllBigIntConstants(funcInfo);
  1759. this->RecordAllStringTemplateCallsiteConstants(funcInfo);
  1760. funcInfo->doubleConstantToRegister.Map([byteCodeFunction](double d, Js::RegSlot location)
  1761. {
  1762. byteCodeFunction->RecordFloatConstant(byteCodeFunction->MapRegSlot(location), d);
  1763. });
  1764. // WARNING !!!
  1765. // DO NOT emit any bytecode before loading the heap arguments. This is because those opcodes may bail
  1766. // out (unlikely, since opcodes emitted in this function should not correspond to user code, but possible)
  1767. // and the Jit assumes that there cannot be any bailouts before LdHeapArguments (or its equivalent)
  1768. if (funcInfo->GetHasArguments())
  1769. {
  1770. sym = funcInfo->GetArgumentsSymbol();
  1771. Assert(sym);
  1772. Assert(funcInfo->GetHasHeapArguments());
  1773. if (funcInfo->GetCallsEval() || (!funcInfo->GetApplyEnclosesArgs()))
  1774. {
  1775. this->LoadHeapArguments(funcInfo);
  1776. }
  1777. }
  1778. else if (!funcInfo->IsGlobalFunction() && !IsInNonDebugMode())
  1779. {
  1780. uint count = funcInfo->inArgsCount + (funcInfo->root->pnodeRest != nullptr ? 1 : 0) - 1;
  1781. if (count != 0)
  1782. {
  1783. Js::PropertyIdArray *propIds = RecyclerNewPlus(scriptContext->GetRecycler(), UInt32Math::Mul(count, sizeof(Js::PropertyId)), Js::PropertyIdArray, count, 0);
  1784. GetFormalArgsArray(this, funcInfo, propIds);
  1785. byteCodeFunction->SetPropertyIdsOfFormals(propIds);
  1786. }
  1787. }
  1788. // Class constructors do not have a [[call]] slot but we don't implement a generic way to express this.
  1789. // What we do is emit a check for the new flag here. If we don't have CallFlags_New set, the opcode will throw.
  1790. // We need to do this before emitting 'this' since the base class constructor will try to construct a new object.
  1791. if (funcInfo->IsClassConstructor())
  1792. {
  1793. m_writer.Empty(Js::OpCode::ChkNewCallFlag);
  1794. }
  1795. // new.target may be used to construct the 'this' register so make sure to load it first
  1796. if (funcInfo->GetNewTargetSymbol())
  1797. {
  1798. this->LoadNewTargetObject(funcInfo);
  1799. }
  1800. if (funcInfo->GetThisSymbol())
  1801. {
  1802. this->LoadThisObject(funcInfo, thisLoadedFromParams);
  1803. }
  1804. else if (ShouldLoadConstThis(funcInfo))
  1805. {
  1806. this->EmitThis(funcInfo, funcInfo->thisConstantRegister, funcInfo->nullConstantRegister);
  1807. }
  1808. if (funcInfo->GetSuperSymbol())
  1809. {
  1810. this->LoadSuperObject(funcInfo);
  1811. }
  1812. if (funcInfo->GetSuperConstructorSymbol())
  1813. {
  1814. this->LoadSuperConstructorObject(funcInfo);
  1815. }
  1816. if (funcInfo->GetImportMetaSymbol())
  1817. {
  1818. this->LoadImportMetaObject(funcInfo);
  1819. }
  1820. //
  1821. // If the function is a function expression with a name,
  1822. // load the function object at runtime to its activation object.
  1823. //
  1824. sym = funcInfo->root->GetFuncSymbol();
  1825. bool funcExprWithName = !funcInfo->IsGlobalFunction() && sym && sym->GetIsFuncExpr();
  1826. if (funcExprWithName)
  1827. {
  1828. if (funcInfo->GetFuncExprNameReference() ||
  1829. (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject()))
  1830. {
  1831. //
  1832. // x = function f(...) { ... }
  1833. // A named function expression's name (Symbol:f) belongs to the enclosing scope.
  1834. // Thus there are no uses of 'f' within the scope of the function (as references to 'f'
  1835. // are looked up in the closure). So, we can't use f's register as it is from the enclosing
  1836. // scope's register namespace. So use a tmp register.
  1837. // In ES5 mode though 'f' is *not* a part of the enclosing scope. So we always assign 'f' a register
  1838. // from it's register namespace, which LdFuncExpr can use.
  1839. //
  1840. Js::RegSlot ldFuncExprDst = sym->GetLocation();
  1841. this->m_writer.Reg1(Js::OpCode::LdFuncExpr, ldFuncExprDst);
  1842. if (sym->IsInSlot(this, funcInfo))
  1843. {
  1844. Js::RegSlot scopeLocation;
  1845. AnalysisAssert(funcInfo->funcExprScope);
  1846. if (funcInfo->funcExprScope->GetIsObject())
  1847. {
  1848. scopeLocation = funcInfo->funcExprScope->GetLocation();
  1849. this->m_writer.Property(Js::OpCode::StFuncExpr, sym->GetLocation(), scopeLocation,
  1850. funcInfo->FindOrAddReferencedPropertyId(sym->GetPosition()));
  1851. }
  1852. else if (funcInfo->paramScope->GetIsObject() || (funcInfo->paramScope->GetCanMerge() && funcInfo->bodyScope->GetIsObject()))
  1853. {
  1854. this->m_writer.ElementU(Js::OpCode::StLocalFuncExpr, sym->GetLocation(),
  1855. funcInfo->FindOrAddReferencedPropertyId(sym->GetPosition()));
  1856. }
  1857. else
  1858. {
  1859. Assert(sym->HasScopeSlot());
  1860. this->m_writer.SlotI1(Js::OpCode::StLocalSlot, sym->GetLocation(),
  1861. sym->GetScopeSlot() + Js::ScopeSlots::FirstSlotIndex);
  1862. }
  1863. }
  1864. else if (ShouldTrackDebuggerMetadata())
  1865. {
  1866. funcInfo->byteCodeFunction->GetFunctionBody()->InsertSymbolToRegSlotList(sym->GetName(), sym->GetLocation(), funcInfo->varRegsCount);
  1867. }
  1868. }
  1869. }
  1870. }
  1871. void ByteCodeGenerator::InvalidateCachedOuterScopes(FuncInfo *funcInfo)
  1872. {
  1873. Assert(funcInfo->GetEnvRegister() != Js::Constants::NoRegister);
  1874. // Walk the scope stack, from funcInfo outward, looking for scopes that have been cached.
  1875. Scope *scope = funcInfo->GetBodyScope()->GetEnclosingScope();
  1876. uint32 envIndex = 0;
  1877. while (scope && scope->GetFunc() == funcInfo)
  1878. {
  1879. // Skip over FuncExpr Scope and parameter scope for current funcInfo to get to the first enclosing scope of the outer function.
  1880. scope = scope->GetEnclosingScope();
  1881. }
  1882. for (; scope; scope = scope->GetEnclosingScope())
  1883. {
  1884. FuncInfo *func = scope->GetFunc();
  1885. if (scope == func->GetBodyScope())
  1886. {
  1887. if (func->Escapes() && func->GetHasCachedScope())
  1888. {
  1889. AssertOrFailFast(scope->GetIsObject());
  1890. this->m_writer.Unsigned1(Js::OpCode::InvalCachedScope, envIndex);
  1891. }
  1892. }
  1893. if (scope->GetMustInstantiate())
  1894. {
  1895. envIndex++;
  1896. }
  1897. }
  1898. }
  1899. void ByteCodeGenerator::LoadThisObject(FuncInfo *funcInfo, bool thisLoadedFromParams)
  1900. {
  1901. Symbol* thisSym = funcInfo->GetThisSymbol();
  1902. Assert(thisSym);
  1903. Assert(!funcInfo->IsLambda());
  1904. if (funcInfo->IsClassConstructor())
  1905. {
  1906. // Derived class constructors initialize 'this' to be Undecl
  1907. // - we'll check this value during a super call and during 'this' access
  1908. //
  1909. // Base class constructors initialize 'this' to a new object using new.target
  1910. if (funcInfo->IsBaseClassConstructor())
  1911. {
  1912. Symbol* newTargetSym = funcInfo->GetNewTargetSymbol();
  1913. Assert(newTargetSym);
  1914. this->Writer()->Reg2(Js::OpCode::NewScObjectNoCtorFull, thisSym->GetLocation(), newTargetSym->GetLocation());
  1915. }
  1916. else
  1917. {
  1918. this->m_writer.Reg1(Js::OpCode::InitUndecl, thisSym->GetLocation());
  1919. }
  1920. }
  1921. else if (!funcInfo->IsGlobalFunction())
  1922. {
  1923. //
  1924. // thisLoadedFromParams would be true for the event Handler case,
  1925. // "this" would have been loaded from parameters to put in the environment
  1926. //
  1927. if (funcInfo->GetIsStrictMode())
  1928. {
  1929. m_writer.ArgIn0(thisSym->GetLocation());
  1930. }
  1931. else if (!thisLoadedFromParams)
  1932. {
  1933. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  1934. m_writer.ArgIn0(tmpReg);
  1935. EmitThis(funcInfo, thisSym->GetLocation(), tmpReg);
  1936. funcInfo->ReleaseTmpRegister(tmpReg);
  1937. }
  1938. else
  1939. {
  1940. EmitThis(funcInfo, thisSym->GetLocation(), thisSym->GetLocation());
  1941. }
  1942. }
  1943. else
  1944. {
  1945. Assert(funcInfo->IsGlobalFunction());
  1946. Js::RegSlot root = funcInfo->nullConstantRegister;
  1947. EmitThis(funcInfo, thisSym->GetLocation(), root);
  1948. }
  1949. }
  1950. void ByteCodeGenerator::LoadNewTargetObject(FuncInfo *funcInfo)
  1951. {
  1952. Symbol* newTargetSym = funcInfo->GetNewTargetSymbol();
  1953. Assert(newTargetSym);
  1954. if (funcInfo->IsClassConstructor())
  1955. {
  1956. Assert(!funcInfo->IsLambda());
  1957. m_writer.ArgIn0(newTargetSym->GetLocation());
  1958. }
  1959. else if (funcInfo->IsGlobalFunction())
  1960. {
  1961. m_writer.Reg1(Js::OpCode::LdUndef, newTargetSym->GetLocation());
  1962. }
  1963. else
  1964. {
  1965. m_writer.Reg1(Js::OpCode::LdNewTarget, newTargetSym->GetLocation());
  1966. }
  1967. }
  1968. void ByteCodeGenerator::LoadImportMetaObject(FuncInfo* funcInfo)
  1969. {
  1970. Symbol* importMetaSym = funcInfo->GetImportMetaSymbol();
  1971. Assert(importMetaSym);
  1972. m_writer.Reg1Unsigned1(Js::OpCode::LdImportMeta, importMetaSym->GetLocation(), this->GetModuleID());
  1973. }
  1974. void ByteCodeGenerator::LoadSuperConstructorObject(FuncInfo *funcInfo)
  1975. {
  1976. Symbol* superConstructorSym = funcInfo->GetSuperConstructorSymbol();
  1977. Assert(superConstructorSym);
  1978. Assert(!funcInfo->IsLambda());
  1979. if (funcInfo->IsDerivedClassConstructor())
  1980. {
  1981. m_writer.Reg1(Js::OpCode::LdFuncObj, superConstructorSym->GetLocation());
  1982. }
  1983. else
  1984. {
  1985. m_writer.Reg1(Js::OpCode::LdUndef, superConstructorSym->GetLocation());
  1986. }
  1987. }
  1988. void ByteCodeGenerator::LoadSuperObject(FuncInfo *funcInfo)
  1989. {
  1990. Symbol* superSym = funcInfo->GetSuperSymbol();
  1991. Assert(superSym);
  1992. Assert(!funcInfo->IsLambda());
  1993. m_writer.Reg1(Js::OpCode::LdHomeObj, superSym->GetLocation());
  1994. }
  1995. void ByteCodeGenerator::EmitSuperCall(FuncInfo* funcInfo, ParseNodeSuperCall * pnodeSuperCall, BOOL fReturnValue, BOOL fEvaluateComponents)
  1996. {
  1997. FuncInfo* nonLambdaFunc = funcInfo;
  1998. bool isResultUsed = pnodeSuperCall->isUsed;
  1999. if (funcInfo->IsLambda())
  2000. {
  2001. nonLambdaFunc = this->FindEnclosingNonLambda();
  2002. }
  2003. if (nonLambdaFunc->IsBaseClassConstructor())
  2004. {
  2005. // super() is not allowed in base class constructors. If we detect this, emit a ReferenceError and skip making the call.
  2006. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_ClassSuperInBaseClass));
  2007. return;
  2008. }
  2009. pnodeSuperCall->isUsed = true;
  2010. // pnode->location refers to two things: the result of the inner function call (`temp` in the pseudocode below),
  2011. // and the result of the super() expression itself
  2012. funcInfo->AcquireLoc(pnodeSuperCall);
  2013. // We need to emit 'this' directly so we can skip throwing a reference error if 'this' is currently undecl (we want to get undecl if 'this' is undecl)
  2014. funcInfo->AcquireLoc(pnodeSuperCall->pnodeThis);
  2015. EmitPropLoadThis(pnodeSuperCall->pnodeThis->location, pnodeSuperCall->pnodeThis, funcInfo, false);
  2016. EmitLoad(pnodeSuperCall->pnodeNewTarget, this, funcInfo);
  2017. Assert(pnodeSuperCall->isSuperCall);
  2018. EmitLoad(pnodeSuperCall->pnodeTarget, this, funcInfo);
  2019. //
  2020. // if (super is class constructor) {
  2021. // _this = new.target;
  2022. // } else {
  2023. // _this = NewScObjFull(new.target);
  2024. // }
  2025. //
  2026. // temp = super.call(_this, new.target); // CallFlag_New | CallFlag_NewTarget | CallFlag_ExtraArg
  2027. // if (temp is object) {
  2028. // _this = temp;
  2029. // }
  2030. //
  2031. // if (UndeclBlockVar === this) {
  2032. // this = _this;
  2033. // } else {
  2034. // throw ReferenceError;
  2035. // }
  2036. //
  2037. Js::RegSlot thisForSuperCall = funcInfo->AcquireTmpRegister();
  2038. Js::RegSlot valueForThis = funcInfo->AcquireTmpRegister();
  2039. Js::RegSlot tmpUndeclReg = funcInfo->AcquireTmpRegister();
  2040. Js::ByteCodeLabel useNewTargetForThisLabel = this->Writer()->DefineLabel();
  2041. Js::ByteCodeLabel makeCallLabel = this->Writer()->DefineLabel();
  2042. Js::ByteCodeLabel useSuperCallResultLabel = this->Writer()->DefineLabel();
  2043. Js::ByteCodeLabel doneLabel = this->Writer()->DefineLabel();
  2044. Js::RegSlot tmpReg = this->EmitLdObjProto(Js::OpCode::LdFuncObjProto, pnodeSuperCall->pnodeTarget->location, funcInfo);
  2045. this->Writer()->BrReg1(Js::OpCode::BrOnClassConstructor, useNewTargetForThisLabel, tmpReg);
  2046. this->Writer()->Reg2(Js::OpCode::NewScObjectNoCtorFull, thisForSuperCall, pnodeSuperCall->pnodeNewTarget->location);
  2047. this->Writer()->Br(Js::OpCode::Br, makeCallLabel);
  2048. this->Writer()->MarkLabel(useNewTargetForThisLabel);
  2049. this->Writer()->Reg2(Js::OpCode::Ld_A_ReuseLoc, thisForSuperCall, pnodeSuperCall->pnodeNewTarget->location);
  2050. this->Writer()->MarkLabel(makeCallLabel);
  2051. EmitCall(pnodeSuperCall, this, funcInfo, fReturnValue, fEvaluateComponents, thisForSuperCall, pnodeSuperCall->pnodeNewTarget->location);
  2052. // We have to use another temp for the this value before assigning to this register.
  2053. // This is because IRBuilder does not expect us to use the value of a temp after potentially assigning to that same temp.
  2054. // Ex:
  2055. // _this = new.target;
  2056. // temp = super.call(_this);
  2057. // if (temp is object) {
  2058. // _this = temp; // creates a new sym for _this as it was previously used
  2059. // }
  2060. // this = _this; // tries to loads a value from the old sym (which is dead)
  2061. this->Writer()->BrReg1(Js::OpCode::BrOnObject_A, useSuperCallResultLabel, pnodeSuperCall->location);
  2062. this->Writer()->Reg2(Js::OpCode::Ld_A, valueForThis, thisForSuperCall);
  2063. this->Writer()->Br(Js::OpCode::Br, doneLabel);
  2064. this->Writer()->MarkLabel(useSuperCallResultLabel);
  2065. this->Writer()->Reg2(Js::OpCode::Ld_A_ReuseLoc, valueForThis, pnodeSuperCall->location);
  2066. this->Writer()->MarkLabel(doneLabel);
  2067. // The call is done and we know what we will bind to 'this' so let's check to see if 'this' is already decl.
  2068. Js::ByteCodeLabel skipLabel = this->Writer()->DefineLabel();
  2069. this->Writer()->Reg1(Js::OpCode::InitUndecl, tmpUndeclReg);
  2070. this->Writer()->BrReg2(Js::OpCode::BrSrEq_A, skipLabel, pnodeSuperCall->pnodeThis->location, tmpUndeclReg);
  2071. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_ClassThisAlreadyAssigned));
  2072. this->Writer()->MarkLabel(skipLabel);
  2073. // If calling code cares about the return value, then move the selected `this` value into the result register.
  2074. if (isResultUsed)
  2075. {
  2076. this->Writer()->Reg2(Js::OpCode::Ld_A, pnodeSuperCall->location, valueForThis);
  2077. }
  2078. Symbol* thisSym = pnodeSuperCall->pnodeThis->sym;
  2079. this->Writer()->Reg2(Js::OpCode::Ld_A, pnodeSuperCall->pnodeThis->location, valueForThis);
  2080. EmitPropStoreForSpecialSymbol(pnodeSuperCall->pnodeThis->location, thisSym, pnodeSuperCall->pnodeThis->pid, funcInfo, false);
  2081. funcInfo->ReleaseTmpRegister(tmpUndeclReg);
  2082. funcInfo->ReleaseTmpRegister(valueForThis);
  2083. funcInfo->ReleaseTmpRegister(thisForSuperCall);
  2084. funcInfo->ReleaseLoc(pnodeSuperCall->pnodeTarget);
  2085. funcInfo->ReleaseLoc(pnodeSuperCall->pnodeNewTarget);
  2086. funcInfo->ReleaseLoc(pnodeSuperCall->pnodeThis);
  2087. }
  2088. void ByteCodeGenerator::EmitClassConstructorEndCode(FuncInfo *funcInfo)
  2089. {
  2090. Symbol* thisSym = funcInfo->GetThisSymbol();
  2091. if (thisSym && thisSym->GetLocation() != Js::Constants::NoRegister)
  2092. {
  2093. EmitPropLoad(ByteCodeGenerator::ReturnRegister, thisSym, thisSym->GetPid(), funcInfo, true);
  2094. this->m_writer.Reg1(Js::OpCode::ChkUndecl, ByteCodeGenerator::ReturnRegister);
  2095. }
  2096. }
  2097. void ByteCodeGenerator::EmitThis(FuncInfo *funcInfo, Js::RegSlot lhsLocation, Js::RegSlot fromRegister)
  2098. {
  2099. if (funcInfo->byteCodeFunction->GetIsStrictMode() && !funcInfo->IsGlobalFunction() && !funcInfo->IsLambda())
  2100. {
  2101. if (lhsLocation != fromRegister)
  2102. {
  2103. m_writer.Reg2(Js::OpCode::Ld_A, lhsLocation, fromRegister);
  2104. }
  2105. }
  2106. else
  2107. {
  2108. m_writer.Reg2Int1(Js::OpCode::LdThis, lhsLocation, fromRegister, this->GetModuleID());
  2109. }
  2110. }
  2111. void ByteCodeGenerator::EmitLoadFormalIntoRegister(ParseNode *pnodeFormal, Js::RegSlot pos, FuncInfo *funcInfo)
  2112. {
  2113. if (pnodeFormal->IsVarLetOrConst())
  2114. {
  2115. // Get the param from its argument position into its assigned register.
  2116. // The position should match the location, otherwise, it has been shadowed by parameter with the same name
  2117. Symbol *formal = pnodeFormal->AsParseNodeVar()->sym;
  2118. if (formal->GetLocation() + 1 == pos)
  2119. {
  2120. // Transfer to the frame object, etc., if necessary.
  2121. this->EmitLocalPropInit(formal->GetLocation(), formal, funcInfo);
  2122. }
  2123. }
  2124. }
  2125. void ByteCodeGenerator::HomeArguments(FuncInfo *funcInfo)
  2126. {
  2127. if (ShouldTrackDebuggerMetadata())
  2128. {
  2129. // Add formals to the debugger propertyidcontainer for reg slots
  2130. auto addFormalsToPropertyIdContainer = [this, funcInfo](ParseNode *pnodeFormal)
  2131. {
  2132. if (pnodeFormal->IsVarLetOrConst())
  2133. {
  2134. Symbol* formal = pnodeFormal->AsParseNodeVar()->sym;
  2135. if (!formal->IsInSlot(this, funcInfo))
  2136. {
  2137. Assert(!formal->GetHasInit());
  2138. funcInfo->GetParsedFunctionBody()->InsertSymbolToRegSlotList(formal->GetName(), formal->GetLocation(), funcInfo->varRegsCount);
  2139. }
  2140. }
  2141. };
  2142. MapFormals(funcInfo->root, addFormalsToPropertyIdContainer);
  2143. }
  2144. // Transfer formal parameters to their home locations on the local frame.
  2145. if (funcInfo->GetHasArguments())
  2146. {
  2147. ParseNodePtr rest = funcInfo->root->pnodeRest;
  2148. if (rest != nullptr && rest->IsVarLetOrConst())
  2149. {
  2150. // Since we don't have to iterate over arguments here, we'll trust the location to be correct.
  2151. Symbol* sym = rest->AsParseNodeVar()->sym;
  2152. EmitLoadFormalIntoRegister(rest, sym->GetLocation() + 1, funcInfo);
  2153. }
  2154. // The arguments object creation helper does this work for us.
  2155. return;
  2156. }
  2157. Js::ArgSlot pos = 1;
  2158. auto loadFormal = [&](ParseNode *pnodeFormal)
  2159. {
  2160. EmitLoadFormalIntoRegister(pnodeFormal, pos, funcInfo);
  2161. pos++;
  2162. };
  2163. MapFormals(funcInfo->root, loadFormal);
  2164. }
  2165. void ByteCodeGenerator::DefineLabels(FuncInfo *funcInfo)
  2166. {
  2167. funcInfo->singleExit = m_writer.DefineLabel();
  2168. SList<ParseNodeStmt *>::Iterator iter(&funcInfo->targetStatements);
  2169. while (iter.Next())
  2170. {
  2171. ParseNodeStmt * node = iter.Data();
  2172. node->breakLabel = m_writer.DefineLabel();
  2173. node->continueLabel = m_writer.DefineLabel();
  2174. node->emitLabels = true;
  2175. }
  2176. }
  2177. void ByteCodeGenerator::EmitGlobalBody(FuncInfo *funcInfo)
  2178. {
  2179. // Emit global code (global scope or eval), fixing up the return register with the implicit
  2180. // return value.
  2181. ParseNode *pnode = funcInfo->root->pnodeBody;
  2182. ParseNode *pnodeLastVal = funcInfo->root->AsParseNodeProg()->pnodeLastValStmt;
  2183. if (pnodeLastVal == nullptr || pnodeLastVal->IsPatternDeclaration())
  2184. {
  2185. // We're not guaranteed to compute any values, so fix up the return register at the top
  2186. // in case.
  2187. this->m_writer.Reg1(Js::OpCode::LdUndef, ReturnRegister);
  2188. }
  2189. while (pnode->nop == knopList)
  2190. {
  2191. ParseNode *stmt = pnode->AsParseNodeBin()->pnode1;
  2192. if (stmt == pnodeLastVal)
  2193. {
  2194. pnodeLastVal = nullptr;
  2195. }
  2196. if (pnodeLastVal == nullptr && (this->flags & fscrReturnExpression))
  2197. {
  2198. EmitTopLevelStatement(stmt, funcInfo, true);
  2199. }
  2200. else
  2201. {
  2202. // Haven't hit the post-dominating return value yet,
  2203. // so don't bother with the return register.
  2204. EmitTopLevelStatement(stmt, funcInfo, false);
  2205. }
  2206. pnode = pnode->AsParseNodeBin()->pnode2;
  2207. }
  2208. EmitTopLevelStatement(pnode, funcInfo, false);
  2209. }
  2210. void ByteCodeGenerator::EmitFunctionBody(FuncInfo *funcInfo)
  2211. {
  2212. // Emit a function body. Only explicit returns and the implicit "undef" at the bottom
  2213. // get copied to the return register.
  2214. ParseNode *pnodeBody = funcInfo->root->pnodeBody;
  2215. ParseNode *pnode = pnodeBody;
  2216. while (pnode->nop == knopList)
  2217. {
  2218. ParseNode *stmt = pnode->AsParseNodeBin()->pnode1;
  2219. if (stmt->CapturesSyms())
  2220. {
  2221. CapturedSymMap *map = funcInfo->EnsureCapturedSymMap();
  2222. SList<Symbol*> *list = map->Item(stmt);
  2223. FOREACH_SLIST_ENTRY(Symbol*, sym, list)
  2224. {
  2225. if (!sym->GetIsCommittedToSlot())
  2226. {
  2227. Assert(sym->GetLocation() != Js::Constants::NoProperty);
  2228. sym->SetIsCommittedToSlot();
  2229. ParseNode *decl = sym->GetDecl();
  2230. Assert(decl);
  2231. if (PHASE_TRACE(Js::DelayCapturePhase, funcInfo->byteCodeFunction))
  2232. {
  2233. Output::Print(_u("--- DelayCapture: Committed symbol '%s' to slot.\n"),
  2234. sym->GetName().GetBuffer());
  2235. Output::Flush();
  2236. }
  2237. // REVIEW[ianhall]: HACK to work around this causing an error due to sym not yet being initialized
  2238. // what is this doing? Why are we assigning sym to itself?
  2239. bool old = sym->GetNeedDeclaration();
  2240. sym->SetNeedDeclaration(false);
  2241. this->EmitPropStore(sym->GetLocation(), sym, sym->GetPid(), funcInfo, decl->nop == knopLetDecl, decl->nop == knopConstDecl);
  2242. sym->SetNeedDeclaration(old);
  2243. }
  2244. }
  2245. NEXT_SLIST_ENTRY;
  2246. }
  2247. EmitTopLevelStatement(stmt, funcInfo, false);
  2248. pnode = pnode->AsParseNodeBin()->pnode2;
  2249. }
  2250. Assert(!pnode->CapturesSyms());
  2251. EmitTopLevelStatement(pnode, funcInfo, false);
  2252. }
  2253. void ByteCodeGenerator::EmitProgram(ParseNodeProg *pnodeProg)
  2254. {
  2255. // Indicate that the binding phase is over.
  2256. this->isBinding = false;
  2257. this->trackEnvDepth = true;
  2258. AssignPropertyIds(pnodeProg->funcInfo->byteCodeFunction);
  2259. int32 initSize = this->maxAstSize / AstBytecodeRatioEstimate;
  2260. // Use the temp allocator in bytecode write temp buffer.
  2261. m_writer.InitData(this->alloc, initSize);
  2262. #ifdef LOG_BYTECODE_AST_RATIO
  2263. // log the max Ast size
  2264. Output::Print(_u("Max Ast size: %d"), initSize);
  2265. #endif
  2266. Assert(pnodeProg && pnodeProg->nop == knopProg);
  2267. if (this->parentScopeInfo)
  2268. {
  2269. // Scope stack is already set up the way we want it, so don't visit the global scope.
  2270. // Start emitting with the nested scope (i.e., the deferred function).
  2271. this->EmitScopeList(pnodeProg->pnodeScopes);
  2272. }
  2273. else
  2274. {
  2275. this->EmitScopeList(pnodeProg);
  2276. }
  2277. }
  2278. void EmitDestructuredObject(ParseNode *lhs, Js::RegSlot rhsLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  2279. void EmitDestructuredValueOrInitializer(ParseNodePtr lhsElementNode, Js::RegSlot rhsLocation, ParseNodePtr initializer, bool isNonPatternAssignmentTarget, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  2280. void ByteCodeGenerator::PopulateFormalsScope(uint beginOffset, FuncInfo *funcInfo, ParseNodeFnc *pnodeFnc)
  2281. {
  2282. Js::DebuggerScope *debuggerScope = nullptr;
  2283. auto processArg = [&](ParseNode *pnodeArg) {
  2284. if (pnodeArg->IsVarLetOrConst())
  2285. {
  2286. if (debuggerScope == nullptr)
  2287. {
  2288. debuggerScope = RecordStartScopeObject(pnodeFnc, funcInfo->paramScope && funcInfo->paramScope->GetIsObject() ? Js::DiagParamScopeInObject : Js::DiagParamScope);
  2289. debuggerScope->SetBegin(beginOffset);
  2290. }
  2291. InsertPropertyToDebuggerScope(funcInfo, debuggerScope, pnodeArg->AsParseNodeVar()->sym);
  2292. }
  2293. };
  2294. MapFormals(pnodeFnc, processArg);
  2295. MapFormalsFromPattern(pnodeFnc, processArg);
  2296. if (debuggerScope != nullptr)
  2297. {
  2298. if (!funcInfo->GetParsedFunctionBody()->IsParamAndBodyScopeMerged())
  2299. {
  2300. InsertPropertyToDebuggerScope(funcInfo, debuggerScope, funcInfo->GetArgumentsSymbol());
  2301. }
  2302. RecordEndScopeObject(pnodeFnc);
  2303. }
  2304. }
  2305. void ByteCodeGenerator::InsertPropertyToDebuggerScope(FuncInfo* funcInfo, Js::DebuggerScope* debuggerScope, Symbol* sym)
  2306. {
  2307. if (sym)
  2308. {
  2309. Js::FunctionBody* funcBody = funcInfo->GetParsedFunctionBody();
  2310. Js::DebuggerScopePropertyFlags flag = Js::DebuggerScopePropertyFlags_None;
  2311. Js::RegSlot location = sym->GetLocation();
  2312. if (ShouldTrackDebuggerMetadata() && !funcInfo->IsBodyAndParamScopeMerged() && funcInfo->bodyScope->FindLocalSymbol(sym->GetName()) != nullptr)
  2313. {
  2314. flag |= Js::DebuggerScopePropertyFlags_HasDuplicateInBody;
  2315. location = funcBody->MapRegSlot(location);
  2316. }
  2317. debuggerScope->AddProperty(location, sym->EnsurePosition(funcInfo), flag);
  2318. }
  2319. }
  2320. void ByteCodeGenerator::EmitDefaultArgs(FuncInfo *funcInfo, ParseNodeFnc *pnodeFnc)
  2321. {
  2322. uint beginOffset = m_writer.GetCurrentOffset();
  2323. MapFormals(pnodeFnc, [&](ParseNode *pnodeArg)
  2324. {
  2325. if (pnodeArg->nop == knopParamPattern)
  2326. {
  2327. this->StartStatement(pnodeArg);
  2328. Assert(pnodeArg->AsParseNodeParamPattern()->location != Js::Constants::NoRegister);
  2329. ParseNodePtr pnode1 = pnodeArg->AsParseNodeParamPattern()->pnode1;
  2330. if (pnode1->IsPattern())
  2331. {
  2332. EmitAssignment(nullptr, pnode1, pnodeArg->AsParseNodeParamPattern()->location, this, funcInfo);
  2333. }
  2334. else
  2335. {
  2336. Assert(pnode1->nop == knopAsg);
  2337. Assert(pnode1->AsParseNodeBin()->pnode1->IsPattern());
  2338. EmitDestructuredValueOrInitializer(pnode1->AsParseNodeBin()->pnode1,
  2339. pnodeArg->AsParseNodeParamPattern()->location,
  2340. pnode1->AsParseNodeBin()->pnode2,
  2341. false /*isNonPatternAssignmentTarget*/,
  2342. this,
  2343. funcInfo);
  2344. }
  2345. this->EndStatement(pnodeArg);
  2346. return;
  2347. }
  2348. else if (pnodeArg->IsVarLetOrConst())
  2349. {
  2350. Js::RegSlot location = pnodeArg->AsParseNodeVar()->sym->GetLocation();
  2351. if (pnodeArg->AsParseNodeVar()->pnodeInit == nullptr)
  2352. {
  2353. // Since the formal hasn't been initialized in LdLetHeapArguments, we'll initialize it here.
  2354. pnodeArg->AsParseNodeVar()->sym->SetNeedDeclaration(false);
  2355. EmitPropStore(location, pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo, true);
  2356. return;
  2357. }
  2358. // Load the default argument if we got undefined, skip RHS evaluation otherwise.
  2359. Js::ByteCodeLabel noDefaultLabel = this->m_writer.DefineLabel();
  2360. Js::ByteCodeLabel endLabel = this->m_writer.DefineLabel();
  2361. this->StartStatement(pnodeArg);
  2362. // Let us use strict not equal to differentiate between null and undefined
  2363. m_writer.BrReg2(Js::OpCode::BrSrNeq_A, noDefaultLabel, location, funcInfo->undefinedConstantRegister);
  2364. Emit(pnodeArg->AsParseNodeVar()->pnodeInit, this, funcInfo, false);
  2365. pnodeArg->AsParseNodeVar()->sym->SetNeedDeclaration(false); // After emit to prevent foo(a = a)
  2366. if (funcInfo->GetHasArguments() && pnodeArg->AsParseNodeVar()->sym->IsInSlot(this, funcInfo))
  2367. {
  2368. EmitPropStore(pnodeArg->AsParseNodeVar()->pnodeInit->location, pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo, true);
  2369. m_writer.Br(endLabel);
  2370. }
  2371. else
  2372. {
  2373. EmitAssignment(nullptr, pnodeArg, pnodeArg->AsParseNodeVar()->pnodeInit->location, this, funcInfo);
  2374. }
  2375. funcInfo->ReleaseLoc(pnodeArg->AsParseNodeVar()->pnodeInit);
  2376. m_writer.MarkLabel(noDefaultLabel);
  2377. if (funcInfo->GetHasArguments() && pnodeArg->AsParseNodeVar()->sym->IsInSlot(this, funcInfo))
  2378. {
  2379. EmitPropStore(location, pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo, true);
  2380. m_writer.MarkLabel(endLabel);
  2381. }
  2382. this->EndStatement(pnodeArg);
  2383. }
  2384. });
  2385. if (m_writer.GetCurrentOffset() > beginOffset)
  2386. {
  2387. PopulateFormalsScope(beginOffset, funcInfo, pnodeFnc);
  2388. }
  2389. }
  2390. void ByteCodeGenerator::EmitOneFunction(ParseNodeFnc *pnodeFnc)
  2391. {
  2392. Assert(pnodeFnc && (pnodeFnc->nop == knopProg || pnodeFnc->nop == knopFncDecl));
  2393. FuncInfo *funcInfo = pnodeFnc->funcInfo;
  2394. Assert(funcInfo != nullptr);
  2395. if (funcInfo->IsFakeGlobalFunction(this->flags))
  2396. {
  2397. return;
  2398. }
  2399. Js::ParseableFunctionInfo* deferParseFunction = funcInfo->byteCodeFunction;
  2400. deferParseFunction->SetGrfscr(deferParseFunction->GetGrfscr() | (this->flags & ~fscrDeferredFncExpression));
  2401. deferParseFunction->SetSourceInfo(this->GetCurrentSourceIndex(),
  2402. funcInfo->root,
  2403. !!(this->flags & fscrEvalCode),
  2404. ((this->flags & fscrDynamicCode) && !(this->flags & fscrEvalCode)));
  2405. deferParseFunction->SetInParamsCount(funcInfo->inArgsCount);
  2406. if (pnodeFnc->HasDefaultArguments())
  2407. {
  2408. deferParseFunction->SetReportedInParamsCount(pnodeFnc->firstDefaultArg + 1);
  2409. }
  2410. else
  2411. {
  2412. deferParseFunction->SetReportedInParamsCount(funcInfo->inArgsCount);
  2413. }
  2414. // Note: Don't check the actual attributes on the functionInfo here, since CanDefer has been cleared while
  2415. // we're generating byte code.
  2416. if (deferParseFunction->IsDeferred() || funcInfo->canDefer)
  2417. {
  2418. Js::ScopeInfo::SaveEnclosingScopeInfo(this, funcInfo);
  2419. }
  2420. if (funcInfo->root->pnodeBody == nullptr)
  2421. {
  2422. if (!PHASE_OFF1(Js::SkipNestedDeferredPhase) && (this->GetFlags() & fscrCreateParserState) == fscrCreateParserState && deferParseFunction->GetCompileCount() == 0)
  2423. {
  2424. deferParseFunction->BuildDeferredStubs(funcInfo->root);
  2425. }
  2426. Assert(!deferParseFunction->IsFunctionBody() || deferParseFunction->GetFunctionBody()->GetByteCode() != nullptr);
  2427. return;
  2428. }
  2429. Js::FunctionBody* byteCodeFunction = funcInfo->GetParsedFunctionBody();
  2430. try
  2431. {
  2432. if (!funcInfo->IsGlobalFunction())
  2433. {
  2434. // Note: Do not set the stack nested func flag if the function has been redeferred and recompiled.
  2435. // In that case the flag already has the value we want.
  2436. if (CanStackNestedFunc(funcInfo, true) && byteCodeFunction->GetCompileCount() == 0)
  2437. {
  2438. #if DBG
  2439. byteCodeFunction->SetCanDoStackNestedFunc();
  2440. #endif
  2441. if (funcInfo->root->astSize <= ParseNodeFnc::MaxStackClosureAST)
  2442. {
  2443. byteCodeFunction->SetStackNestedFunc(true);
  2444. }
  2445. }
  2446. }
  2447. if (byteCodeFunction->DoStackNestedFunc())
  2448. {
  2449. uint nestedCount = byteCodeFunction->GetNestedCount();
  2450. for (uint i = 0; i < nestedCount; i++)
  2451. {
  2452. Js::FunctionProxy * nested = byteCodeFunction->GetNestedFunctionProxy(i);
  2453. if (nested->IsFunctionBody())
  2454. {
  2455. nested->GetFunctionBody()->SetStackNestedFuncParent(byteCodeFunction->GetFunctionInfo());
  2456. }
  2457. }
  2458. }
  2459. if (byteCodeFunction->GetByteCode() != nullptr)
  2460. {
  2461. // Previously compiled function nested within a re-deferred and re-compiled function.
  2462. return;
  2463. }
  2464. // Bug : 301517
  2465. // In the debug mode the hasOnlyThis optimization needs to be disabled, since user can break in this function
  2466. // and do operation on 'this' and its property, which may not be defined yet.
  2467. if (funcInfo->root->HasOnlyThisStmts() && !IsInDebugMode())
  2468. {
  2469. byteCodeFunction->SetHasOnlyThisStmts(true);
  2470. }
  2471. if (byteCodeFunction->IsInlineApplyDisabled() || this->scriptContext->GetConfig()->IsNoNative())
  2472. {
  2473. if ((pnodeFnc->nop == knopFncDecl) && (funcInfo->GetHasHeapArguments()) && (!funcInfo->GetCallsEval()) && ApplyEnclosesArgs(pnodeFnc, this))
  2474. {
  2475. bool applyEnclosesArgs = true;
  2476. for (ParseNode* pnodeVar = funcInfo->root->pnodeVars; pnodeVar; pnodeVar = pnodeVar->AsParseNodeVar()->pnodeNext)
  2477. {
  2478. Symbol* sym = pnodeVar->AsParseNodeVar()->sym;
  2479. if (sym->GetSymbolType() == STVariable && !sym->IsArguments())
  2480. {
  2481. applyEnclosesArgs = false;
  2482. break;
  2483. }
  2484. }
  2485. auto constAndLetCheck = [](ParseNodeBlock *pnodeBlock, bool *applyEnclosesArgs)
  2486. {
  2487. if (*applyEnclosesArgs)
  2488. {
  2489. for (auto lexvar = pnodeBlock->pnodeLexVars; lexvar; lexvar = lexvar->AsParseNodeVar()->pnodeNext)
  2490. {
  2491. Symbol* sym = lexvar->AsParseNodeVar()->sym;
  2492. if (sym->GetSymbolType() == STVariable && !sym->IsArguments())
  2493. {
  2494. *applyEnclosesArgs = false;
  2495. break;
  2496. }
  2497. }
  2498. }
  2499. };
  2500. constAndLetCheck(funcInfo->root->pnodeScopes, &applyEnclosesArgs);
  2501. constAndLetCheck(funcInfo->root->pnodeBodyScope, &applyEnclosesArgs);
  2502. funcInfo->SetApplyEnclosesArgs(applyEnclosesArgs);
  2503. }
  2504. }
  2505. InitScopeSlotArray(funcInfo);
  2506. FinalizeRegisters(funcInfo, byteCodeFunction);
  2507. DebugOnly(Js::RegSlot firstTmpReg = funcInfo->varRegsCount);
  2508. // Reserve temp registers for the inner scopes. We prefer temps because the JIT will then renumber them
  2509. // and see different lifetimes. (Note that debug mode requires permanent registers. See FinalizeRegisters.)
  2510. // Need to revisit the condition when enabling JitES6Generators.
  2511. uint innerScopeCount = funcInfo->InnerScopeCount();
  2512. if (!this->IsInDebugMode() && !byteCodeFunction->IsCoroutine())
  2513. {
  2514. byteCodeFunction->SetInnerScopeCount(innerScopeCount);
  2515. if (innerScopeCount)
  2516. {
  2517. funcInfo->SetFirstInnerScopeReg(funcInfo->AcquireTmpRegister());
  2518. for (uint i = 1; i < innerScopeCount; i++)
  2519. {
  2520. funcInfo->AcquireTmpRegister();
  2521. }
  2522. }
  2523. }
  2524. funcInfo->inlineCacheMap = Anew(alloc, FuncInfo::InlineCacheMap,
  2525. alloc,
  2526. funcInfo->RegCount() // Pass the actual register count. // TODO: Check if we can reduce this count
  2527. );
  2528. funcInfo->rootObjectLoadInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2529. alloc,
  2530. 10);
  2531. funcInfo->rootObjectLoadMethodInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2532. alloc,
  2533. 10);
  2534. funcInfo->rootObjectStoreInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2535. alloc,
  2536. 10);
  2537. funcInfo->referencedPropertyIdToMapIndex = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2538. alloc,
  2539. 10);
  2540. byteCodeFunction->AllocateLiteralRegexArray();
  2541. m_callSiteId = 0;
  2542. m_callApplyCallSiteCount = 0;
  2543. m_writer.Begin(byteCodeFunction, alloc, this->DoJitLoopBodies(funcInfo), funcInfo->hasLoop, this->IsInDebugMode());
  2544. this->PushFuncInfo(_u("EmitOneFunction"), funcInfo);
  2545. this->inPrologue = true;
  2546. Scope* paramScope = funcInfo->GetParamScope();
  2547. Scope* bodyScope = funcInfo->GetBodyScope();
  2548. // For now, emit all constant loads at top of function (should instead put in closest dominator of uses).
  2549. LoadAllConstants(funcInfo);
  2550. HomeArguments(funcInfo);
  2551. if (funcInfo->root->IsAsync())
  2552. {
  2553. Writer()->Reg1(Js::OpCode::NewAwaitObject, funcInfo->awaitRegister);
  2554. }
  2555. if (!funcInfo->IsBodyAndParamScopeMerged())
  2556. {
  2557. byteCodeFunction->SetParamAndBodyScopeNotMerged();
  2558. // Pop the body scope before emitting the default args
  2559. PopScope();
  2560. Assert(this->GetCurrentScope() == paramScope);
  2561. }
  2562. if (funcInfo->root->pnodeRest != nullptr)
  2563. {
  2564. byteCodeFunction->SetHasRestParameter();
  2565. }
  2566. if (funcInfo->IsGlobalFunction())
  2567. {
  2568. EnsureNoRedeclarations(pnodeFnc->pnodeScopes, funcInfo);
  2569. }
  2570. ::BeginEmitBlock(pnodeFnc->pnodeScopes, this, funcInfo);
  2571. DefineLabels(funcInfo);
  2572. // We need to emit the storage for special symbols before we emit the default arguments in case the default
  2573. // argument expressions reference those special names.
  2574. if (pnodeFnc->HasNonSimpleParameterList())
  2575. {
  2576. // If the param and body scope are merged, the special symbol vars are located in the body scope so we
  2577. // need to walk over the var list.
  2578. if (funcInfo->IsBodyAndParamScopeMerged())
  2579. {
  2580. for (ParseNodePtr pnodeVar = pnodeFnc->pnodeVars; pnodeVar; pnodeVar = pnodeVar->AsParseNodeVar()->pnodeNext)
  2581. {
  2582. #if DBG
  2583. bool reachedEndOfSpecialSymbols = false;
  2584. #endif
  2585. Symbol* sym = pnodeVar->AsParseNodeVar()->sym;
  2586. if (sym != nullptr && sym->IsSpecialSymbol())
  2587. {
  2588. EmitPropStoreForSpecialSymbol(sym->GetLocation(), sym, sym->GetPid(), funcInfo, true);
  2589. if (ShouldTrackDebuggerMetadata() && !sym->IsInSlot(this, funcInfo))
  2590. {
  2591. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), sym->GetLocation(), funcInfo->varRegsCount);
  2592. }
  2593. }
  2594. else
  2595. {
  2596. #if DBG
  2597. reachedEndOfSpecialSymbols = true;
  2598. #else
  2599. // All of the special symbols exist at the beginning of the var list (parser guarantees this and debug build asserts this)
  2600. // so we can quit walking at the first non-special one we see.
  2601. break;
  2602. #endif
  2603. }
  2604. #if DBG
  2605. if (reachedEndOfSpecialSymbols)
  2606. {
  2607. Assert(sym == nullptr || !sym->IsSpecialSymbol());
  2608. }
  2609. #endif
  2610. }
  2611. }
  2612. else
  2613. {
  2614. paramScope->ForEachSymbol([&](Symbol* sym) {
  2615. if (sym && sym->IsSpecialSymbol())
  2616. {
  2617. EmitPropStoreForSpecialSymbol(sym->GetLocation(), sym, sym->GetPid(), funcInfo, true);
  2618. }
  2619. });
  2620. }
  2621. }
  2622. if (pnodeFnc->HasNonSimpleParameterList() || !funcInfo->IsBodyAndParamScopeMerged())
  2623. {
  2624. Assert(pnodeFnc->HasNonSimpleParameterList() || CONFIG_FLAG(ForceSplitScope));
  2625. this->InitBlockScopedNonTemps(funcInfo->root->pnodeScopes, funcInfo);
  2626. EmitDefaultArgs(funcInfo, pnodeFnc);
  2627. if (!funcInfo->IsBodyAndParamScopeMerged())
  2628. {
  2629. Assert(this->GetCurrentScope() == paramScope);
  2630. // Push the body scope
  2631. PushScope(bodyScope);
  2632. funcInfo->SetCurrentChildScope(bodyScope);
  2633. // Mark the beginning of the body scope so that new scope slots can be created.
  2634. this->Writer()->Empty(Js::OpCode::BeginBodyScope);
  2635. }
  2636. }
  2637. DefineUserVars(funcInfo);
  2638. // Emit all scope-wide function definitions before emitting function bodies
  2639. // so that calls may reference functions they precede lexically.
  2640. // Note, global eval scope is a fake local scope and is handled as if it were
  2641. // a lexical block instead of a true global scope, so do not define the functions
  2642. // here. They will be defined during BeginEmitBlock.
  2643. if (!(funcInfo->IsGlobalFunction() && this->IsEvalWithNoParentScopeInfo()))
  2644. {
  2645. // This only handles function declarations, which param scope cannot have any.
  2646. DefineFunctions(funcInfo);
  2647. }
  2648. // If the function has non simple parameter list, the params needs to be evaluated when the generator object is created
  2649. // (that is when the function is called). So insert an extra yield we can execute up to, to do this.
  2650. // In a Module we execute until this yield to hoist functions accross modules.
  2651. if (pnodeFnc->IsGenerator() && (pnodeFnc->HasNonSimpleParameterList() || pnodeFnc->IsModule()))
  2652. {
  2653. EmitStartupYield(this, funcInfo);
  2654. }
  2655. if (pnodeFnc->HasNonSimpleParameterList() || !funcInfo->IsBodyAndParamScopeMerged())
  2656. {
  2657. Assert(pnodeFnc->HasNonSimpleParameterList() || CONFIG_FLAG(ForceSplitScope));
  2658. this->InitBlockScopedNonTemps(funcInfo->root->pnodeBodyScope, funcInfo);
  2659. }
  2660. else
  2661. {
  2662. this->InitBlockScopedNonTemps(funcInfo->root->pnodeScopes, funcInfo);
  2663. }
  2664. if (!pnodeFnc->HasNonSimpleParameterList() && funcInfo->GetHasArguments() && !NeedScopeObjectForArguments(funcInfo, pnodeFnc))
  2665. {
  2666. // If we didn't create a scope object and didn't have default args, we still need to transfer the formals to their slots.
  2667. MapFormalsWithoutRest(pnodeFnc, [&](ParseNode *pnodeArg) { EmitPropStore(pnodeArg->AsParseNodeVar()->sym->GetLocation(), pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo); });
  2668. }
  2669. Js::RegSlot formalsUpperBound = Js::Constants::NoRegister; // Needed for tracking the last RegSlot in the param scope
  2670. if (!funcInfo->IsBodyAndParamScopeMerged())
  2671. {
  2672. // Emit bytecode to copy the initial values from param names to their corresponding body bindings.
  2673. // We have to do this after the rest param is marked as false for need declaration.
  2674. Symbol* funcSym = funcInfo->root->GetFuncSymbol();
  2675. paramScope->ForEachSymbol([&](Symbol* param) {
  2676. Symbol* varSym = funcInfo->GetBodyScope()->FindLocalSymbol(param->GetName());
  2677. if ((funcSym == nullptr || funcSym != param) // Do not copy the symbol over to body as the function expression symbol
  2678. // is expected to stay inside the function expression scope
  2679. && (varSym && varSym->GetSymbolType() == STVariable && (varSym->IsInSlot(this, funcInfo) || varSym->GetLocation() != Js::Constants::NoRegister)))
  2680. {
  2681. if (!varSym->GetNeedDeclaration())
  2682. {
  2683. if (param->IsInSlot(this, funcInfo))
  2684. {
  2685. // Simulating EmitPropLoad here. We can't directly call the method as we have to use the param scope specifically.
  2686. // Walking the scope chain is not possible at this time.
  2687. Js::RegSlot tempReg = funcInfo->AcquireTmpRegister();
  2688. Js::PropertyId slot = param->EnsureScopeSlot(this, funcInfo);
  2689. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(paramScope, slot);
  2690. Js::OpCode op = paramScope->GetIsObject() ? Js::OpCode::LdParamObjSlot : Js::OpCode::LdParamSlot;
  2691. slot = slot + (paramScope->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  2692. this->m_writer.SlotI1(op, tempReg, slot, profileId);
  2693. this->EmitPropStore(tempReg, varSym, varSym->GetPid(), funcInfo);
  2694. funcInfo->ReleaseTmpRegister(tempReg);
  2695. }
  2696. else if (param->GetLocation() != Js::Constants::NoRegister)
  2697. {
  2698. this->EmitPropStore(param->GetLocation(), varSym, varSym->GetPid(), funcInfo);
  2699. }
  2700. else
  2701. {
  2702. Assert(param->IsArguments() && !funcInfo->GetHasArguments());
  2703. }
  2704. }
  2705. else
  2706. {
  2707. // There is a let redeclaration of arguments symbol. Any other var will cause a
  2708. // re-declaration error.
  2709. Assert(param->IsArguments());
  2710. }
  2711. }
  2712. if (ShouldTrackDebuggerMetadata() && param->GetLocation() != Js::Constants::NoRegister)
  2713. {
  2714. if (formalsUpperBound == Js::Constants::NoRegister || formalsUpperBound < param->GetLocation())
  2715. {
  2716. formalsUpperBound = param->GetLocation();
  2717. }
  2718. }
  2719. });
  2720. }
  2721. if (ShouldTrackDebuggerMetadata() && byteCodeFunction->GetPropertyIdOnRegSlotsContainer())
  2722. {
  2723. byteCodeFunction->GetPropertyIdOnRegSlotsContainer()->formalsUpperBound = formalsUpperBound;
  2724. }
  2725. if (pnodeFnc->pnodeBodyScope != nullptr)
  2726. {
  2727. ::BeginEmitBlock(pnodeFnc->pnodeBodyScope, this, funcInfo);
  2728. }
  2729. this->inPrologue = false;
  2730. if (funcInfo->IsGlobalFunction())
  2731. {
  2732. EmitGlobalBody(funcInfo);
  2733. }
  2734. else
  2735. {
  2736. EmitFunctionBody(funcInfo);
  2737. }
  2738. if (pnodeFnc->pnodeBodyScope != nullptr)
  2739. {
  2740. ::EndEmitBlock(pnodeFnc->pnodeBodyScope, this, funcInfo);
  2741. }
  2742. ::EndEmitBlock(pnodeFnc->pnodeScopes, this, funcInfo);
  2743. if (!this->IsInDebugMode())
  2744. {
  2745. // Release the temp registers that we reserved for inner scopes above.
  2746. if (innerScopeCount)
  2747. {
  2748. Js::RegSlot tmpReg = funcInfo->FirstInnerScopeReg() + innerScopeCount - 1;
  2749. for (uint i = 0; i < innerScopeCount; i++)
  2750. {
  2751. funcInfo->ReleaseTmpRegister(tmpReg);
  2752. tmpReg--;
  2753. }
  2754. }
  2755. }
  2756. Assert(funcInfo->firstTmpReg == firstTmpReg);
  2757. Assert(funcInfo->curTmpReg == firstTmpReg);
  2758. Assert(byteCodeFunction->GetFirstTmpReg() == firstTmpReg + byteCodeFunction->GetConstantCount());
  2759. byteCodeFunction->CheckAndSetVarCount(funcInfo->varRegsCount);
  2760. byteCodeFunction->CheckAndSetOutParamMaxDepth(funcInfo->outArgsMaxDepth);
  2761. byteCodeFunction->SetForInLoopDepth(funcInfo->GetMaxForInLoopLevel());
  2762. // Do a uint32 add just to verify that we haven't overflowed the reg slot type.
  2763. UInt32Math::Add(funcInfo->varRegsCount, funcInfo->constRegsCount);
  2764. #if DBG_DUMP
  2765. if (PHASE_STATS1(Js::ByteCodePhase))
  2766. {
  2767. Output::Print(_u(" BCode: %-10d, Aux: %-10d, AuxC: %-10d Total: %-10d, %s\n"),
  2768. m_writer.ByteCodeDataSize(),
  2769. m_writer.AuxiliaryDataSize(),
  2770. m_writer.AuxiliaryContextDataSize(),
  2771. m_writer.ByteCodeDataSize() + m_writer.AuxiliaryDataSize() + m_writer.AuxiliaryContextDataSize(),
  2772. funcInfo->name);
  2773. this->scriptContext->byteCodeDataSize += m_writer.ByteCodeDataSize();
  2774. this->scriptContext->byteCodeAuxiliaryDataSize += m_writer.AuxiliaryDataSize();
  2775. this->scriptContext->byteCodeAuxiliaryContextDataSize += m_writer.AuxiliaryContextDataSize();
  2776. }
  2777. #endif
  2778. this->MapCacheIdsToPropertyIds(funcInfo);
  2779. this->MapReferencedPropertyIds(funcInfo);
  2780. Assert(this->TopFuncInfo() == funcInfo);
  2781. PopFuncInfo(_u("EmitOneFunction"));
  2782. m_writer.SetCallSiteCount(m_callSiteId);
  2783. m_writer.SetCallApplyCallsiteCount(m_callApplyCallSiteCount);
  2784. #if ENABLE_NATIVE_CODEGEN
  2785. if (funcInfo->callSiteToCallApplyCallSiteMap)
  2786. {
  2787. this->MapCallSiteToCallApplyCallSiteMap(funcInfo);
  2788. }
  2789. #endif
  2790. #ifdef LOG_BYTECODE_AST_RATIO
  2791. m_writer.End(funcInfo->root->astSize, this->maxAstSize);
  2792. #else
  2793. m_writer.End();
  2794. #endif
  2795. }
  2796. catch (...)
  2797. {
  2798. // Failed to generate byte-code for this function body (likely OOM or stack overflow). Notify the function body so that
  2799. // it can revert intermediate state changes that may have taken place during byte code generation before the failure.
  2800. byteCodeFunction->ResetByteCodeGenState();
  2801. m_writer.Reset();
  2802. throw;
  2803. }
  2804. #ifdef PERF_HINT
  2805. if (PHASE_TRACE1(Js::PerfHintPhase) && !byteCodeFunction->GetIsGlobalFunc())
  2806. {
  2807. if (byteCodeFunction->GetHasTry())
  2808. {
  2809. WritePerfHint(PerfHints::HasTryBlock_Verbose, byteCodeFunction);
  2810. }
  2811. if (funcInfo->GetCallsEval())
  2812. {
  2813. WritePerfHint(PerfHints::CallsEval_Verbose, byteCodeFunction);
  2814. }
  2815. else if (funcInfo->GetChildCallsEval())
  2816. {
  2817. WritePerfHint(PerfHints::ChildCallsEval, byteCodeFunction);
  2818. }
  2819. }
  2820. #endif
  2821. if (!byteCodeFunction->GetSourceContextInfo()->IsDynamic() && byteCodeFunction->GetIsTopLevel() && !(this->flags & fscrEvalCode))
  2822. {
  2823. // Add the top level of nested functions to the tracking dictionary. Wait until this point so that all nested functions have gone
  2824. // through the Emit API so source info, etc., is initialized, and these are not orphaned functions left behind by an unfinished pass.
  2825. byteCodeFunction->ForEachNestedFunc([&](Js::FunctionProxy * nestedFunc, uint32 i)
  2826. {
  2827. if (nestedFunc && nestedFunc->IsDeferredParseFunction() && nestedFunc->GetParseableFunctionInfo()->GetIsDeclaration())
  2828. {
  2829. byteCodeFunction->GetUtf8SourceInfo()->TrackDeferredFunction(nestedFunc->GetLocalFunctionId(), nestedFunc->GetParseableFunctionInfo());
  2830. }
  2831. return true;
  2832. });
  2833. }
  2834. byteCodeFunction->SetInitialDefaultEntryPoint();
  2835. byteCodeFunction->SetCompileCount(UInt32Math::Add(byteCodeFunction->GetCompileCount(), 1));
  2836. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2837. if (byteCodeFunction->IsInDebugMode() != scriptContext->IsScriptContextInDebugMode()) // debug mode mismatch
  2838. {
  2839. if (m_utf8SourceInfo->GetIsLibraryCode())
  2840. {
  2841. Assert(!byteCodeFunction->IsInDebugMode()); // Library script byteCode is never in debug mode
  2842. }
  2843. else
  2844. {
  2845. Js::Throw::FatalInternalError();
  2846. }
  2847. }
  2848. #endif
  2849. #if DBG_DUMP
  2850. if (PHASE_DUMP(Js::ByteCodePhase, funcInfo->byteCodeFunction) && Js::Configuration::Global.flags.Verbose)
  2851. {
  2852. pnodeFnc->Dump();
  2853. }
  2854. if (this->Trace() || PHASE_DUMP(Js::ByteCodePhase, funcInfo->byteCodeFunction))
  2855. {
  2856. Js::ByteCodeDumper::Dump(byteCodeFunction);
  2857. }
  2858. if (PHASE_DUMP(Js::DebuggerScopePhase, funcInfo->byteCodeFunction))
  2859. {
  2860. byteCodeFunction->DumpScopes();
  2861. }
  2862. #endif
  2863. #if ENABLE_NATIVE_CODEGEN
  2864. if ((!PHASE_OFF(Js::BackEndPhase, funcInfo->byteCodeFunction))
  2865. && !this->forceNoNative
  2866. && !this->scriptContext->GetConfig()->IsNoNative())
  2867. {
  2868. GenerateFunction(this->scriptContext->GetNativeCodeGenerator(), byteCodeFunction);
  2869. }
  2870. #endif
  2871. }
  2872. void ByteCodeGenerator::MapCacheIdsToPropertyIds(FuncInfo *funcInfo)
  2873. {
  2874. Js::FunctionBody *functionBody = funcInfo->GetParsedFunctionBody();
  2875. uint rootObjectLoadInlineCacheStart = funcInfo->GetInlineCacheCount();
  2876. uint rootObjectLoadMethodInlineCacheStart = rootObjectLoadInlineCacheStart + funcInfo->GetRootObjectLoadInlineCacheCount();
  2877. uint rootObjectStoreInlineCacheStart = rootObjectLoadMethodInlineCacheStart + funcInfo->GetRootObjectLoadMethodInlineCacheCount();
  2878. uint totalFieldAccessInlineCacheCount = rootObjectStoreInlineCacheStart + funcInfo->GetRootObjectStoreInlineCacheCount();
  2879. functionBody->CreateCacheIdToPropertyIdMap(rootObjectLoadInlineCacheStart, rootObjectLoadMethodInlineCacheStart,
  2880. rootObjectStoreInlineCacheStart, totalFieldAccessInlineCacheCount, funcInfo->GetIsInstInlineCacheCount());
  2881. if (totalFieldAccessInlineCacheCount == 0)
  2882. {
  2883. return;
  2884. }
  2885. funcInfo->inlineCacheMap->Map([functionBody](Js::RegSlot regSlot, FuncInfo::InlineCacheIdMap *inlineCacheIdMap)
  2886. {
  2887. inlineCacheIdMap->Map([functionBody](Js::PropertyId propertyId, FuncInfo::InlineCacheList* inlineCacheList)
  2888. {
  2889. if (inlineCacheList)
  2890. {
  2891. inlineCacheList->Iterate([functionBody, propertyId](InlineCacheUnit cacheUnit)
  2892. {
  2893. CompileAssert(offsetof(InlineCacheUnit, cacheId) == offsetof(InlineCacheUnit, loadCacheId));
  2894. if (cacheUnit.loadCacheId != -1)
  2895. {
  2896. functionBody->SetPropertyIdForCacheId(cacheUnit.loadCacheId, propertyId);
  2897. }
  2898. if (cacheUnit.loadMethodCacheId != -1)
  2899. {
  2900. functionBody->SetPropertyIdForCacheId(cacheUnit.loadMethodCacheId, propertyId);
  2901. }
  2902. if (cacheUnit.storeCacheId != -1)
  2903. {
  2904. functionBody->SetPropertyIdForCacheId(cacheUnit.storeCacheId, propertyId);
  2905. }
  2906. });
  2907. }
  2908. });
  2909. });
  2910. funcInfo->rootObjectLoadInlineCacheMap->Map([functionBody, rootObjectLoadInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  2911. {
  2912. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectLoadInlineCacheStart, propertyId);
  2913. });
  2914. funcInfo->rootObjectLoadMethodInlineCacheMap->Map([functionBody, rootObjectLoadMethodInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  2915. {
  2916. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectLoadMethodInlineCacheStart, propertyId);
  2917. });
  2918. funcInfo->rootObjectStoreInlineCacheMap->Map([functionBody, rootObjectStoreInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  2919. {
  2920. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectStoreInlineCacheStart, propertyId);
  2921. });
  2922. SListBase<uint>::Iterator valueOfIter(&funcInfo->valueOfStoreCacheIds);
  2923. while (valueOfIter.Next())
  2924. {
  2925. functionBody->SetPropertyIdForCacheId(valueOfIter.Data(), Js::PropertyIds::valueOf);
  2926. }
  2927. SListBase<uint>::Iterator toStringIter(&funcInfo->toStringStoreCacheIds);
  2928. while (toStringIter.Next())
  2929. {
  2930. functionBody->SetPropertyIdForCacheId(toStringIter.Data(), Js::PropertyIds::toString);
  2931. }
  2932. #if DBG
  2933. functionBody->VerifyCacheIdToPropertyIdMap();
  2934. #endif
  2935. }
  2936. void ByteCodeGenerator::MapReferencedPropertyIds(FuncInfo * funcInfo)
  2937. {
  2938. Js::FunctionBody *functionBody = funcInfo->GetParsedFunctionBody();
  2939. uint referencedPropertyIdCount = funcInfo->GetReferencedPropertyIdCount();
  2940. functionBody->CreateReferencedPropertyIdMap(referencedPropertyIdCount);
  2941. funcInfo->referencedPropertyIdToMapIndex->Map([functionBody](Js::PropertyId propertyId, uint mapIndex)
  2942. {
  2943. functionBody->SetReferencedPropertyIdWithMapIndex(mapIndex, propertyId);
  2944. });
  2945. #if DBG
  2946. functionBody->VerifyReferencedPropertyIdMap();
  2947. #endif
  2948. }
  2949. #if ENABLE_NATIVE_CODEGEN
  2950. void ByteCodeGenerator::MapCallSiteToCallApplyCallSiteMap(FuncInfo * funcInfo)
  2951. {
  2952. Js::FunctionBody * functionBody = funcInfo->GetParsedFunctionBody();
  2953. if (functionBody->CreateCallSiteToCallApplyCallSiteArray())
  2954. {
  2955. funcInfo->callSiteToCallApplyCallSiteMap->Map([functionBody](Js::ProfileId callSiteId, Js::ProfileId callApplyCallSiteId)
  2956. {
  2957. functionBody->GetCallSiteToCallApplyCallSiteArray()[callSiteId] = callApplyCallSiteId;
  2958. });
  2959. }
  2960. }
  2961. #endif
  2962. void ByteCodeGenerator::EmitScopeList(ParseNode *pnode, ParseNode *breakOnBodyScopeNode)
  2963. {
  2964. while (pnode)
  2965. {
  2966. if (breakOnBodyScopeNode != nullptr && breakOnBodyScopeNode == pnode)
  2967. {
  2968. break;
  2969. }
  2970. switch (pnode->nop)
  2971. {
  2972. case knopFncDecl:
  2973. #ifdef ASMJS_PLAT
  2974. if (pnode->AsParseNodeFnc()->GetAsmjsMode())
  2975. {
  2976. Js::ExclusiveContext context(this, GetScriptContext());
  2977. if (Js::AsmJSCompiler::Compile(&context, pnode->AsParseNodeFnc(), pnode->AsParseNodeFnc()->pnodeParams))
  2978. {
  2979. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  2980. break;
  2981. }
  2982. else if (CONFIG_FLAG(AsmJsStopOnError))
  2983. {
  2984. exit(JSERR_AsmJsCompileError);
  2985. }
  2986. else
  2987. {
  2988. // If deferral is not allowed, throw and reparse everything with asm.js disabled.
  2989. throw Js::AsmJsParseException();
  2990. }
  2991. }
  2992. #endif
  2993. // FALLTHROUGH
  2994. case knopProg:
  2995. if (pnode->AsParseNodeFnc()->funcInfo)
  2996. {
  2997. FuncInfo* funcInfo = pnode->AsParseNodeFnc()->funcInfo;
  2998. Scope* paramScope = funcInfo->GetParamScope();
  2999. if (!funcInfo->IsBodyAndParamScopeMerged())
  3000. {
  3001. funcInfo->SetCurrentChildScope(paramScope);
  3002. }
  3003. else
  3004. {
  3005. funcInfo->SetCurrentChildScope(funcInfo->GetBodyScope());
  3006. }
  3007. this->StartEmitFunction(pnode->AsParseNodeFnc());
  3008. if (!funcInfo->IsBodyAndParamScopeMerged())
  3009. {
  3010. this->EmitScopeList(pnode->AsParseNodeFnc()->pnodeBodyScope->pnodeScopes);
  3011. }
  3012. else
  3013. {
  3014. this->EmitScopeList(pnode->AsParseNodeFnc()->pnodeScopes);
  3015. }
  3016. this->EmitOneFunction(pnode->AsParseNodeFnc());
  3017. this->EndEmitFunction(pnode->AsParseNodeFnc());
  3018. Assert(pnode->AsParseNodeFnc()->pnodeBody == nullptr || funcInfo->isReused || funcInfo->GetCurrentChildScope() == funcInfo->GetBodyScope());
  3019. funcInfo->SetCurrentChildScope(nullptr);
  3020. }
  3021. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  3022. break;
  3023. case knopBlock:
  3024. {
  3025. ParseNodeBlock * pnodeBlock = pnode->AsParseNodeBlock();
  3026. this->StartEmitBlock(pnodeBlock);
  3027. this->EmitScopeList(pnodeBlock->pnodeScopes);
  3028. this->EndEmitBlock(pnodeBlock);
  3029. pnode = pnodeBlock->pnodeNext;
  3030. break;
  3031. }
  3032. case knopCatch:
  3033. {
  3034. ParseNodeCatch * pnodeCatch = pnode->AsParseNodeCatch();
  3035. this->StartEmitCatch(pnodeCatch);
  3036. this->EmitScopeList(pnodeCatch->pnodeScopes);
  3037. this->EndEmitCatch(pnodeCatch);
  3038. pnode = pnodeCatch->pnodeNext;
  3039. break;
  3040. }
  3041. case knopWith:
  3042. this->StartEmitWith(pnode);
  3043. this->EmitScopeList(pnode->AsParseNodeWith()->pnodeScopes);
  3044. this->EndEmitWith(pnode);
  3045. pnode = pnode->AsParseNodeWith()->pnodeNext;
  3046. break;
  3047. default:
  3048. AssertMsg(false, "Unexpected opcode in tree of scopes");
  3049. break;
  3050. }
  3051. }
  3052. }
  3053. void ByteCodeGenerator::EnsureFncDeclScopeSlot(ParseNodeFnc *pnodeFnc, FuncInfo *funcInfo)
  3054. {
  3055. if (pnodeFnc->pnodeName)
  3056. {
  3057. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  3058. Symbol *sym = pnodeFnc->pnodeName->sym;
  3059. // If this function is shadowing the arguments symbol in body then skip it.
  3060. // We will allocate scope slot for the arguments symbol during EmitLocalPropInit.
  3061. if (sym && !sym->IsArguments())
  3062. {
  3063. sym->EnsureScopeSlot(this, funcInfo);
  3064. }
  3065. }
  3066. }
  3067. // Similar to EnsureFncScopeSlot visitor function, but verifies that a slot is needed before assigning it.
  3068. void ByteCodeGenerator::CheckFncDeclScopeSlot(ParseNodeFnc *pnodeFnc, FuncInfo *funcInfo)
  3069. {
  3070. if (pnodeFnc->pnodeName)
  3071. {
  3072. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  3073. Symbol *sym = pnodeFnc->pnodeName->sym;
  3074. if (sym && sym->NeedsSlotAlloc(this, funcInfo))
  3075. {
  3076. sym->EnsureScopeSlot(this, funcInfo);
  3077. }
  3078. }
  3079. }
  3080. void ByteCodeGenerator::StartEmitFunction(ParseNodeFnc *pnodeFnc)
  3081. {
  3082. Assert(pnodeFnc->nop == knopFncDecl || pnodeFnc->nop == knopProg);
  3083. FuncInfo *funcInfo = pnodeFnc->funcInfo;
  3084. Scope * const bodyScope = funcInfo->GetBodyScope();
  3085. Scope * const paramScope = funcInfo->GetParamScope();
  3086. if (funcInfo->byteCodeFunction->IsFunctionParsed() && funcInfo->root->pnodeBody != nullptr)
  3087. {
  3088. if (funcInfo->GetParsedFunctionBody()->GetByteCode() == nullptr && !(flags & (fscrEval | fscrImplicitThis)))
  3089. {
  3090. // Only set the environment depth if it's truly known (i.e., not in eval or event handler).
  3091. funcInfo->GetParsedFunctionBody()->SetEnvDepth(this->envDepth);
  3092. }
  3093. if (funcInfo->GetCallsEval())
  3094. {
  3095. funcInfo->byteCodeFunction->SetDontInline(true);
  3096. }
  3097. Scope * const funcExprScope = funcInfo->funcExprScope;
  3098. if (funcExprScope)
  3099. {
  3100. if (funcInfo->GetCallsEval())
  3101. {
  3102. Assert(funcExprScope->GetIsObject());
  3103. }
  3104. if (funcExprScope->GetIsObject())
  3105. {
  3106. funcExprScope->SetCapturesAll(true);
  3107. funcExprScope->SetMustInstantiate(true);
  3108. PushScope(funcExprScope);
  3109. }
  3110. else
  3111. {
  3112. Symbol *sym = funcInfo->root->GetFuncSymbol();
  3113. if (funcInfo->IsBodyAndParamScopeMerged())
  3114. {
  3115. funcInfo->bodyScope->AddSymbol(sym);
  3116. }
  3117. else
  3118. {
  3119. funcInfo->paramScope->AddSymbol(sym);
  3120. }
  3121. sym->EnsureScopeSlot(this, funcInfo);
  3122. if (sym->GetHasNonLocalReference())
  3123. {
  3124. sym->GetScope()->SetHasOwnLocalInClosure(true);
  3125. }
  3126. }
  3127. }
  3128. if (pnodeFnc->nop != knopProg)
  3129. {
  3130. if (!bodyScope->GetIsObject() && NeedObjectAsFunctionScope(funcInfo, pnodeFnc))
  3131. {
  3132. Assert(bodyScope->GetIsObject());
  3133. }
  3134. if (bodyScope->GetIsObject())
  3135. {
  3136. bodyScope->SetLocation(funcInfo->frameObjRegister);
  3137. }
  3138. else
  3139. {
  3140. bodyScope->SetLocation(funcInfo->frameSlotsRegister);
  3141. }
  3142. if (!funcInfo->IsBodyAndParamScopeMerged())
  3143. {
  3144. if (paramScope->GetIsObject())
  3145. {
  3146. paramScope->SetLocation(funcInfo->frameObjRegister);
  3147. }
  3148. else
  3149. {
  3150. paramScope->SetLocation(funcInfo->frameSlotsRegister);
  3151. }
  3152. }
  3153. if (bodyScope->GetIsObject())
  3154. {
  3155. // Win8 908700: Disable under F12 debugger because there are too many cached scopes holding onto locals.
  3156. funcInfo->SetHasCachedScope(
  3157. !PHASE_OFF(Js::CachedScopePhase, funcInfo->byteCodeFunction) &&
  3158. !funcInfo->Escapes() &&
  3159. funcInfo->frameObjRegister != Js::Constants::NoRegister &&
  3160. !ApplyEnclosesArgs(pnodeFnc, this) &&
  3161. funcInfo->IsBodyAndParamScopeMerged() && // There is eval in the param scope
  3162. !pnodeFnc->HasDefaultArguments() &&
  3163. !pnodeFnc->HasDestructuredParams() &&
  3164. (PHASE_FORCE(Js::CachedScopePhase, funcInfo->byteCodeFunction) || !IsInDebugMode())
  3165. #if ENABLE_TTD
  3166. && !funcInfo->GetParsedFunctionBody()->GetScriptContext()->GetThreadContext()->IsRuntimeInTTDMode()
  3167. #endif
  3168. && !funcInfo->byteCodeFunction->IsCoroutine()
  3169. );
  3170. if (funcInfo->GetHasCachedScope())
  3171. {
  3172. Assert(funcInfo->funcObjRegister == Js::Constants::NoRegister);
  3173. Symbol *funcSym = funcInfo->root->GetFuncSymbol();
  3174. if (funcSym && funcSym->GetIsFuncExpr())
  3175. {
  3176. if (funcSym->GetLocation() == Js::Constants::NoRegister)
  3177. {
  3178. funcInfo->funcObjRegister = funcInfo->NextVarRegister();
  3179. }
  3180. else
  3181. {
  3182. funcInfo->funcObjRegister = funcSym->GetLocation();
  3183. }
  3184. }
  3185. else
  3186. {
  3187. funcInfo->funcObjRegister = funcInfo->NextVarRegister();
  3188. }
  3189. Assert(funcInfo->funcObjRegister != Js::Constants::NoRegister);
  3190. }
  3191. ParseNode *pnode;
  3192. Symbol *sym;
  3193. if (funcInfo->GetHasArguments())
  3194. {
  3195. // Process function's formal parameters
  3196. MapFormals(pnodeFnc, [&](ParseNode *pnode)
  3197. {
  3198. if (pnode->IsVarLetOrConst())
  3199. {
  3200. pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo);
  3201. }
  3202. });
  3203. MapFormalsFromPattern(pnodeFnc, [&](ParseNode *pnode) { pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo); });
  3204. // Only allocate scope slot for "arguments" when really necessary. "hasDeferredChild"
  3205. // doesn't require scope slot for "arguments" because inner functions can't access
  3206. // outer function's arguments directly.
  3207. sym = funcInfo->GetArgumentsSymbol();
  3208. Assert(sym);
  3209. if (sym->NeedsSlotAlloc(this, funcInfo))
  3210. {
  3211. sym->EnsureScopeSlot(this, funcInfo);
  3212. }
  3213. }
  3214. sym = funcInfo->root->GetFuncSymbol();
  3215. if (sym && sym->NeedsSlotAlloc(this, funcInfo))
  3216. {
  3217. if (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject())
  3218. {
  3219. sym->SetScopeSlot(0);
  3220. }
  3221. else if (funcInfo->GetFuncExprNameReference())
  3222. {
  3223. sym->EnsureScopeSlot(this, funcInfo);
  3224. }
  3225. }
  3226. if (!funcInfo->GetHasArguments())
  3227. {
  3228. Symbol *formal;
  3229. Js::ArgSlot pos = 1;
  3230. auto moveArgToReg = [&](ParseNode *pnode)
  3231. {
  3232. if (pnode->IsVarLetOrConst())
  3233. {
  3234. formal = pnode->AsParseNodeVar()->sym;
  3235. // Get the param from its argument position into its assigned register.
  3236. // The position should match the location; otherwise, it has been shadowed by parameter with the same name.
  3237. if (formal->GetLocation() + 1 == pos)
  3238. {
  3239. pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo);
  3240. }
  3241. }
  3242. pos++;
  3243. };
  3244. MapFormals(pnodeFnc, moveArgToReg);
  3245. MapFormalsFromPattern(pnodeFnc, [&](ParseNode *pnode) { pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo); });
  3246. }
  3247. for (pnode = pnodeFnc->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  3248. {
  3249. sym = pnode->AsParseNodeVar()->sym;
  3250. if (!(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  3251. {
  3252. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  3253. {
  3254. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  3255. }
  3256. if (sym->GetSymbolType() == STVariable && !sym->IsArguments())
  3257. {
  3258. sym->EnsureScopeSlot(this, funcInfo);
  3259. }
  3260. }
  3261. }
  3262. auto ensureFncDeclScopeSlots = [&](ParseNode *pnodeScope)
  3263. {
  3264. for (pnode = pnodeScope; pnode;)
  3265. {
  3266. switch (pnode->nop)
  3267. {
  3268. case knopFncDecl:
  3269. if (pnode->AsParseNodeFnc()->IsDeclaration())
  3270. {
  3271. EnsureFncDeclScopeSlot(pnode->AsParseNodeFnc(), funcInfo);
  3272. }
  3273. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  3274. break;
  3275. case knopBlock:
  3276. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  3277. break;
  3278. case knopCatch:
  3279. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  3280. break;
  3281. case knopWith:
  3282. pnode = pnode->AsParseNodeWith()->pnodeNext;
  3283. break;
  3284. }
  3285. }
  3286. };
  3287. pnodeFnc->MapContainerScopes(ensureFncDeclScopeSlots);
  3288. if (pnodeFnc->pnodeBody)
  3289. {
  3290. Assert(pnodeFnc->pnodeScopes->nop == knopBlock);
  3291. this->EnsureLetConstScopeSlots(pnodeFnc->pnodeBodyScope, funcInfo);
  3292. }
  3293. }
  3294. else
  3295. {
  3296. ParseNode *pnode;
  3297. Symbol *sym;
  3298. pnodeFnc->MapContainerScopes([&](ParseNode *pnodeScope) { this->EnsureFncScopeSlots(pnodeScope, funcInfo); });
  3299. for (pnode = pnodeFnc->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  3300. {
  3301. sym = pnode->AsParseNodeVar()->sym;
  3302. if (!(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  3303. {
  3304. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  3305. {
  3306. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  3307. }
  3308. if (sym->GetSymbolType() == STVariable && sym->NeedsSlotAlloc(this, funcInfo) && !sym->IsArguments())
  3309. {
  3310. sym->EnsureScopeSlot(this, funcInfo);
  3311. }
  3312. }
  3313. }
  3314. auto ensureScopeSlot = [&](ParseNode *pnode)
  3315. {
  3316. if (pnode->IsVarLetOrConst())
  3317. {
  3318. sym = pnode->AsParseNodeVar()->sym;
  3319. if (sym->GetSymbolType() == STFormal && sym->NeedsSlotAlloc(this, funcInfo))
  3320. {
  3321. sym->EnsureScopeSlot(this, funcInfo);
  3322. }
  3323. }
  3324. };
  3325. // Process function's formal parameters
  3326. MapFormals(pnodeFnc, ensureScopeSlot);
  3327. MapFormalsFromPattern(pnodeFnc, ensureScopeSlot);
  3328. if (funcInfo->GetHasArguments())
  3329. {
  3330. sym = funcInfo->GetArgumentsSymbol();
  3331. Assert(sym);
  3332. // There is no eval so the arguments may be captured in a lambda.
  3333. // But we cannot relay on slots getting allocated while the lambda is emitted as the function body may be reparsed.
  3334. sym->EnsureScopeSlot(this, funcInfo);
  3335. }
  3336. if (pnodeFnc->pnodeBody)
  3337. {
  3338. this->EnsureLetConstScopeSlots(pnodeFnc->pnodeScopes, funcInfo);
  3339. this->EnsureLetConstScopeSlots(pnodeFnc->pnodeBodyScope, funcInfo);
  3340. }
  3341. }
  3342. // When we have split scope and body scope does not have any scope slots allocated, we don't have to mark the body scope as mustinstantiate.
  3343. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  3344. {
  3345. bodyScope->SetMustInstantiate(true);
  3346. }
  3347. else if (pnodeFnc->IsBodyAndParamScopeMerged() || bodyScope->GetScopeSlotCount() != 0)
  3348. {
  3349. bodyScope->SetMustInstantiate(funcInfo->frameSlotsRegister != Js::Constants::NoRegister);
  3350. if (pnodeFnc->IsBodyAndParamScopeMerged() && paramScope && paramScope->GetHasNestedParamFunc())
  3351. {
  3352. paramScope->SetMustInstantiate(funcInfo->frameSlotsRegister != Js::Constants::NoRegister);
  3353. }
  3354. }
  3355. if (!pnodeFnc->IsBodyAndParamScopeMerged())
  3356. {
  3357. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  3358. {
  3359. paramScope->SetMustInstantiate(true);
  3360. }
  3361. else
  3362. {
  3363. // In the case of function expression being captured in the param scope the hasownlocalinclosure will be false for param scope,
  3364. // as function expression symbol stays in the function expression scope. We don't have to set mustinstantiate for param scope in that case.
  3365. paramScope->SetMustInstantiate(paramScope->GetHasOwnLocalInClosure());
  3366. }
  3367. }
  3368. }
  3369. else
  3370. {
  3371. bool newScopeForEval = (funcInfo->byteCodeFunction->GetIsStrictMode() && (this->GetFlags() & fscrEval));
  3372. if (newScopeForEval)
  3373. {
  3374. Assert(bodyScope->GetIsObject());
  3375. }
  3376. }
  3377. }
  3378. PushFuncInfo(_u("StartEmitFunction"), funcInfo);
  3379. if (!funcInfo->IsBodyAndParamScopeMerged())
  3380. {
  3381. ParseNodeBlock * paramBlock = pnodeFnc->pnodeScopes;
  3382. Assert(paramBlock->blockType == Parameter);
  3383. PushScope(paramScope);
  3384. // While emitting the functions we have to stop when we see the body scope block.
  3385. // Otherwise functions defined in the body scope will not be able to get the right references.
  3386. this->EmitScopeList(paramBlock->pnodeScopes, pnodeFnc->pnodeBodyScope);
  3387. Assert(this->GetCurrentScope() == paramScope);
  3388. }
  3389. PushScope(bodyScope);
  3390. }
  3391. void ByteCodeGenerator::EmitModuleExportAccess(Symbol* sym, Js::OpCode opcode, Js::RegSlot location, FuncInfo* funcInfo)
  3392. {
  3393. if (EnsureSymbolModuleSlots(sym, funcInfo))
  3394. {
  3395. this->Writer()->SlotI2(opcode, location, sym->GetModuleIndex(), sym->GetScopeSlot());
  3396. }
  3397. else
  3398. {
  3399. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(ERRInvalidExportName));
  3400. if (opcode == Js::OpCode::LdModuleSlot)
  3401. {
  3402. this->Writer()->Reg1(Js::OpCode::LdUndef, location);
  3403. }
  3404. }
  3405. }
  3406. bool ByteCodeGenerator::EnsureSymbolModuleSlots(Symbol* sym, FuncInfo* funcInfo)
  3407. {
  3408. Assert(sym->GetIsModuleExportStorage());
  3409. if (sym->GetModuleIndex() != Js::Constants::NoProperty && sym->GetScopeSlot() != Js::Constants::NoProperty)
  3410. {
  3411. return true;
  3412. }
  3413. Js::JavascriptLibrary* library = this->GetScriptContext()->GetLibrary();
  3414. library->EnsureModuleRecordList();
  3415. uint moduleIndex = this->GetModuleID();
  3416. uint moduleSlotIndex;
  3417. Js::SourceTextModuleRecord* moduleRecord = library->GetModuleRecord(moduleIndex);
  3418. if (sym->GetIsModuleImport())
  3419. {
  3420. Js::PropertyId localImportNameId = sym->EnsurePosition(funcInfo);
  3421. Js::ModuleNameRecord* moduleNameRecord = nullptr;
  3422. if (!moduleRecord->ResolveImport(localImportNameId, &moduleNameRecord))
  3423. {
  3424. return false;
  3425. }
  3426. AnalysisAssert(moduleNameRecord != nullptr);
  3427. Assert(moduleNameRecord->module->IsSourceTextModuleRecord());
  3428. Js::SourceTextModuleRecord* resolvedModuleRecord =
  3429. (Js::SourceTextModuleRecord*)PointerValue(moduleNameRecord->module);
  3430. moduleIndex = resolvedModuleRecord->GetModuleId();
  3431. moduleSlotIndex = resolvedModuleRecord->GetLocalExportSlotIndexByLocalName(moduleNameRecord->bindingName);
  3432. }
  3433. else
  3434. {
  3435. Js::PropertyId exportNameId = sym->EnsurePosition(funcInfo);
  3436. moduleSlotIndex = moduleRecord->GetLocalExportSlotIndexByLocalName(exportNameId);
  3437. }
  3438. sym->SetModuleIndex(moduleIndex);
  3439. sym->SetScopeSlot(moduleSlotIndex);
  3440. return true;
  3441. }
  3442. void ByteCodeGenerator::EmitAssignmentToDefaultModuleExport(ParseNode* pnode, FuncInfo* funcInfo)
  3443. {
  3444. // We are assigning pnode to the default export of the current module.
  3445. uint moduleIndex = this->GetModuleID();
  3446. Js::JavascriptLibrary* library = this->GetScriptContext()->GetLibrary();
  3447. library->EnsureModuleRecordList();
  3448. Js::SourceTextModuleRecord* moduleRecord = library->GetModuleRecord(moduleIndex);
  3449. uint moduleSlotIndex = moduleRecord->GetLocalExportSlotIndexByExportName(Js::PropertyIds::default_);
  3450. this->Writer()->SlotI2(Js::OpCode::StModuleSlot, pnode->location, moduleIndex, moduleSlotIndex);
  3451. }
  3452. void ByteCodeGenerator::EnsureLetConstScopeSlots(ParseNodeBlock *pnodeBlock, FuncInfo *funcInfo)
  3453. {
  3454. bool callsEval = pnodeBlock->GetCallsEval() || pnodeBlock->GetChildCallsEval();
  3455. auto ensureLetConstSlots = ([this, funcInfo, callsEval](ParseNode *pnode)
  3456. {
  3457. Symbol *sym = pnode->AsParseNodeVar()->sym;
  3458. if (callsEval || sym->NeedsSlotAlloc(this, funcInfo))
  3459. {
  3460. sym->EnsureScopeSlot(this, funcInfo);
  3461. this->ProcessCapturedSym(sym);
  3462. }
  3463. });
  3464. IterateBlockScopedVariables(pnodeBlock, ensureLetConstSlots);
  3465. }
  3466. void ByteCodeGenerator::EnsureFncScopeSlots(ParseNode *pnode, FuncInfo *funcInfo)
  3467. {
  3468. while (pnode)
  3469. {
  3470. switch (pnode->nop)
  3471. {
  3472. case knopFncDecl:
  3473. if (pnode->AsParseNodeFnc()->IsDeclaration())
  3474. {
  3475. this->CheckFncDeclScopeSlot(pnode->AsParseNodeFnc(), funcInfo);
  3476. }
  3477. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  3478. break;
  3479. case knopBlock:
  3480. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  3481. break;
  3482. case knopCatch:
  3483. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  3484. break;
  3485. case knopWith:
  3486. pnode = pnode->AsParseNodeWith()->pnodeNext;
  3487. break;
  3488. }
  3489. }
  3490. }
  3491. void ByteCodeGenerator::EndEmitFunction(ParseNodeFnc *pnodeFnc)
  3492. {
  3493. Assert(pnodeFnc->nop == knopFncDecl || pnodeFnc->nop == knopProg);
  3494. Assert(pnodeFnc->nop == knopFncDecl && currentScope->GetEnclosingScope() != nullptr || pnodeFnc->nop == knopProg);
  3495. PopScope(); // function body
  3496. FuncInfo *funcInfo = pnodeFnc->funcInfo;
  3497. Scope* paramScope = funcInfo->paramScope;
  3498. if (!funcInfo->IsBodyAndParamScopeMerged())
  3499. {
  3500. Assert(this->GetCurrentScope() == paramScope);
  3501. PopScope(); // Pop the param scope
  3502. }
  3503. if (funcInfo->byteCodeFunction->IsFunctionParsed() && funcInfo->root->pnodeBody != nullptr)
  3504. {
  3505. // StartEmitFunction omits the matching PushScope for already-parsed functions.
  3506. // TODO: Refactor Start and EndEmitFunction for clarity.
  3507. Scope *scope = funcInfo->funcExprScope;
  3508. if (scope && scope->GetMustInstantiate())
  3509. {
  3510. Assert(currentScope == scope);
  3511. PopScope();
  3512. }
  3513. }
  3514. Assert(funcInfo == this->TopFuncInfo());
  3515. PopFuncInfo(_u("EndEmitFunction"));
  3516. }
  3517. void ByteCodeGenerator::StartEmitCatch(ParseNodeCatch *pnodeCatch)
  3518. {
  3519. Assert(pnodeCatch->nop == knopCatch);
  3520. Scope *scope = pnodeCatch->scope;
  3521. FuncInfo *funcInfo = scope->GetFunc();
  3522. // Catch scope is a dynamic object if it can be passed to a scoped lookup helper (i.e., eval is present or we're in an event handler).
  3523. if (funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval() || (this->flags & (fscrEval | fscrImplicitThis)))
  3524. {
  3525. scope->SetIsObject();
  3526. }
  3527. if (pnodeCatch->HasPatternParam())
  3528. {
  3529. ParseNode *pnode1 = pnodeCatch->GetParam()->AsParseNodeParamPattern()->pnode1;
  3530. scope->SetCapturesAll(funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval());
  3531. scope->SetMustInstantiate(scope->Count() > 0 && (scope->GetMustInstantiate() || scope->GetCapturesAll() || funcInfo->IsGlobalFunction()));
  3532. Parser::MapBindIdentifier(pnode1, [&](ParseNodePtr item)
  3533. {
  3534. Symbol *sym = item->AsParseNodeVar()->sym;
  3535. if (funcInfo->IsGlobalFunction())
  3536. {
  3537. sym->SetIsGlobalCatch(true);
  3538. }
  3539. if (sym->NeedsScopeObject())
  3540. {
  3541. scope->SetIsObject();
  3542. }
  3543. Assert(sym->GetScopeSlot() == Js::Constants::NoProperty);
  3544. if (sym->NeedsSlotAlloc(this, funcInfo))
  3545. {
  3546. sym->EnsureScopeSlot(this, funcInfo);
  3547. }
  3548. });
  3549. }
  3550. else if (pnodeCatch->HasParam())
  3551. {
  3552. Symbol *sym = pnodeCatch->GetParam()->AsParseNodeName()->sym;
  3553. // Catch object is stored in the catch scope if there may be an ambiguous lookup or a var declaration that hides it.
  3554. scope->SetCapturesAll(funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval() || sym->GetHasNonLocalReference());
  3555. scope->SetMustInstantiate(scope->GetCapturesAll() || funcInfo->IsGlobalFunction());
  3556. if (funcInfo->IsGlobalFunction())
  3557. {
  3558. sym->SetIsGlobalCatch(true);
  3559. }
  3560. if (sym->NeedsScopeObject())
  3561. {
  3562. scope->SetIsObject();
  3563. }
  3564. if (scope->GetMustInstantiate())
  3565. {
  3566. if (sym->IsInSlot(this, funcInfo))
  3567. {
  3568. // Since there is only one symbol we are pushing to slot.
  3569. // Also in order to make IsInSlot to return true - forcing the sym-has-non-local-reference.
  3570. this->ProcessCapturedSym(sym);
  3571. sym->EnsureScopeSlot(this, funcInfo);
  3572. }
  3573. }
  3574. }
  3575. PushScope(scope);
  3576. }
  3577. void ByteCodeGenerator::EndEmitCatch(ParseNodeCatch *pnodeCatch)
  3578. {
  3579. Assert(pnodeCatch->nop == knopCatch);
  3580. Assert(currentScope == pnodeCatch->scope);
  3581. PopScope();
  3582. }
  3583. void ByteCodeGenerator::StartEmitBlock(ParseNodeBlock *pnodeBlock)
  3584. {
  3585. if (!BlockHasOwnScope(pnodeBlock, this))
  3586. {
  3587. return;
  3588. }
  3589. Assert(pnodeBlock->nop == knopBlock);
  3590. PushBlock(pnodeBlock);
  3591. Scope *scope = pnodeBlock->scope;
  3592. if (pnodeBlock->GetCallsEval() || pnodeBlock->GetChildCallsEval() || (this->flags & (fscrEval | fscrImplicitThis)))
  3593. {
  3594. Assert(scope->GetIsObject());
  3595. }
  3596. // TODO: Consider nested deferred parsing.
  3597. if (scope->GetMustInstantiate())
  3598. {
  3599. FuncInfo *funcInfo = scope->GetFunc();
  3600. this->EnsureFncScopeSlots(pnodeBlock->pnodeScopes, funcInfo);
  3601. this->EnsureLetConstScopeSlots(pnodeBlock, funcInfo);
  3602. PushScope(scope);
  3603. }
  3604. }
  3605. void ByteCodeGenerator::EndEmitBlock(ParseNodeBlock *pnodeBlock)
  3606. {
  3607. if (!BlockHasOwnScope(pnodeBlock, this))
  3608. {
  3609. return;
  3610. }
  3611. Assert(pnodeBlock->nop == knopBlock);
  3612. Scope *scope = pnodeBlock->scope;
  3613. if (scope && scope->GetMustInstantiate())
  3614. {
  3615. Assert(currentScope == pnodeBlock->scope);
  3616. PopScope();
  3617. }
  3618. PopBlock();
  3619. }
  3620. void ByteCodeGenerator::StartEmitWith(ParseNode *pnodeWith)
  3621. {
  3622. Assert(pnodeWith->nop == knopWith);
  3623. Scope *scope = pnodeWith->AsParseNodeWith()->scope;
  3624. AssertOrFailFast(scope->GetIsObject());
  3625. PushScope(scope);
  3626. }
  3627. void ByteCodeGenerator::EndEmitWith(ParseNode *pnodeWith)
  3628. {
  3629. Assert(pnodeWith->nop == knopWith);
  3630. Assert(currentScope == pnodeWith->AsParseNodeWith()->scope);
  3631. PopScope();
  3632. }
  3633. Js::RegSlot ByteCodeGenerator::PrependLocalScopes(Js::RegSlot evalEnv, Js::RegSlot tempLoc, FuncInfo *funcInfo)
  3634. {
  3635. Scope *currScope = this->currentScope;
  3636. Scope *funcScope = funcInfo->GetCurrentChildScope() ? funcInfo->GetCurrentChildScope() : funcInfo->GetBodyScope();
  3637. if (currScope == funcScope)
  3638. {
  3639. return evalEnv;
  3640. }
  3641. bool acquireTempLoc = tempLoc == Js::Constants::NoRegister;
  3642. if (acquireTempLoc)
  3643. {
  3644. tempLoc = funcInfo->AcquireTmpRegister();
  3645. }
  3646. // The with/catch objects must be prepended to the environment we pass to eval() or to a func declared inside with,
  3647. // but the list must first be reversed so that innermost scopes appear first in the list.
  3648. while (currScope != funcScope)
  3649. {
  3650. Scope *innerScope;
  3651. for (innerScope = currScope; innerScope->GetEnclosingScope() != funcScope; innerScope = innerScope->GetEnclosingScope())
  3652. ;
  3653. if (innerScope->GetMustInstantiate())
  3654. {
  3655. if (!innerScope->HasInnerScopeIndex())
  3656. {
  3657. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  3658. {
  3659. this->m_writer.Reg2(Js::OpCode::LdInnerFrameDisplayNoParent, tempLoc, innerScope->GetLocation());
  3660. }
  3661. else
  3662. {
  3663. this->m_writer.Reg3(Js::OpCode::LdInnerFrameDisplay, tempLoc, innerScope->GetLocation(), evalEnv);
  3664. }
  3665. }
  3666. else
  3667. {
  3668. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  3669. {
  3670. this->m_writer.Reg1Unsigned1(Js::OpCode::LdIndexedFrameDisplayNoParent, tempLoc, innerScope->GetInnerScopeIndex());
  3671. }
  3672. else
  3673. {
  3674. this->m_writer.Reg2Int1(Js::OpCode::LdIndexedFrameDisplay, tempLoc, evalEnv, innerScope->GetInnerScopeIndex());
  3675. }
  3676. }
  3677. evalEnv = tempLoc;
  3678. }
  3679. funcScope = innerScope;
  3680. }
  3681. if (acquireTempLoc)
  3682. {
  3683. funcInfo->ReleaseTmpRegister(tempLoc);
  3684. }
  3685. return evalEnv;
  3686. }
  3687. void ByteCodeGenerator::EmitLoadInstance(Symbol *sym, IdentPtr pid, Js::RegSlot *pThisLocation, Js::RegSlot *pInstLocation, FuncInfo *funcInfo)
  3688. {
  3689. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  3690. Js::RegSlot thisLocation = *pThisLocation;
  3691. Js::RegSlot instLocation = *pInstLocation;
  3692. Js::PropertyId envIndex = -1;
  3693. Scope *scope = nullptr;
  3694. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  3695. Assert(symScope);
  3696. if (sym != nullptr && sym->GetIsModuleExportStorage())
  3697. {
  3698. *pInstLocation = Js::Constants::NoRegister;
  3699. return;
  3700. }
  3701. JsUtil::List<DynamicLoadRecord, ArenaAllocator> recList(this->alloc);
  3702. for (;;)
  3703. {
  3704. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  3705. if (scope == this->globalScope)
  3706. {
  3707. break;
  3708. }
  3709. if (scope != symScope)
  3710. {
  3711. // We're not sure where the function is (eval/with/etc).
  3712. // So we're going to need registers to hold the instance where we (dynamically) find
  3713. // the function, and possibly to hold the "this" pointer we will pass to it.
  3714. // Assign them here so that they can't overlap with the scopeLocation assigned below.
  3715. // Otherwise we wind up with temp lifetime confusion in the IRBuilder. (Win8 281689)
  3716. if (instLocation == Js::Constants::NoRegister)
  3717. {
  3718. instLocation = funcInfo->AcquireTmpRegister();
  3719. }
  3720. }
  3721. if (envIndex == -1)
  3722. {
  3723. Assert(funcInfo == scope->GetFunc());
  3724. scopeLocation = scope->GetLocation();
  3725. }
  3726. if (scope == symScope)
  3727. {
  3728. break;
  3729. }
  3730. // Found a scope to which the property may have been added.
  3731. Assert(scope && scope->GetIsDynamic());
  3732. AssertOrFailFast(scope->GetIsObject());
  3733. // Record dynamic scopes, in order. Define a label for each one. Remember whether we've seen a 'with'.
  3734. // For each dynamic scope, emit BrOnHas[Env,Local]Property $Ln, where n is the scope's position in the list
  3735. // Then emit code for default access (i.e., static binding). If no 'with', do not create a temp for 'this', just use 'undefined'.
  3736. // End static portion with 'Br $Ldone'.
  3737. // Then, for each item in list, emit:
  3738. // $Ln:
  3739. // copy dynamic scope to 'instance' temp, using 'reuse_loc' form of the opcode
  3740. // do the same for 'this' temp', only if we've seen a 'with'
  3741. // if not the last item in the list, Br $Ldone
  3742. DynamicLoadRecord rec;
  3743. rec.label = this->m_writer.DefineLabel();
  3744. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  3745. Js::PropertyIdIndexType propertyIndex = funcInfo->FindOrAddReferencedPropertyId(propertyId);
  3746. if (scope->GetScopeType() != ScopeType_With)
  3747. {
  3748. if (envIndex == -1)
  3749. {
  3750. // The local body scope. Branch cannot bail on implicit calls.
  3751. this->m_writer.BrLocalProperty(Js::OpCode::BrOnHasLocalProperty, rec.label, propertyIndex);
  3752. rec.kind = DynamicLoadKind::Local;
  3753. }
  3754. else
  3755. {
  3756. // Function body scope in an enclosing function that calls eval.
  3757. // Emit a branch opcode that does not require bail on implicit calls.
  3758. uint32 frameDisplayIndex = envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var);
  3759. this->m_writer.BrEnvProperty(Js::OpCode::BrOnHasLocalEnvProperty, rec.label, propertyIndex, frameDisplayIndex);
  3760. rec.kind = DynamicLoadKind::Env;
  3761. rec.index = frameDisplayIndex;
  3762. }
  3763. }
  3764. else
  3765. {
  3766. if (thisLocation == Js::Constants::NoRegister)
  3767. {
  3768. thisLocation = funcInfo->AcquireTmpRegister();
  3769. }
  3770. if (envIndex == -1)
  3771. {
  3772. // With object declared in this function. HasProperty may have implicit calls.
  3773. this->m_writer.BrProperty(Js::OpCode::BrOnHasProperty, rec.label, scopeLocation, propertyIndex);
  3774. rec.kind = DynamicLoadKind::LocalWith;
  3775. rec.instance = scopeLocation;
  3776. }
  3777. else
  3778. {
  3779. // With object declared in an enclosing function. HasProperty may have implicit calls.
  3780. uint32 frameDisplayIndex = envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var);
  3781. this->m_writer.BrEnvProperty(Js::OpCode::BrOnHasEnvProperty, rec.label, propertyIndex, frameDisplayIndex);
  3782. rec.kind = DynamicLoadKind::EnvWith;
  3783. rec.index = frameDisplayIndex;
  3784. }
  3785. }
  3786. recList.Add(rec);
  3787. }
  3788. if (sym == nullptr || sym->GetIsGlobal())
  3789. {
  3790. if (this->flags & (fscrEval | fscrImplicitThis))
  3791. {
  3792. // Load of a symbol with unknown scope from within eval.
  3793. // Get it from the closure environment.
  3794. if (instLocation == Js::Constants::NoRegister)
  3795. {
  3796. instLocation = funcInfo->AcquireTmpRegister();
  3797. }
  3798. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  3799. if (thisLocation == Js::Constants::NoRegister)
  3800. {
  3801. thisLocation = funcInfo->AcquireTmpRegister();
  3802. }
  3803. this->m_writer.ScopedProperty2(Js::OpCode::ScopedLdInst, instLocation,
  3804. funcInfo->FindOrAddReferencedPropertyId(propertyId), thisLocation);
  3805. }
  3806. else
  3807. {
  3808. if (instLocation == Js::Constants::NoRegister)
  3809. {
  3810. instLocation = ByteCodeGenerator::RootObjectRegister;
  3811. }
  3812. else
  3813. {
  3814. this->m_writer.Reg2(Js::OpCode::Ld_A, instLocation, ByteCodeGenerator::RootObjectRegister);
  3815. }
  3816. if (thisLocation == Js::Constants::NoRegister)
  3817. {
  3818. thisLocation = funcInfo->undefinedConstantRegister;
  3819. }
  3820. else
  3821. {
  3822. this->m_writer.Reg2(Js::OpCode::Ld_A, thisLocation, funcInfo->undefinedConstantRegister);
  3823. }
  3824. }
  3825. }
  3826. else if (instLocation != Js::Constants::NoRegister)
  3827. {
  3828. if (envIndex != -1)
  3829. {
  3830. AssertOrFailFast(scope->GetIsObject());
  3831. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation,
  3832. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  3833. }
  3834. else if (scope->HasInnerScopeIndex())
  3835. {
  3836. this->m_writer.Reg1Unsigned1(Js::OpCode::LdInnerScope, instLocation, scope->GetInnerScopeIndex());
  3837. }
  3838. else if (symScope == funcInfo->GetParamScope())
  3839. {
  3840. Assert(funcInfo->frameObjRegister != Js::Constants::NoRegister && !funcInfo->IsBodyAndParamScopeMerged());
  3841. this->m_writer.Reg1(Js::OpCode::LdParamObj, instLocation);
  3842. }
  3843. else if (symScope != funcInfo->GetBodyScope())
  3844. {
  3845. this->m_writer.Reg2(Js::OpCode::Ld_A, instLocation, scopeLocation);
  3846. }
  3847. else
  3848. {
  3849. Assert(funcInfo->frameObjRegister != Js::Constants::NoRegister);
  3850. this->m_writer.Reg1(Js::OpCode::LdLocalObj, instLocation);
  3851. }
  3852. if (thisLocation != Js::Constants::NoRegister)
  3853. {
  3854. this->m_writer.Reg2(Js::OpCode::Ld_A, thisLocation, funcInfo->undefinedConstantRegister);
  3855. }
  3856. else
  3857. {
  3858. thisLocation = funcInfo->undefinedConstantRegister;
  3859. }
  3860. }
  3861. if (!recList.Empty())
  3862. {
  3863. Assert(instLocation != Js::Constants::NoRegister);
  3864. Assert(thisLocation != Js::Constants::NoRegister);
  3865. Js::ByteCodeLabel doneLabel = this->m_writer.DefineLabel();
  3866. this->m_writer.Br(doneLabel);
  3867. for (int i = 0;; i++)
  3868. {
  3869. this->m_writer.MarkLabel(recList.Item(i).label);
  3870. switch(recList.Item(i).kind)
  3871. {
  3872. case DynamicLoadKind::Local:
  3873. this->m_writer.Reg1(Js::OpCode::LdLocalObj_ReuseLoc, instLocation);
  3874. if (thisLocation != funcInfo->undefinedConstantRegister)
  3875. {
  3876. Assert(thisLocation != instLocation);
  3877. this->m_writer.Reg2(Js::OpCode::Ld_A_ReuseLoc, thisLocation, funcInfo->undefinedConstantRegister);
  3878. }
  3879. break;
  3880. case DynamicLoadKind::Env:
  3881. this->m_writer.SlotI1(Js::OpCode::LdEnvObj_ReuseLoc, instLocation, recList.Item(i).index);
  3882. if (thisLocation != funcInfo->undefinedConstantRegister)
  3883. {
  3884. Assert(thisLocation != instLocation);
  3885. this->m_writer.Reg2(Js::OpCode::Ld_A_ReuseLoc, thisLocation, funcInfo->undefinedConstantRegister);
  3886. }
  3887. break;
  3888. case DynamicLoadKind::LocalWith:
  3889. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj_ReuseLoc, instLocation, recList.Item(i).instance);
  3890. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj_ReuseLoc, thisLocation, recList.Item(i).instance);
  3891. break;
  3892. case DynamicLoadKind::EnvWith:
  3893. {
  3894. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  3895. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, tmpReg, recList.Item(i).index);
  3896. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj_ReuseLoc, instLocation, tmpReg);
  3897. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj_ReuseLoc, thisLocation, tmpReg);
  3898. funcInfo->ReleaseTmpRegister(tmpReg);
  3899. break;
  3900. }
  3901. default:
  3902. AssertOrFailFast(UNREACHED);
  3903. }
  3904. if (i == recList.Count() - 1)
  3905. {
  3906. break;
  3907. }
  3908. this->m_writer.Br(doneLabel);
  3909. }
  3910. this->m_writer.MarkLabel(doneLabel);
  3911. }
  3912. *pThisLocation = thisLocation;
  3913. *pInstLocation = instLocation;
  3914. }
  3915. void ByteCodeGenerator::EmitGlobalFncDeclInit(Js::RegSlot rhsLocation, Js::PropertyId propertyId, FuncInfo * funcInfo)
  3916. {
  3917. // Note: declared variables and assignments in the global function go to the root object directly.
  3918. if (this->flags & fscrEval)
  3919. {
  3920. // Func decl's always get their init values before any use, so we don't pre-initialize the property to undef.
  3921. // That means that we have to use ScopedInitFld so that we initialize the property on the right instance
  3922. // even if the instance doesn't have the property yet (i.e., collapse the init-to-undef and the store
  3923. // into one operation). See WOOB 1121763 and 1120973.
  3924. this->m_writer.ScopedProperty(Js::OpCode::ScopedInitFunc, rhsLocation,
  3925. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  3926. }
  3927. else
  3928. {
  3929. this->EmitPatchableRootProperty(Js::OpCode::InitRootFld, rhsLocation, propertyId, false, true, funcInfo);
  3930. }
  3931. }
  3932. void
  3933. ByteCodeGenerator::EmitPatchableRootProperty(Js::OpCode opcode,
  3934. Js::RegSlot regSlot, Js::PropertyId propertyId, bool isLoadMethod, bool isStore, FuncInfo * funcInfo)
  3935. {
  3936. uint cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, isLoadMethod, isStore);
  3937. this->m_writer.PatchableRootProperty(opcode, regSlot, cacheId, isLoadMethod, isStore);
  3938. }
  3939. void ByteCodeGenerator::EmitLocalPropInit(Js::RegSlot rhsLocation, Symbol *sym, FuncInfo *funcInfo)
  3940. {
  3941. Scope *scope = sym->GetScope();
  3942. // Check consistency of sym->IsInSlot.
  3943. Assert(sym->NeedsSlotAlloc(this, funcInfo) || sym->GetScopeSlot() == Js::Constants::NoProperty);
  3944. // Arrived at the scope in which the property was defined.
  3945. if (sym->NeedsSlotAlloc(this, funcInfo))
  3946. {
  3947. // The property is in memory rather than register. We'll have to load it from the slots.
  3948. if (scope->GetIsObject())
  3949. {
  3950. Assert(!this->TopFuncInfo()->GetParsedFunctionBody()->DoStackNestedFunc());
  3951. Js::PropertyId propertyId = sym->EnsurePosition(this);
  3952. Js::RegSlot objReg;
  3953. if (scope->HasInnerScopeIndex())
  3954. {
  3955. objReg = funcInfo->InnerScopeToRegSlot(scope);
  3956. }
  3957. else
  3958. {
  3959. objReg = scope->GetLocation();
  3960. }
  3961. uint cacheId = funcInfo->FindOrAddInlineCacheId(objReg, propertyId, false, true);
  3962. Js::OpCode op = this->GetInitFldOp(scope, objReg, funcInfo, sym->GetIsNonSimpleParameter());
  3963. if (objReg != Js::Constants::NoRegister && objReg == funcInfo->frameObjRegister)
  3964. {
  3965. this->m_writer.ElementP(op, rhsLocation, cacheId);
  3966. }
  3967. else if (scope->HasInnerScopeIndex())
  3968. {
  3969. this->m_writer.ElementPIndexed(op, rhsLocation, scope->GetInnerScopeIndex(), cacheId);
  3970. }
  3971. else
  3972. {
  3973. this->m_writer.PatchableProperty(op, rhsLocation, scope->GetLocation(), cacheId);
  3974. }
  3975. }
  3976. else
  3977. {
  3978. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  3979. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  3980. Js::RegSlot slotReg = scope->GetCanMerge() ? funcInfo->frameSlotsRegister : scope->GetLocation();
  3981. // Now store the property to its slot.
  3982. Js::OpCode op = this->GetStSlotOp(scope, -1, slotReg, false, funcInfo);
  3983. if (slotReg != Js::Constants::NoRegister && slotReg == funcInfo->frameSlotsRegister)
  3984. {
  3985. this->m_writer.SlotI1(op, rhsLocation, slot + Js::ScopeSlots::FirstSlotIndex);
  3986. }
  3987. else
  3988. {
  3989. this->m_writer.SlotI2(op, rhsLocation, scope->GetInnerScopeIndex(), slot + Js::ScopeSlots::FirstSlotIndex);
  3990. }
  3991. }
  3992. }
  3993. if (sym->GetLocation() != Js::Constants::NoRegister && rhsLocation != sym->GetLocation())
  3994. {
  3995. this->m_writer.Reg2(Js::OpCode::Ld_A, sym->GetLocation(), rhsLocation);
  3996. }
  3997. }
  3998. Js::OpCode
  3999. ByteCodeGenerator::GetStSlotOp(Scope *scope, int envIndex, Js::RegSlot scopeLocation, bool chkBlockVar, FuncInfo *funcInfo)
  4000. {
  4001. Js::OpCode op;
  4002. if (envIndex != -1)
  4003. {
  4004. if (scope->GetIsObject())
  4005. {
  4006. op = Js::OpCode::StEnvObjSlot;
  4007. }
  4008. else
  4009. {
  4010. op = Js::OpCode::StEnvSlot;
  4011. }
  4012. }
  4013. else if (scopeLocation != Js::Constants::NoRegister &&
  4014. scopeLocation == funcInfo->frameSlotsRegister)
  4015. {
  4016. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  4017. {
  4018. // Symbol is from the param scope of a split scope function and we are emitting the body.
  4019. // We should use the param scope's bytecode now.
  4020. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  4021. op = Js::OpCode::StParamSlot;
  4022. }
  4023. else
  4024. {
  4025. op = Js::OpCode::StLocalSlot;
  4026. }
  4027. }
  4028. else if (scopeLocation != Js::Constants::NoRegister &&
  4029. scopeLocation == funcInfo->frameObjRegister)
  4030. {
  4031. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  4032. {
  4033. // Symbol is from the param scope of a split scope function and we are emitting the body.
  4034. // We should use the param scope's bytecode now.
  4035. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  4036. op = Js::OpCode::StParamObjSlot;
  4037. }
  4038. else
  4039. {
  4040. op = Js::OpCode::StLocalObjSlot;
  4041. }
  4042. }
  4043. else
  4044. {
  4045. Assert(scope->HasInnerScopeIndex());
  4046. if (scope->GetIsObject())
  4047. {
  4048. op = Js::OpCode::StInnerObjSlot;
  4049. }
  4050. else
  4051. {
  4052. op = Js::OpCode::StInnerSlot;
  4053. }
  4054. }
  4055. if (chkBlockVar)
  4056. {
  4057. op = this->ToChkUndeclOp(op);
  4058. }
  4059. return op;
  4060. }
  4061. Js::OpCode
  4062. ByteCodeGenerator::GetInitFldOp(Scope *scope, Js::RegSlot scopeLocation, FuncInfo *funcInfo, bool letDecl)
  4063. {
  4064. Js::OpCode op;
  4065. if (scopeLocation != Js::Constants::NoRegister &&
  4066. scopeLocation == funcInfo->frameObjRegister)
  4067. {
  4068. op = letDecl ? Js::OpCode::InitLocalLetFld : Js::OpCode::InitLocalFld;
  4069. }
  4070. else if (scope->HasInnerScopeIndex())
  4071. {
  4072. op = letDecl ? Js::OpCode::InitInnerLetFld : Js::OpCode::InitInnerFld;
  4073. }
  4074. else
  4075. {
  4076. op = letDecl ? Js::OpCode::InitLetFld : Js::OpCode::InitFld;
  4077. }
  4078. return op;
  4079. }
  4080. void ByteCodeGenerator::EmitPropStore(Js::RegSlot rhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool isLetDecl, bool isConstDecl, bool isFncDeclVar, bool skipUseBeforeDeclarationCheck)
  4081. {
  4082. Js::PropertyId envIndex = -1;
  4083. Scope *symScope = sym == nullptr || sym->GetIsGlobal() ? this->globalScope : sym->GetScope();
  4084. Assert(symScope);
  4085. // isFncDeclVar denotes that the symbol being stored to here is the var
  4086. // binding of a function declaration and we know we want to store directly
  4087. // to it, skipping over any dynamic scopes that may lie in between.
  4088. Scope *scope = nullptr;
  4089. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4090. Js::OpCode op;
  4091. if (sym && sym->GetIsModuleExportStorage())
  4092. {
  4093. if (!isConstDecl && sym->GetDecl() && sym->GetDecl()->nop == knopConstDecl)
  4094. {
  4095. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4096. }
  4097. EmitModuleExportAccess(sym, Js::OpCode::StModuleSlot, rhsLocation, funcInfo);
  4098. return;
  4099. }
  4100. if (isFncDeclVar)
  4101. {
  4102. // async functions allow for the fncDeclVar to be in the body or parameter scope
  4103. // of the parent function, so we need to calculate envIndex in lieu of the while
  4104. // loop below.
  4105. do
  4106. {
  4107. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4108. } while (scope != symScope);
  4109. Assert(scope == symScope);
  4110. scopeLocation = scope->GetLocation();
  4111. }
  4112. JsUtil::List<DynamicLoadRecord, ArenaAllocator> recList(this->alloc);
  4113. while (!isFncDeclVar)
  4114. {
  4115. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4116. if (scope == this->globalScope)
  4117. {
  4118. break;
  4119. }
  4120. if (envIndex == -1)
  4121. {
  4122. Assert(funcInfo == scope->GetFunc());
  4123. scopeLocation = scope->GetLocation();
  4124. }
  4125. if (scope == symScope)
  4126. {
  4127. break;
  4128. }
  4129. // Found a scope to which the property may have been added.
  4130. Assert(scope && scope->GetIsDynamic());
  4131. AssertOrFailFast(scope->GetIsObject());
  4132. DynamicLoadRecord rec;
  4133. rec.label = this->m_writer.DefineLabel();
  4134. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4135. Js::PropertyIdIndexType propertyIndex = funcInfo->FindOrAddReferencedPropertyId(propertyId);
  4136. if (scope->GetScopeType() != ScopeType_With)
  4137. {
  4138. if (envIndex == -1)
  4139. {
  4140. this->m_writer.BrLocalProperty(Js::OpCode::BrOnHasLocalProperty, rec.label, propertyIndex);
  4141. rec.kind = DynamicLoadKind::Local;
  4142. rec.instance = scopeLocation;
  4143. }
  4144. else
  4145. {
  4146. uint32 frameDisplayIndex = envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var);
  4147. this->m_writer.BrEnvProperty(Js::OpCode::BrOnHasLocalEnvProperty, rec.label, propertyIndex, frameDisplayIndex);
  4148. rec.kind = DynamicLoadKind::Env;
  4149. rec.index = frameDisplayIndex;
  4150. }
  4151. }
  4152. else
  4153. {
  4154. if (envIndex == -1)
  4155. {
  4156. this->m_writer.BrProperty(Js::OpCode::BrOnHasProperty, rec.label, scopeLocation, propertyIndex);
  4157. rec.kind = DynamicLoadKind::LocalWith;
  4158. rec.instance = scopeLocation;
  4159. }
  4160. else
  4161. {
  4162. uint32 frameDisplayIndex = envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var);
  4163. this->m_writer.BrEnvProperty(Js::OpCode::BrOnHasEnvProperty, rec.label, propertyIndex, frameDisplayIndex);
  4164. rec.kind = DynamicLoadKind::EnvWith;
  4165. rec.index = frameDisplayIndex;
  4166. }
  4167. }
  4168. recList.Add(rec);
  4169. }
  4170. // Arrived at the scope in which the property was defined.
  4171. if (!skipUseBeforeDeclarationCheck && sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo)
  4172. {
  4173. EmitUseBeforeDeclarationRuntimeError(this, Js::Constants::NoRegister);
  4174. // Intentionally continue on to do normal EmitPropStore behavior so
  4175. // that the bytecode ends up well-formed for the backend. This is
  4176. // in contrast to EmitPropLoad and EmitPropTypeof where they both
  4177. // tell EmitUseBeforeDeclarationRuntimeError to emit a LdUndef in place
  4178. // of their load and then they skip emitting their own bytecode.
  4179. // Potayto potahto.
  4180. }
  4181. if (sym == nullptr || sym->GetIsGlobal())
  4182. {
  4183. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4184. bool isConsoleScopeLetConst = this->IsConsoleScopeEval() && (isLetDecl || isConstDecl);
  4185. if (this->flags & fscrEval)
  4186. {
  4187. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4188. {
  4189. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->frameDisplayRegister, propertyId, false, true);
  4190. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo, isConsoleScopeLetConst), rhsLocation, cacheId);
  4191. }
  4192. else
  4193. {
  4194. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, true);
  4195. // In "eval", store to a symbol with unknown scope goes through the closure environment.
  4196. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo, isConsoleScopeLetConst), rhsLocation, cacheId);
  4197. }
  4198. }
  4199. else if (this->flags & fscrImplicitThis)
  4200. {
  4201. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, true);
  4202. // In HTML event handler, store to a symbol with unknown scope goes through the closure environment.
  4203. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo, isConsoleScopeLetConst), rhsLocation, cacheId);
  4204. }
  4205. else
  4206. {
  4207. this->EmitPatchableRootProperty(GetStFldOpCode(funcInfo, true, isLetDecl, isConstDecl, false, forceStrictModeForClassComputedPropertyName), rhsLocation, propertyId, false, true, funcInfo);
  4208. }
  4209. }
  4210. else if (sym->GetIsFuncExpr())
  4211. {
  4212. // Store to function expr variable.
  4213. // strict mode: we need to throw type error
  4214. if (funcInfo->byteCodeFunction->GetIsStrictMode())
  4215. {
  4216. // Note that in this case the sym's location belongs to the parent function, so we can't use it.
  4217. // It doesn't matter which register we use, as long as it's valid for this function.
  4218. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_CantAssignToReadOnly));
  4219. }
  4220. }
  4221. else if (sym->IsInSlot(this, funcInfo) || envIndex != -1)
  4222. {
  4223. if (!isConstDecl && sym->GetIsConst())
  4224. {
  4225. // This is a case where const reassignment can't be proven statically (e.g., eval, with) so
  4226. // we have to catch it at runtime.
  4227. this->m_writer.W1(
  4228. Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4229. }
  4230. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4231. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4232. bool chkBlockVar = !isLetDecl && !isConstDecl && NeedCheckBlockVar(sym, scope, funcInfo);
  4233. // The property is in memory rather than register. We'll have to load it from the slots.
  4234. op = this->GetStSlotOp(scope, envIndex, scopeLocation, chkBlockVar, funcInfo);
  4235. if (envIndex != -1)
  4236. {
  4237. this->m_writer.SlotI2(op, rhsLocation,
  4238. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var),
  4239. slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex));
  4240. }
  4241. else if (scopeLocation != Js::Constants::NoRegister &&
  4242. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4243. {
  4244. this->m_writer.SlotI1(op, rhsLocation,
  4245. slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex));
  4246. }
  4247. else
  4248. {
  4249. Assert(scope->HasInnerScopeIndex());
  4250. this->m_writer.SlotI2(op, rhsLocation, scope->GetInnerScopeIndex(),
  4251. slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex));
  4252. }
  4253. if (this->ShouldTrackDebuggerMetadata() && (isLetDecl || isConstDecl))
  4254. {
  4255. Js::PropertyId location = scope->GetIsObject() ? sym->GetLocation() : slot;
  4256. this->UpdateDebuggerPropertyInitializationOffset(location, sym->GetPosition(), false);
  4257. }
  4258. }
  4259. else
  4260. {
  4261. if (!isConstDecl && sym->GetDecl() && sym->GetDecl()->nop == knopConstDecl)
  4262. {
  4263. // This is a case where const reassignment can't be proven statically (e.g., eval, with) so
  4264. // we have to catch it at runtime.
  4265. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4266. }
  4267. if (rhsLocation != sym->GetLocation())
  4268. {
  4269. this->m_writer.Reg2(Js::OpCode::Ld_A, sym->GetLocation(), rhsLocation);
  4270. if (this->ShouldTrackDebuggerMetadata() && (isLetDecl || isConstDecl))
  4271. {
  4272. this->UpdateDebuggerPropertyInitializationOffset(sym->GetLocation(), sym->GetPosition());
  4273. }
  4274. }
  4275. }
  4276. if (!recList.Empty())
  4277. {
  4278. Js::ByteCodeLabel doneLabel = this->m_writer.DefineLabel();
  4279. this->m_writer.Br(doneLabel);
  4280. for (int i = 0;; i++)
  4281. {
  4282. uint cacheId;
  4283. Js::RegSlot instLocation;
  4284. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4285. this->m_writer.MarkLabel(recList.Item(i).label);
  4286. switch(recList.Item(i).kind)
  4287. {
  4288. case DynamicLoadKind::Local:
  4289. cacheId = funcInfo->FindOrAddInlineCacheId(recList.Item(i).instance, propertyId, false, true);
  4290. this->m_writer.ElementP(Js::OpCode::StLocalFld, rhsLocation, cacheId);
  4291. break;
  4292. case DynamicLoadKind::Env:
  4293. instLocation = funcInfo->AcquireTmpRegister();
  4294. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation, recList.Item(i).index);
  4295. cacheId = funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, true);
  4296. this->m_writer.PatchableProperty(Js::OpCode::StFld, rhsLocation, instLocation, cacheId);
  4297. funcInfo->ReleaseTmpRegister(instLocation);
  4298. break;
  4299. case DynamicLoadKind::LocalWith:
  4300. instLocation = funcInfo->AcquireTmpRegister();
  4301. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, recList.Item(i).instance);
  4302. cacheId = funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, true);
  4303. this->m_writer.PatchableProperty(Js::OpCode::StFld, rhsLocation, instLocation, cacheId);
  4304. funcInfo->ReleaseTmpRegister(instLocation);
  4305. break;
  4306. case DynamicLoadKind::EnvWith:
  4307. instLocation = funcInfo->AcquireTmpRegister();
  4308. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation, recList.Item(i).index);
  4309. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4310. cacheId = funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, true);
  4311. this->m_writer.PatchableProperty(Js::OpCode::StFld, rhsLocation, instLocation, cacheId);
  4312. funcInfo->ReleaseTmpRegister(instLocation);
  4313. break;
  4314. default:
  4315. AssertOrFailFast(UNREACHED);
  4316. }
  4317. if (i == recList.Count() - 1)
  4318. {
  4319. break;
  4320. }
  4321. this->m_writer.Br(doneLabel);
  4322. }
  4323. this->m_writer.MarkLabel(doneLabel);
  4324. }
  4325. }
  4326. Js::OpCode
  4327. ByteCodeGenerator::GetLdSlotOp(Scope *scope, int envIndex, Js::RegSlot scopeLocation, FuncInfo *funcInfo)
  4328. {
  4329. Js::OpCode op;
  4330. if (envIndex != -1)
  4331. {
  4332. if (scope->GetIsObject())
  4333. {
  4334. op = Js::OpCode::LdEnvObjSlot;
  4335. }
  4336. else
  4337. {
  4338. op = Js::OpCode::LdEnvSlot;
  4339. }
  4340. }
  4341. else if (scopeLocation != Js::Constants::NoRegister &&
  4342. scopeLocation == funcInfo->frameSlotsRegister)
  4343. {
  4344. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  4345. {
  4346. // Symbol is from the param scope of a split scope function and we are emitting the body.
  4347. // We should use the param scope's bytecode now.
  4348. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  4349. op = Js::OpCode::LdParamSlot;
  4350. }
  4351. else
  4352. {
  4353. op = Js::OpCode::LdLocalSlot;
  4354. }
  4355. }
  4356. else if (scopeLocation != Js::Constants::NoRegister &&
  4357. scopeLocation == funcInfo->frameObjRegister)
  4358. {
  4359. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  4360. {
  4361. // Symbol is from the param scope of a split scope function and we are emitting the body.
  4362. // We should use the param scope's bytecode now.
  4363. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  4364. op = Js::OpCode::LdParamObjSlot;
  4365. }
  4366. else
  4367. {
  4368. op = Js::OpCode::LdLocalObjSlot;
  4369. }
  4370. }
  4371. else if (scope->HasInnerScopeIndex())
  4372. {
  4373. if (scope->GetIsObject())
  4374. {
  4375. op = Js::OpCode::LdInnerObjSlot;
  4376. }
  4377. else
  4378. {
  4379. op = Js::OpCode::LdInnerSlot;
  4380. }
  4381. }
  4382. else
  4383. {
  4384. AssertOrFailFast(scope->GetIsObject());
  4385. op = Js::OpCode::LdObjSlot;
  4386. }
  4387. return op;
  4388. }
  4389. bool ByteCodeGenerator::ShouldLoadConstThis(FuncInfo* funcInfo)
  4390. {
  4391. #if DBG
  4392. // We should load a const 'this' binding if the following holds
  4393. // - The function has a 'this' name node
  4394. // - We are in a global or global lambda function
  4395. // - The function has no 'this' symbol (an indirect eval would have this symbol)
  4396. if (funcInfo->thisConstantRegister != Js::Constants::NoRegister)
  4397. {
  4398. Assert((funcInfo->IsLambda() || funcInfo->IsGlobalFunction())
  4399. && !funcInfo->GetThisSymbol()
  4400. && !(this->flags & fscrEval));
  4401. }
  4402. #endif
  4403. return funcInfo->thisConstantRegister != Js::Constants::NoRegister;
  4404. }
  4405. void ByteCodeGenerator::EmitPropLoadThis(Js::RegSlot lhsLocation, ParseNodeSpecialName *pnodeSpecialName, FuncInfo *funcInfo, bool chkUndecl)
  4406. {
  4407. Symbol* sym = pnodeSpecialName->sym;
  4408. if (!sym && this->ShouldLoadConstThis(funcInfo))
  4409. {
  4410. this->Writer()->Reg2(Js::OpCode::Ld_A, lhsLocation, funcInfo->thisConstantRegister);
  4411. }
  4412. else
  4413. {
  4414. this->EmitPropLoad(lhsLocation, pnodeSpecialName->sym, pnodeSpecialName->pid, funcInfo, true);
  4415. if ((!sym || sym->GetNeedDeclaration()) && chkUndecl)
  4416. {
  4417. this->Writer()->Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4418. }
  4419. }
  4420. }
  4421. void ByteCodeGenerator::EmitPropStoreForSpecialSymbol(Js::RegSlot rhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool init)
  4422. {
  4423. if (!funcInfo->IsGlobalFunction() || (this->flags & fscrEval))
  4424. {
  4425. if (init)
  4426. {
  4427. EmitLocalPropInit(rhsLocation, sym, funcInfo);
  4428. }
  4429. else
  4430. {
  4431. EmitPropStore(rhsLocation, sym, pid, funcInfo, false, false, false, true);
  4432. }
  4433. }
  4434. }
  4435. void ByteCodeGenerator::EmitPropLoad(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool skipUseBeforeDeclarationCheck)
  4436. {
  4437. // If sym belongs to a parent frame, get it from the closure environment.
  4438. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4439. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4440. // Otherwise, just copy the value to the lhsLocation.
  4441. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4442. Js::PropertyId envIndex = -1;
  4443. Scope *scope = nullptr;
  4444. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4445. Assert(symScope);
  4446. if (sym && sym->GetIsModuleExportStorage())
  4447. {
  4448. EmitModuleExportAccess(sym, Js::OpCode::LdModuleSlot, lhsLocation, funcInfo);
  4449. return;
  4450. }
  4451. JsUtil::List<DynamicLoadRecord, ArenaAllocator> recList(this->alloc);
  4452. for (;;)
  4453. {
  4454. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4455. if (scope == this->globalScope)
  4456. {
  4457. break;
  4458. }
  4459. scopeLocation = scope->GetLocation();
  4460. if (scope == symScope)
  4461. {
  4462. break;
  4463. }
  4464. // Found a scope to which the property may have been added.
  4465. Assert(scope && scope->GetIsDynamic());
  4466. AssertOrFailFast(scope->GetIsObject());
  4467. DynamicLoadRecord rec;
  4468. rec.label = this->m_writer.DefineLabel();
  4469. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4470. Js::PropertyIdIndexType propertyIndex = funcInfo->FindOrAddReferencedPropertyId(propertyId);
  4471. if (scope->GetScopeType() != ScopeType_With)
  4472. {
  4473. if (envIndex == -1)
  4474. {
  4475. this->m_writer.BrLocalProperty(Js::OpCode::BrOnHasLocalProperty, rec.label, propertyIndex);
  4476. rec.kind = DynamicLoadKind::Local;
  4477. rec.instance = scopeLocation;
  4478. }
  4479. else
  4480. {
  4481. uint32 frameDisplayIndex = envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var);
  4482. this->m_writer.BrEnvProperty(Js::OpCode::BrOnHasLocalEnvProperty, rec.label, propertyIndex, frameDisplayIndex);
  4483. rec.kind = DynamicLoadKind::Env;
  4484. rec.index = frameDisplayIndex;
  4485. }
  4486. }
  4487. else
  4488. {
  4489. if (envIndex == -1)
  4490. {
  4491. this->m_writer.BrProperty(Js::OpCode::BrOnHasProperty, rec.label, scopeLocation, propertyIndex);
  4492. rec.kind = DynamicLoadKind::LocalWith;
  4493. rec.instance = scopeLocation;
  4494. }
  4495. else
  4496. {
  4497. uint32 frameDisplayIndex = envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var);
  4498. this->m_writer.BrEnvProperty(Js::OpCode::BrOnHasEnvProperty, rec.label, propertyIndex, frameDisplayIndex);
  4499. rec.kind = DynamicLoadKind::EnvWith;
  4500. rec.index = frameDisplayIndex;
  4501. }
  4502. }
  4503. recList.Add(rec);
  4504. }
  4505. // Arrived at the scope in which the property was defined.
  4506. if (sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo && !skipUseBeforeDeclarationCheck)
  4507. {
  4508. // Ensure this symbol has a slot if it needs one.
  4509. if (sym->IsInSlot(this, funcInfo))
  4510. {
  4511. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4512. funcInfo->FindOrAddSlotProfileId(scope, slot);
  4513. }
  4514. if (skipUseBeforeDeclarationCheck)
  4515. {
  4516. if (lhsLocation != Js::Constants::NoRegister)
  4517. {
  4518. this->m_writer.Reg1(Js::OpCode::InitUndecl, lhsLocation);
  4519. }
  4520. }
  4521. else
  4522. {
  4523. EmitUseBeforeDeclarationRuntimeError(this, lhsLocation);
  4524. }
  4525. }
  4526. else if (sym == nullptr || sym->GetIsGlobal())
  4527. {
  4528. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4529. if (this->flags & fscrEval)
  4530. {
  4531. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4532. {
  4533. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->frameDisplayRegister, propertyId, false, false);
  4534. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4535. }
  4536. else
  4537. {
  4538. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, false);
  4539. // Load of a symbol with unknown scope from within eval
  4540. // Get it from the closure environment.
  4541. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4542. }
  4543. }
  4544. else if (this->flags & fscrImplicitThis)
  4545. {
  4546. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, false);
  4547. // Load of a symbol with unknown scope from within event handler.
  4548. // Get it from the closure environment.
  4549. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4550. }
  4551. else
  4552. {
  4553. // Special case non-writable built-ins
  4554. // TODO: support non-writable global property in general by detecting what attribute the property have current?
  4555. // But can't be done if we are byte code serialized, because the attribute might be different for use fields
  4556. // next time we run. May want to catch that in the JIT.
  4557. Js::OpCode opcode = Js::OpCode::LdRootFld;
  4558. // These properties are non-writable
  4559. switch (propertyId)
  4560. {
  4561. case Js::PropertyIds::NaN:
  4562. opcode = Js::OpCode::LdNaN;
  4563. break;
  4564. case Js::PropertyIds::Infinity:
  4565. opcode = Js::OpCode::LdInfinity;
  4566. break;
  4567. case Js::PropertyIds::undefined:
  4568. opcode = Js::OpCode::LdUndef;
  4569. break;
  4570. case Js::PropertyIds::__chakraLibrary:
  4571. if (CONFIG_FLAG(LdChakraLib) || CONFIG_FLAG(TestChakraLib))
  4572. {
  4573. opcode = Js::OpCode::LdChakraLib;
  4574. }
  4575. break;
  4576. }
  4577. if (opcode == Js::OpCode::LdRootFld)
  4578. {
  4579. this->EmitPatchableRootProperty(Js::OpCode::LdRootFld, lhsLocation, propertyId, false, false, funcInfo);
  4580. }
  4581. else
  4582. {
  4583. this->Writer()->Reg1(opcode, lhsLocation);
  4584. }
  4585. }
  4586. }
  4587. else if (sym->IsInSlot(this, funcInfo) || envIndex != -1)
  4588. {
  4589. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4590. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4591. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(scope, slot);
  4592. bool chkBlockVar = NeedCheckBlockVar(sym, scope, funcInfo);
  4593. Js::OpCode op;
  4594. // Now get the property from its slot.
  4595. op = this->GetLdSlotOp(scope, envIndex, scopeLocation, funcInfo);
  4596. slot = slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  4597. if (envIndex != -1)
  4598. {
  4599. this->m_writer.SlotI2(op, lhsLocation, envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var), slot, profileId);
  4600. }
  4601. else if (scopeLocation != Js::Constants::NoRegister &&
  4602. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4603. {
  4604. this->m_writer.SlotI1(op, lhsLocation, slot, profileId);
  4605. }
  4606. else if (scope->HasInnerScopeIndex())
  4607. {
  4608. this->m_writer.SlotI2(op, lhsLocation, scope->GetInnerScopeIndex(), slot, profileId);
  4609. }
  4610. else
  4611. {
  4612. AssertOrFailFast(scope->GetIsObject());
  4613. this->m_writer.Slot(op, lhsLocation, scopeLocation, slot, profileId);
  4614. }
  4615. if (chkBlockVar)
  4616. {
  4617. this->m_writer.Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4618. }
  4619. }
  4620. else
  4621. {
  4622. if (lhsLocation != sym->GetLocation())
  4623. {
  4624. this->m_writer.Reg2(Js::OpCode::Ld_A, lhsLocation, sym->GetLocation());
  4625. }
  4626. if (sym->GetIsBlockVar() && ((sym->GetDecl()->nop == knopLetDecl || sym->GetDecl()->nop == knopConstDecl) && sym->GetDecl()->AsParseNodeVar()->isSwitchStmtDecl))
  4627. {
  4628. this->m_writer.Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4629. }
  4630. }
  4631. if (!recList.Empty())
  4632. {
  4633. Js::ByteCodeLabel doneLabel = this->m_writer.DefineLabel();
  4634. this->m_writer.Br(doneLabel);
  4635. for (int i = 0;; i++)
  4636. {
  4637. uint cacheId;
  4638. Js::RegSlot instLocation;
  4639. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4640. this->m_writer.MarkLabel(recList.Item(i).label);
  4641. switch(recList.Item(i).kind)
  4642. {
  4643. case DynamicLoadKind::Local:
  4644. cacheId = funcInfo->FindOrAddInlineCacheId(recList.Item(i).instance, propertyId, false, false);
  4645. this->m_writer.ElementP(Js::OpCode::LdLocalFld_ReuseLoc, lhsLocation, cacheId);
  4646. break;
  4647. case DynamicLoadKind::Env:
  4648. instLocation = funcInfo->AcquireTmpRegister();
  4649. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation, recList.Item(i).index);
  4650. cacheId = funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, false);
  4651. this->m_writer.PatchableProperty(Js::OpCode::LdFld_ReuseLoc, lhsLocation, instLocation, cacheId);
  4652. funcInfo->ReleaseTmpRegister(instLocation);
  4653. break;
  4654. case DynamicLoadKind::LocalWith:
  4655. instLocation = funcInfo->AcquireTmpRegister();
  4656. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, recList.Item(i).instance);
  4657. cacheId = funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, false);
  4658. this->m_writer.PatchableProperty(Js::OpCode::LdFld_ReuseLoc, lhsLocation, instLocation, cacheId);
  4659. funcInfo->ReleaseTmpRegister(instLocation);
  4660. break;
  4661. case DynamicLoadKind::EnvWith:
  4662. instLocation = funcInfo->AcquireTmpRegister();
  4663. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation, recList.Item(i).index);
  4664. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4665. cacheId = funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, false);
  4666. this->m_writer.PatchableProperty(Js::OpCode::LdFld_ReuseLoc, lhsLocation, instLocation, cacheId);
  4667. funcInfo->ReleaseTmpRegister(instLocation);
  4668. break;
  4669. default:
  4670. AssertOrFailFast(UNREACHED);
  4671. }
  4672. if (i == recList.Count() - 1)
  4673. {
  4674. break;
  4675. }
  4676. this->m_writer.Br(doneLabel);
  4677. }
  4678. this->m_writer.MarkLabel(doneLabel);
  4679. }
  4680. }
  4681. bool ByteCodeGenerator::NeedCheckBlockVar(Symbol* sym, Scope* scope, FuncInfo* funcInfo) const
  4682. {
  4683. bool tdz = sym->GetIsBlockVar()
  4684. && (scope->GetFunc() != funcInfo || ((sym->GetDecl()->nop == knopLetDecl || sym->GetDecl()->nop == knopConstDecl) && sym->GetDecl()->AsParseNodeVar()->isSwitchStmtDecl));
  4685. return tdz || sym->GetIsNonSimpleParameter();
  4686. }
  4687. void ByteCodeGenerator::EmitPropDelete(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo)
  4688. {
  4689. // If sym belongs to a parent frame, delete it from the closure environment.
  4690. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4691. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4692. // Otherwise, just return false.
  4693. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4694. Js::PropertyId envIndex = -1;
  4695. Scope *scope = nullptr;
  4696. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4697. Assert(symScope);
  4698. JsUtil::List<DynamicLoadRecord, ArenaAllocator> recList(this->alloc);
  4699. for (;;)
  4700. {
  4701. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4702. if (scope == this->globalScope)
  4703. {
  4704. scopeLocation = ByteCodeGenerator::RootObjectRegister;
  4705. }
  4706. else if (envIndex == -1)
  4707. {
  4708. Assert(funcInfo == scope->GetFunc());
  4709. scopeLocation = scope->GetLocation();
  4710. }
  4711. if (scope == symScope)
  4712. {
  4713. break;
  4714. }
  4715. // Found a scope to which the property may have been added.
  4716. Assert(scope && scope->GetIsDynamic());
  4717. AssertOrFailFast(scope->GetIsObject());
  4718. DynamicLoadRecord rec;
  4719. rec.label = this->m_writer.DefineLabel();
  4720. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4721. Js::PropertyIdIndexType propertyIndex = funcInfo->FindOrAddReferencedPropertyId(propertyId);
  4722. if (scope->GetScopeType() != ScopeType_With)
  4723. {
  4724. if (envIndex == -1)
  4725. {
  4726. this->m_writer.BrLocalProperty(Js::OpCode::BrOnHasLocalProperty, rec.label, propertyIndex);
  4727. rec.kind = DynamicLoadKind::Local;
  4728. rec.instance = scopeLocation;
  4729. }
  4730. else
  4731. {
  4732. uint32 frameDisplayIndex = envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var);
  4733. this->m_writer.BrEnvProperty(Js::OpCode::BrOnHasLocalEnvProperty, rec.label, propertyIndex, frameDisplayIndex);
  4734. rec.kind = DynamicLoadKind::Env;
  4735. rec.index = frameDisplayIndex;
  4736. }
  4737. }
  4738. else
  4739. {
  4740. if (envIndex == -1)
  4741. {
  4742. this->m_writer.BrProperty(Js::OpCode::BrOnHasProperty, rec.label, scopeLocation, propertyIndex);
  4743. rec.kind = DynamicLoadKind::LocalWith;
  4744. rec.instance = scopeLocation;
  4745. }
  4746. else
  4747. {
  4748. uint32 frameDisplayIndex = envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var);
  4749. this->m_writer.BrEnvProperty(Js::OpCode::BrOnHasEnvProperty, rec.label, propertyIndex, frameDisplayIndex);
  4750. rec.kind = DynamicLoadKind::EnvWith;
  4751. rec.index = frameDisplayIndex;
  4752. }
  4753. }
  4754. recList.Add(rec);
  4755. }
  4756. // Arrived at the scope in which the property was defined.
  4757. if (sym == nullptr || sym->GetIsGlobal())
  4758. {
  4759. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4760. if (this->flags & (fscrEval | fscrImplicitThis))
  4761. {
  4762. this->m_writer.ScopedProperty(Js::OpCode::ScopedDeleteFld, lhsLocation,
  4763. funcInfo->FindOrAddReferencedPropertyId(propertyId), forceStrictModeForClassComputedPropertyName);
  4764. }
  4765. else
  4766. {
  4767. this->m_writer.Property(Js::OpCode::DeleteRootFld, lhsLocation, ByteCodeGenerator::RootObjectRegister,
  4768. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4769. }
  4770. }
  4771. else
  4772. {
  4773. // The delete will look like a non-local reference, so make sure a slot is reserved.
  4774. sym->EnsureScopeSlot(this, funcInfo);
  4775. this->m_writer.Reg1(Js::OpCode::LdFalse, lhsLocation);
  4776. }
  4777. if (!recList.Empty())
  4778. {
  4779. Js::ByteCodeLabel doneLabel = this->m_writer.DefineLabel();
  4780. this->m_writer.Br(doneLabel);
  4781. for (int i = 0;; i++)
  4782. {
  4783. Js::RegSlot instLocation;
  4784. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4785. Js::PropertyIdIndexType propertyIndex = funcInfo->FindOrAddReferencedPropertyId(propertyId);
  4786. this->m_writer.MarkLabel(recList.Item(i).label);
  4787. switch(recList.Item(i).kind)
  4788. {
  4789. case DynamicLoadKind::Local:
  4790. this->m_writer.ElementU(Js::OpCode::DeleteLocalFld_ReuseLoc, lhsLocation, propertyIndex);
  4791. break;
  4792. case DynamicLoadKind::Env:
  4793. instLocation = funcInfo->AcquireTmpRegister();
  4794. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation, recList.Item(i).index);
  4795. this->m_writer.Property(Js::OpCode::DeleteFld_ReuseLoc, lhsLocation, instLocation, propertyIndex);
  4796. funcInfo->ReleaseTmpRegister(instLocation);
  4797. break;
  4798. case DynamicLoadKind::LocalWith:
  4799. instLocation = funcInfo->AcquireTmpRegister();
  4800. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, recList.Item(i).instance);
  4801. this->m_writer.Property(Js::OpCode::DeleteFld_ReuseLoc, lhsLocation, instLocation, propertyIndex);
  4802. funcInfo->ReleaseTmpRegister(instLocation);
  4803. break;
  4804. case DynamicLoadKind::EnvWith:
  4805. instLocation = funcInfo->AcquireTmpRegister();
  4806. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation, recList.Item(i).index);
  4807. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4808. this->m_writer.Property(Js::OpCode::DeleteFld_ReuseLoc, lhsLocation, instLocation, propertyIndex);
  4809. funcInfo->ReleaseTmpRegister(instLocation);
  4810. break;
  4811. default:
  4812. AssertOrFailFast(UNREACHED);
  4813. }
  4814. if (i == recList.Count() - 1)
  4815. {
  4816. break;
  4817. }
  4818. this->m_writer.Br(doneLabel);
  4819. }
  4820. this->m_writer.MarkLabel(doneLabel);
  4821. }
  4822. }
  4823. void ByteCodeGenerator::EmitTypeOfFld(FuncInfo * funcInfo, Js::PropertyId propertyId, Js::RegSlot value, Js::RegSlot instance, Js::OpCode ldFldOp, bool reuseLoc)
  4824. {
  4825. uint cacheId;
  4826. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  4827. switch (ldFldOp)
  4828. {
  4829. case Js::OpCode::LdRootFldForTypeOf:
  4830. cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, false, false);
  4831. this->Writer()->PatchableRootProperty(ldFldOp, tmpReg, cacheId, false, false);
  4832. break;
  4833. case Js::OpCode::LdLocalFld:
  4834. case Js::OpCode::ScopedLdFldForTypeOf:
  4835. cacheId = funcInfo->FindOrAddInlineCacheId(instance, propertyId, false, false);
  4836. this->Writer()->ElementP(ldFldOp, tmpReg, cacheId);
  4837. break;
  4838. default:
  4839. cacheId = funcInfo->FindOrAddInlineCacheId(instance, propertyId, false, false);
  4840. this->Writer()->PatchableProperty(ldFldOp, tmpReg, instance, cacheId);
  4841. break;
  4842. }
  4843. this->Writer()->Reg2(reuseLoc ? Js::OpCode::Typeof_ReuseLoc : Js::OpCode::Typeof, value, tmpReg);
  4844. funcInfo->ReleaseTmpRegister(tmpReg);
  4845. }
  4846. void ByteCodeGenerator::EmitPropTypeof(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo)
  4847. {
  4848. // If sym belongs to a parent frame, delete it from the closure environment.
  4849. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4850. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4851. // Otherwise, just return false
  4852. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4853. Js::PropertyId envIndex = -1;
  4854. Scope *scope = nullptr;
  4855. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4856. Assert(symScope);
  4857. if (sym && sym->GetIsModuleExportStorage())
  4858. {
  4859. Js::RegSlot tmpLocation = funcInfo->AcquireTmpRegister();
  4860. EmitModuleExportAccess(sym, Js::OpCode::LdModuleSlot, tmpLocation, funcInfo);
  4861. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, tmpLocation);
  4862. funcInfo->ReleaseTmpRegister(tmpLocation);
  4863. return;
  4864. }
  4865. JsUtil::List<DynamicLoadRecord, ArenaAllocator> recList(this->alloc);
  4866. for (;;)
  4867. {
  4868. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4869. if (scope == this->globalScope)
  4870. {
  4871. scopeLocation = ByteCodeGenerator::RootObjectRegister;
  4872. }
  4873. else if (envIndex == -1)
  4874. {
  4875. Assert(funcInfo == scope->GetFunc());
  4876. scopeLocation = scope->GetLocation();
  4877. }
  4878. if (scope == symScope)
  4879. {
  4880. break;
  4881. }
  4882. // Found a scope to which the property may have been added.
  4883. Assert(scope && scope->GetIsDynamic());
  4884. AssertOrFailFast(scope->GetIsObject());
  4885. DynamicLoadRecord rec;
  4886. rec.label = this->m_writer.DefineLabel();
  4887. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4888. Js::PropertyIdIndexType propertyIndex = funcInfo->FindOrAddReferencedPropertyId(propertyId);
  4889. if (scope->GetScopeType() != ScopeType_With)
  4890. {
  4891. if (envIndex == -1)
  4892. {
  4893. this->m_writer.BrLocalProperty(Js::OpCode::BrOnHasLocalProperty, rec.label, propertyIndex);
  4894. rec.kind = DynamicLoadKind::Local;
  4895. rec.instance = scopeLocation;
  4896. }
  4897. else
  4898. {
  4899. uint32 frameDisplayIndex = envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var);
  4900. this->m_writer.BrEnvProperty(Js::OpCode::BrOnHasLocalEnvProperty, rec.label, propertyIndex, frameDisplayIndex);
  4901. rec.kind = DynamicLoadKind::Env;
  4902. rec.index = frameDisplayIndex;
  4903. }
  4904. }
  4905. else
  4906. {
  4907. if (envIndex == -1)
  4908. {
  4909. this->m_writer.BrProperty(Js::OpCode::BrOnHasProperty, rec.label, scopeLocation, propertyIndex);
  4910. rec.kind = DynamicLoadKind::LocalWith;
  4911. rec.instance = scopeLocation;
  4912. }
  4913. else
  4914. {
  4915. uint32 frameDisplayIndex = envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var);
  4916. this->m_writer.BrEnvProperty(Js::OpCode::BrOnHasEnvProperty, rec.label, propertyIndex, frameDisplayIndex);
  4917. rec.kind = DynamicLoadKind::EnvWith;
  4918. rec.index = frameDisplayIndex;
  4919. }
  4920. }
  4921. recList.Add(rec);
  4922. }
  4923. // Arrived at the scope in which the property was defined.
  4924. if (sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo)
  4925. {
  4926. // Ensure this symbol has a slot if it needs one.
  4927. if (sym->IsInSlot(this, funcInfo))
  4928. {
  4929. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4930. funcInfo->FindOrAddSlotProfileId(scope, slot);
  4931. }
  4932. EmitUseBeforeDeclarationRuntimeError(this, lhsLocation);
  4933. }
  4934. else if (sym == nullptr || sym->GetIsGlobal())
  4935. {
  4936. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4937. if (this->flags & fscrEval)
  4938. {
  4939. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4940. {
  4941. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->frameDisplayRegister, Js::OpCode::ScopedLdFldForTypeOf);
  4942. }
  4943. else
  4944. {
  4945. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->GetEnvRegister(), Js::OpCode::ScopedLdFldForTypeOf);
  4946. }
  4947. }
  4948. else if (this->flags & fscrImplicitThis)
  4949. {
  4950. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->GetEnvRegister(), Js::OpCode::ScopedLdFldForTypeOf);
  4951. }
  4952. else
  4953. {
  4954. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, ByteCodeGenerator::RootObjectRegister, Js::OpCode::LdRootFldForTypeOf);
  4955. }
  4956. }
  4957. else if (sym->IsInSlot(this, funcInfo) || envIndex != -1)
  4958. {
  4959. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4960. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4961. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(scope, slot);
  4962. Js::RegSlot tmpLocation = funcInfo->AcquireTmpRegister();
  4963. bool chkBlockVar = NeedCheckBlockVar(sym, scope, funcInfo);
  4964. Js::OpCode op;
  4965. op = this->GetLdSlotOp(scope, envIndex, scopeLocation, funcInfo);
  4966. slot = slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  4967. if (envIndex != -1)
  4968. {
  4969. this->m_writer.SlotI2(op, tmpLocation, envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var), slot, profileId);
  4970. }
  4971. else if (scopeLocation != Js::Constants::NoRegister &&
  4972. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4973. {
  4974. this->m_writer.SlotI1(op, tmpLocation, slot, profileId);
  4975. }
  4976. else if (scope->HasInnerScopeIndex())
  4977. {
  4978. this->m_writer.SlotI2(op, tmpLocation, scope->GetInnerScopeIndex(), slot, profileId);
  4979. }
  4980. else
  4981. {
  4982. AssertOrFailFast(scope->GetIsObject());
  4983. this->m_writer.Slot(op, tmpLocation, scopeLocation, slot, profileId);
  4984. }
  4985. if (chkBlockVar)
  4986. {
  4987. this->m_writer.Reg1(Js::OpCode::ChkUndecl, tmpLocation);
  4988. }
  4989. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, tmpLocation);
  4990. funcInfo->ReleaseTmpRegister(tmpLocation);
  4991. }
  4992. else
  4993. {
  4994. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, sym->GetLocation());
  4995. }
  4996. if (!recList.Empty())
  4997. {
  4998. Js::ByteCodeLabel doneLabel = this->m_writer.DefineLabel();
  4999. this->m_writer.Br(doneLabel);
  5000. for (int i = 0;; i++)
  5001. {
  5002. Js::RegSlot instLocation;
  5003. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  5004. this->m_writer.MarkLabel(recList.Item(i).label);
  5005. switch(recList.Item(i).kind)
  5006. {
  5007. case DynamicLoadKind::Local:
  5008. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, recList.Item(i).instance, Js::OpCode::LdLocalFld, true);
  5009. break;
  5010. case DynamicLoadKind::Env:
  5011. instLocation = funcInfo->AcquireTmpRegister();
  5012. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation, recList.Item(i).index);
  5013. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, instLocation, Js::OpCode::LdFldForTypeOf, true);
  5014. funcInfo->ReleaseTmpRegister(instLocation);
  5015. break;
  5016. case DynamicLoadKind::LocalWith:
  5017. instLocation = funcInfo->AcquireTmpRegister();
  5018. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, recList.Item(i).instance);
  5019. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, instLocation, Js::OpCode::LdFldForTypeOf, true);
  5020. funcInfo->ReleaseTmpRegister(instLocation);
  5021. break;
  5022. case DynamicLoadKind::EnvWith:
  5023. instLocation = funcInfo->AcquireTmpRegister();
  5024. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation, recList.Item(i).index);
  5025. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  5026. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, instLocation, Js::OpCode::LdFldForTypeOf, true);
  5027. funcInfo->ReleaseTmpRegister(instLocation);
  5028. break;
  5029. default:
  5030. AssertOrFailFast(UNREACHED);
  5031. }
  5032. if (i == recList.Count() - 1)
  5033. {
  5034. break;
  5035. }
  5036. this->m_writer.Br(doneLabel);
  5037. }
  5038. this->m_writer.MarkLabel(doneLabel);
  5039. }
  5040. }
  5041. void ByteCodeGenerator::EnsureNoRedeclarations(ParseNodeBlock *pnodeBlock, FuncInfo *funcInfo)
  5042. {
  5043. // Emit dynamic runtime checks for variable re-declarations. Only necessary for global functions (script or eval).
  5044. // In eval only var declarations can cause redeclaration, and only in non-strict mode, because let/const variables
  5045. // remain local to the eval code.
  5046. Assert(pnodeBlock->nop == knopBlock);
  5047. Assert(pnodeBlock->blockType == PnodeBlockType::Global || pnodeBlock->scope->GetScopeType() == ScopeType_GlobalEvalBlock);
  5048. if (!(this->flags & fscrEvalCode))
  5049. {
  5050. IterateBlockScopedVariables(pnodeBlock, [this](ParseNode *pnode)
  5051. {
  5052. FuncInfo *funcInfo = this->TopFuncInfo();
  5053. Symbol *sym = pnode->AsParseNodeVar()->sym;
  5054. Assert(sym->GetIsGlobal());
  5055. Js::PropertyId propertyId = sym->EnsurePosition(this);
  5056. this->m_writer.ElementRootU(Js::OpCode::EnsureNoRootFld, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  5057. });
  5058. }
  5059. auto emitRedeclCheck = [this](Symbol * sym, FuncInfo * funcInfo, bool isFncDecl = false)
  5060. {
  5061. Js::PropertyId propertyId = sym->EnsurePosition(this);
  5062. // Global function declarations must pass #sec-candeclareglobalfunction
  5063. // which is enforced by EnsureCanDeclGloFunc
  5064. if (isFncDecl)
  5065. {
  5066. this->m_writer.ElementRootU(Js::OpCode::EnsureCanDeclGloFunc, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  5067. }
  5068. if (this->flags & fscrEval)
  5069. {
  5070. if (!funcInfo->byteCodeFunction->GetIsStrictMode())
  5071. {
  5072. this->m_writer.ScopedProperty(Js::OpCode::ScopedEnsureNoRedeclFld, ByteCodeGenerator::RootObjectRegister,
  5073. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  5074. }
  5075. }
  5076. else
  5077. {
  5078. this->m_writer.ElementRootU(Js::OpCode::EnsureNoRootRedeclFld, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  5079. }
  5080. };
  5081. // scan for function declarations
  5082. // these behave like "var" declarations
  5083. for (ParseNodePtr pnode = pnodeBlock->pnodeScopes; pnode;)
  5084. {
  5085. switch (pnode->nop) {
  5086. case knopFncDecl:
  5087. if (pnode->AsParseNodeFnc()->IsDeclaration())
  5088. {
  5089. emitRedeclCheck(pnode->AsParseNodeFnc()->pnodeName->sym, funcInfo, true);
  5090. }
  5091. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  5092. break;
  5093. case knopBlock:
  5094. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  5095. break;
  5096. case knopCatch:
  5097. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  5098. break;
  5099. case knopWith:
  5100. pnode = pnode->AsParseNodeWith()->pnodeNext;
  5101. break;
  5102. default:
  5103. Assert(UNREACHED);
  5104. }
  5105. }
  5106. // scan for var declarations
  5107. for (ParseNode *pnode = funcInfo->root->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  5108. {
  5109. Symbol* sym = pnode->AsParseNodeVar()->sym;
  5110. if (sym == nullptr || pnode->AsParseNodeVar()->isBlockScopeFncDeclVar || sym->IsSpecialSymbol())
  5111. continue;
  5112. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  5113. {
  5114. // The init node was bound to the catch object, because it's inside a catch and has the
  5115. // same name as the catch object. But we want to define a user var at function scope,
  5116. // so find the right symbol. (We'll still assign the RHS value to the catch object symbol.)
  5117. // This also applies to a var declaration in the same scope as a let declaration.
  5118. // Assert that catch cannot be at function scope and let and var at function scope is redeclaration error.
  5119. Assert(sym->GetIsCatch() || funcInfo->bodyScope != sym->GetScope());
  5120. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  5121. Assert(sym && !sym->GetIsCatch() && !sym->GetIsBlockVar());
  5122. }
  5123. Assert(sym->GetIsGlobal());
  5124. if (sym->GetSymbolType() == STVariable)
  5125. {
  5126. emitRedeclCheck(sym, funcInfo);
  5127. }
  5128. }
  5129. }
  5130. void ByteCodeGenerator::RecordAllIntConstants(FuncInfo * funcInfo)
  5131. {
  5132. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5133. funcInfo->constantToRegister.Map([byteCodeFunction](unsigned int val, Js::RegSlot location)
  5134. {
  5135. byteCodeFunction->RecordIntConstant(byteCodeFunction->MapRegSlot(location), val);
  5136. });
  5137. }
  5138. void ByteCodeGenerator::RecordAllStrConstants(FuncInfo * funcInfo)
  5139. {
  5140. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5141. funcInfo->stringToRegister.Map([byteCodeFunction](IdentPtr pid, Js::RegSlot location)
  5142. {
  5143. byteCodeFunction->RecordStrConstant(byteCodeFunction->MapRegSlot(location), pid->Psz(), pid->Cch(), pid->IsUsedInLdElem());
  5144. });
  5145. }
  5146. void ByteCodeGenerator::RecordAllBigIntConstants(FuncInfo * funcInfo)
  5147. {
  5148. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5149. funcInfo->bigintToRegister.Map([byteCodeFunction](ParseNode* pnode, Js::RegSlot location)
  5150. {
  5151. IdentPtr pid = pnode->AsParseNodeBigInt()->pid;
  5152. byteCodeFunction->RecordBigIntConstant(byteCodeFunction->MapRegSlot(location), pid->Psz(), pid->Cch(), pnode->AsParseNodeBigInt()->isNegative);
  5153. });
  5154. }
  5155. void ByteCodeGenerator::RecordAllStringTemplateCallsiteConstants(FuncInfo* funcInfo)
  5156. {
  5157. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5158. funcInfo->stringTemplateCallsiteRegisterMap.Map([byteCodeFunction](ParseNodePtr pnode, Js::RegSlot location)
  5159. {
  5160. Js::ScriptContext* scriptContext = byteCodeFunction->GetScriptContext();
  5161. Js::RecyclableObject* rawArray = ByteCodeGenerator::BuildArrayFromStringList(pnode->AsParseNodeStrTemplate()->pnodeStringRawLiterals, pnode->AsParseNodeStrTemplate()->countStringLiterals, scriptContext);
  5162. rawArray->Freeze();
  5163. Js::RecyclableObject* callsiteObject = ByteCodeGenerator::BuildArrayFromStringList(pnode->AsParseNodeStrTemplate()->pnodeStringLiterals, pnode->AsParseNodeStrTemplate()->countStringLiterals, scriptContext);
  5164. callsiteObject->SetPropertyWithAttributes(Js::PropertyIds::raw, rawArray, PropertyNone, nullptr);
  5165. callsiteObject->Freeze();
  5166. byteCodeFunction->RecordConstant(byteCodeFunction->MapRegSlot(location), callsiteObject);
  5167. });
  5168. }
  5169. bool IsApplyArgs(ParseNodeCall* callNode)
  5170. {
  5171. ParseNode* target = callNode->pnodeTarget;
  5172. ParseNode* args = callNode->pnodeArgs;
  5173. if ((target != nullptr) && (target->nop == knopDot))
  5174. {
  5175. ParseNode* lhsNode = target->AsParseNodeBin()->pnode1;
  5176. if ((lhsNode != nullptr) && ((lhsNode->nop == knopDot) || (lhsNode->nop == knopName)) && !IsArguments(lhsNode))
  5177. {
  5178. ParseNode* nameNode = target->AsParseNodeBin()->pnode2;
  5179. if (nameNode != nullptr)
  5180. {
  5181. bool nameIsApply = nameNode->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::apply;
  5182. if (nameIsApply && args != nullptr && args->nop == knopList)
  5183. {
  5184. ParseNode* arg1 = args->AsParseNodeBin()->pnode1;
  5185. ParseNode* arg2 = args->AsParseNodeBin()->pnode2;
  5186. if ((arg1 != nullptr) && ByteCodeGenerator::IsThis(arg1) && (arg2 != nullptr) && (arg2->nop == knopName) && (arg2->AsParseNodeName()->sym != nullptr))
  5187. {
  5188. return arg2->AsParseNodeName()->sym->IsArguments();
  5189. }
  5190. }
  5191. }
  5192. }
  5193. }
  5194. return false;
  5195. }
  5196. void PostCheckApplyEnclosesArgs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, ApplyCheck* applyCheck)
  5197. {
  5198. if ((pnode == nullptr) || (!applyCheck->matches))
  5199. {
  5200. return;
  5201. }
  5202. if (pnode->nop == knopCall)
  5203. {
  5204. if ((!pnode->isUsed) && IsApplyArgs(pnode->AsParseNodeCall()))
  5205. {
  5206. if (!applyCheck->insideApplyCall)
  5207. {
  5208. applyCheck->matches = false;
  5209. }
  5210. applyCheck->insideApplyCall = false;
  5211. }
  5212. }
  5213. }
  5214. void CheckApplyEnclosesArgs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, ApplyCheck* applyCheck)
  5215. {
  5216. if ((pnode == nullptr) || (!applyCheck->matches))
  5217. {
  5218. return;
  5219. }
  5220. switch (pnode->nop)
  5221. {
  5222. case knopName:
  5223. {
  5224. Symbol* sym = pnode->AsParseNodeName()->sym;
  5225. if (sym != nullptr)
  5226. {
  5227. if (sym->IsArguments())
  5228. {
  5229. if (!applyCheck->insideApplyCall)
  5230. {
  5231. applyCheck->matches = false;
  5232. }
  5233. }
  5234. }
  5235. break;
  5236. }
  5237. case knopCall:
  5238. if ((!pnode->isUsed) && IsApplyArgs(pnode->AsParseNodeCall()))
  5239. {
  5240. // no nested apply calls
  5241. if (applyCheck->insideApplyCall)
  5242. {
  5243. applyCheck->matches = false;
  5244. }
  5245. else
  5246. {
  5247. applyCheck->insideApplyCall = true;
  5248. applyCheck->sawApply = true;
  5249. pnode->AsParseNodeCall()->isApplyCall = true;
  5250. }
  5251. }
  5252. break;
  5253. }
  5254. }
  5255. unsigned int CountArguments(ParseNode *pnode, BOOL *pSideEffect = nullptr)
  5256. {
  5257. // If the caller passed us a pSideEffect, it wants to know whether there are potential
  5258. // side-effects in the argument list. We need to know this so that the call target
  5259. // operands can be preserved if necessary.
  5260. // For now, treat any non-leaf op as a potential side-effect. This causes no detectable slowdowns,
  5261. // but we can be more precise if we need to be.
  5262. if (pSideEffect)
  5263. {
  5264. *pSideEffect = FALSE;
  5265. }
  5266. unsigned int argCount = 1;
  5267. if (pnode != nullptr)
  5268. {
  5269. while (pnode->nop == knopList)
  5270. {
  5271. argCount++;
  5272. if (pSideEffect && !(ParseNode::Grfnop(pnode->AsParseNodeBin()->pnode1->nop) & fnopLeaf))
  5273. {
  5274. *pSideEffect = TRUE;
  5275. }
  5276. pnode = pnode->AsParseNodeBin()->pnode2;
  5277. }
  5278. argCount++;
  5279. if (pSideEffect && !(ParseNode::Grfnop(pnode->nop) & fnopLeaf))
  5280. {
  5281. *pSideEffect = TRUE;
  5282. }
  5283. }
  5284. AssertOrFailFastMsg(argCount < Js::Constants::UShortMaxValue, "Number of allowed arguments are already capped at parser level");
  5285. return argCount;
  5286. }
  5287. void SaveOpndValue(ParseNode *pnode, FuncInfo *funcInfo)
  5288. {
  5289. // Save a local name to a register other than its home location.
  5290. // This guards against side-effects in cases like x.foo(x = bar()).
  5291. Symbol *sym = nullptr;
  5292. if (pnode->nop == knopName)
  5293. {
  5294. sym = pnode->AsParseNodeName()->sym;
  5295. }
  5296. else if (pnode->nop == knopComputedName)
  5297. {
  5298. ParseNode *pnode1 = pnode->AsParseNodeUni()->pnode1;
  5299. if (pnode1->nop == knopName)
  5300. {
  5301. sym = pnode1->AsParseNodeName()->sym;
  5302. }
  5303. }
  5304. if (sym == nullptr)
  5305. {
  5306. return;
  5307. }
  5308. // If the target is a local being kept in its home location,
  5309. // protect the target's value in the event the home location is overwritten.
  5310. if (pnode->location != Js::Constants::NoRegister &&
  5311. sym->GetScope()->GetFunc() == funcInfo &&
  5312. pnode->location == sym->GetLocation())
  5313. {
  5314. pnode->location = funcInfo->AcquireTmpRegister();
  5315. }
  5316. }
  5317. void ByteCodeGenerator::StartStatement(ParseNode* node)
  5318. {
  5319. Assert(TopFuncInfo() != nullptr);
  5320. m_writer.StartStatement(node, TopFuncInfo()->curTmpReg - TopFuncInfo()->firstTmpReg);
  5321. }
  5322. void ByteCodeGenerator::EndStatement(ParseNode* node)
  5323. {
  5324. m_writer.EndStatement(node);
  5325. }
  5326. void ByteCodeGenerator::StartSubexpression(ParseNode* node)
  5327. {
  5328. Assert(TopFuncInfo() != nullptr);
  5329. m_writer.StartSubexpression(node);
  5330. }
  5331. void ByteCodeGenerator::EndSubexpression(ParseNode* node)
  5332. {
  5333. m_writer.EndSubexpression(node);
  5334. }
  5335. void EmitReference(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  5336. {
  5337. // Generate code for the LHS of an assignment.
  5338. switch (pnode->nop)
  5339. {
  5340. case knopDot:
  5341. Emit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  5342. break;
  5343. case knopIndex:
  5344. Emit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  5345. Emit(pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo, false);
  5346. break;
  5347. case knopName:
  5348. break;
  5349. case knopArrayPattern:
  5350. case knopObjectPattern:
  5351. break;
  5352. case knopCall:
  5353. case knopNew:
  5354. // Emit the operands of a call that will be used as a LHS.
  5355. // These have to be emitted before the RHS, but they have to persist until
  5356. // the end of the expression.
  5357. // Emit the call target operands first.
  5358. // The call target does not need to be emitted for a super call - EmitSuperCall will do this.
  5359. if (!pnode->AsParseNodeCall()->isSuperCall)
  5360. {
  5361. switch (pnode->AsParseNodeCall()->pnodeTarget->nop)
  5362. {
  5363. case knopDot:
  5364. case knopIndex:
  5365. funcInfo->AcquireLoc(pnode->AsParseNodeCall()->pnodeTarget);
  5366. EmitReference(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5367. break;
  5368. case knopName:
  5369. {
  5370. Symbol* sym = pnode->AsParseNodeCall()->pnodeTarget->AsParseNodeName()->sym;
  5371. if (!sym || sym->GetLocation() == Js::Constants::NoRegister)
  5372. {
  5373. funcInfo->AcquireLoc(pnode->AsParseNodeCall()->pnodeTarget);
  5374. }
  5375. if (sym && (sym->IsInSlot(byteCodeGenerator, funcInfo) || sym->GetScope()->GetFunc() != funcInfo))
  5376. {
  5377. // Can't get the value from the assigned register, so load it here.
  5378. EmitLoad(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5379. }
  5380. else
  5381. {
  5382. // EmitLoad will check for needsDeclaration and emit the Use Before Declaration error
  5383. // bytecode op as necessary, but EmitReference does not check this (by design). So we
  5384. // must manually check here.
  5385. EmitUseBeforeDeclaration(pnode->AsParseNodeCall()->pnodeTarget->AsParseNodeName()->sym, byteCodeGenerator, funcInfo);
  5386. EmitReference(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5387. }
  5388. break;
  5389. }
  5390. default:
  5391. EmitLoad(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5392. break;
  5393. }
  5394. }
  5395. // Now the arg list. We evaluate everything now and emit the ArgOut's later.
  5396. if (pnode->AsParseNodeCall()->pnodeArgs)
  5397. {
  5398. ParseNode *pnodeArg = pnode->AsParseNodeCall()->pnodeArgs;
  5399. while (pnodeArg->nop == knopList)
  5400. {
  5401. Emit(pnodeArg->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  5402. pnodeArg = pnodeArg->AsParseNodeBin()->pnode2;
  5403. }
  5404. Emit(pnodeArg, byteCodeGenerator, funcInfo, false);
  5405. }
  5406. break;
  5407. default:
  5408. Emit(pnode, byteCodeGenerator, funcInfo, false);
  5409. break;
  5410. }
  5411. }
  5412. void EmitGetIterator(Js::RegSlot iteratorReg, Js::RegSlot iterableReg, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5413. void EmitIteratorClose(Js::RegSlot iteratorLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, bool isAsync = false);
  5414. void EmitFunctionCall(
  5415. Js::RegSlot resultReg,
  5416. Js::RegSlot funcReg,
  5417. Js::RegSlot thisReg,
  5418. Js::RegSlot argReg,
  5419. ByteCodeGenerator* byteCodeGenerator,
  5420. FuncInfo* funcInfo)
  5421. {
  5422. Js::ArgSlot argCount = argReg == Js::Constants::NoRegister ? 1 : 2;
  5423. funcInfo->StartRecordingOutArgs(argCount);
  5424. Js::ProfileId callSite = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  5425. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argCount);
  5426. byteCodeGenerator->Writer()->ArgOut<true>(0, thisReg, callSite, false);
  5427. if (argReg != Js::Constants::NoRegister)
  5428. byteCodeGenerator->Writer()->ArgOut<true>(1, argReg, callSite, false);
  5429. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallI, resultReg, funcReg, argCount, callSite);
  5430. }
  5431. void EmitFunctionCall(
  5432. Js::RegSlot resultReg,
  5433. Js::RegSlot funcReg,
  5434. Js::RegSlot thisReg,
  5435. ByteCodeGenerator* byteCodeGenerator,
  5436. FuncInfo* funcInfo)
  5437. {
  5438. Js::RegSlot argReg = Js::Constants::NoRegister;
  5439. EmitFunctionCall(resultReg, funcReg, thisReg, argReg, byteCodeGenerator, funcInfo);
  5440. }
  5441. void EmitThrowOnNotObject(Js::RegSlot varReg, ByteCodeGenerator* byteCodeGenerator)
  5442. {
  5443. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  5444. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, skipThrow, varReg);
  5445. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_NeedObject));
  5446. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  5447. }
  5448. void EmitGetOptionalObjectMethod(
  5449. Js::RegSlot methodReg,
  5450. Js::RegSlot objectReg,
  5451. Js::PropertyId propertyId,
  5452. Js::ByteCodeLabel noMethodLabel,
  5453. ByteCodeGenerator* byteCodeGenerator,
  5454. FuncInfo* funcInfo)
  5455. {
  5456. uint cacheId = funcInfo->FindOrAddInlineCacheId(
  5457. objectReg,
  5458. propertyId,
  5459. /* isLoadMethod */ true,
  5460. /* isStore */ false);
  5461. byteCodeGenerator->Writer()->PatchableProperty(
  5462. Js::OpCode::LdFld,
  5463. methodReg,
  5464. objectReg,
  5465. cacheId,
  5466. /* isCtor */ false,
  5467. /* registerCacheIdForCall */ true);
  5468. byteCodeGenerator->Writer()->BrReg2(
  5469. Js::OpCode::BrEq_A,
  5470. noMethodLabel,
  5471. methodReg,
  5472. funcInfo->undefinedConstantRegister);
  5473. }
  5474. void EmitGetObjectMethod(
  5475. Js::RegSlot methodReg,
  5476. Js::RegSlot objectReg,
  5477. Js::PropertyId propertyId,
  5478. ByteCodeGenerator* byteCodeGenerator,
  5479. FuncInfo* funcInfo)
  5480. {
  5481. uint cacheId = funcInfo->FindOrAddInlineCacheId(
  5482. objectReg,
  5483. propertyId,
  5484. /* isLoadMethod */ true,
  5485. /* isStore */ false);
  5486. byteCodeGenerator->Writer()->PatchableProperty(
  5487. Js::OpCode::LdMethodFld,
  5488. methodReg,
  5489. objectReg,
  5490. cacheId,
  5491. /* isCtor */ false,
  5492. /* registerCacheIdForCall */ true);
  5493. }
  5494. void EmitGetObjectProperty(
  5495. Js::RegSlot resultReg,
  5496. Js::RegSlot objectReg,
  5497. Js::PropertyId propertyId,
  5498. ByteCodeGenerator* byteCodeGenerator,
  5499. FuncInfo* funcInfo)
  5500. {
  5501. uint cacheId = funcInfo->FindOrAddInlineCacheId(
  5502. objectReg,
  5503. propertyId,
  5504. /* isLoadMethod */ false,
  5505. /* isStore */ false);
  5506. byteCodeGenerator->Writer()->PatchableProperty(
  5507. Js::OpCode::LdFld,
  5508. resultReg,
  5509. objectReg,
  5510. cacheId,
  5511. /* isCtor */ false,
  5512. /* registerCacheIdForCall */ false);
  5513. }
  5514. void EmitDestructuredElement(ParseNode *elem, Js::RegSlot sourceLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo *funcInfo)
  5515. {
  5516. switch (elem->nop)
  5517. {
  5518. case knopVarDecl:
  5519. case knopLetDecl:
  5520. case knopConstDecl:
  5521. // We manually need to set NeedDeclaration since the node won't be visited.
  5522. elem->AsParseNodeVar()->sym->SetNeedDeclaration(false);
  5523. break;
  5524. default:
  5525. EmitReference(elem, byteCodeGenerator, funcInfo);
  5526. }
  5527. EmitAssignment(nullptr, elem, sourceLocation, byteCodeGenerator, funcInfo);
  5528. funcInfo->ReleaseReference(elem);
  5529. }
  5530. void EmitDestructuredRestArray(
  5531. ParseNode* elem,
  5532. Js::RegSlot iteratorLocation,
  5533. Js::RegSlot nextMethodReg,
  5534. Js::RegSlot shouldCallReturnFunctionLocation,
  5535. Js::RegSlot shouldCallReturnFunctionLocationFinally,
  5536. ByteCodeGenerator* byteCodeGenerator,
  5537. FuncInfo* funcInfo)
  5538. {
  5539. Js::RegSlot restArrayLocation = funcInfo->AcquireTmpRegister();
  5540. bool isAssignmentTarget = !(elem->AsParseNodeUni()->pnode1->IsPattern() || elem->AsParseNodeUni()->pnode1->IsVarLetOrConst());
  5541. if (isAssignmentTarget)
  5542. {
  5543. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue_ReuseLoc, shouldCallReturnFunctionLocation);
  5544. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue_ReuseLoc, shouldCallReturnFunctionLocationFinally);
  5545. EmitReference(elem->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo);
  5546. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse_ReuseLoc, shouldCallReturnFunctionLocation);
  5547. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse_ReuseLoc, shouldCallReturnFunctionLocationFinally);
  5548. }
  5549. byteCodeGenerator->Writer()->Reg1Unsigned1(
  5550. Js::OpCode::NewScArray,
  5551. restArrayLocation,
  5552. ByteCodeGenerator::DefaultArraySize);
  5553. // BytecodeGen can't convey to IRBuilder that some of the temporaries used here are live. When we
  5554. // have a rest parameter, a counter is used in a loop for the array index, but there is no way to
  5555. // convey this is live on the back edge.
  5556. // As a workaround, we have a persistent var reg that is used for the loop counter
  5557. Js::RegSlot counterLocation = elem->location;
  5558. // TODO[ianhall]: Is calling EnregisterConstant() during Emit phase allowed?
  5559. Js::RegSlot zeroConstantReg = byteCodeGenerator->EnregisterConstant(0);
  5560. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, counterLocation, zeroConstantReg);
  5561. // loopTop:
  5562. Js::ByteCodeLabel loopTop = byteCodeGenerator->Writer()->DefineLabel();
  5563. byteCodeGenerator->Writer()->MarkLabel(loopTop);
  5564. Js::RegSlot itemLocation = funcInfo->AcquireTmpRegister();
  5565. EmitFunctionCall(
  5566. itemLocation,
  5567. nextMethodReg,
  5568. iteratorLocation,
  5569. byteCodeGenerator,
  5570. funcInfo);
  5571. EmitThrowOnNotObject(itemLocation, byteCodeGenerator);
  5572. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  5573. EmitGetObjectProperty(
  5574. doneLocation,
  5575. itemLocation,
  5576. Js::PropertyIds::done,
  5577. byteCodeGenerator,
  5578. funcInfo);
  5579. Js::ByteCodeLabel iteratorDone = byteCodeGenerator->Writer()->DefineLabel();
  5580. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, iteratorDone, doneLocation);
  5581. Js::RegSlot valueLocation = funcInfo->AcquireTmpRegister();
  5582. EmitGetObjectProperty(
  5583. valueLocation,
  5584. itemLocation,
  5585. Js::PropertyIds::value,
  5586. byteCodeGenerator,
  5587. funcInfo);
  5588. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue_ReuseLoc, shouldCallReturnFunctionLocation);
  5589. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue_ReuseLoc, shouldCallReturnFunctionLocationFinally);
  5590. byteCodeGenerator->Writer()->Element(
  5591. ByteCodeGenerator::GetStElemIOpCode(funcInfo),
  5592. valueLocation, restArrayLocation, counterLocation);
  5593. funcInfo->ReleaseTmpRegister(valueLocation);
  5594. funcInfo->ReleaseTmpRegister(doneLocation);
  5595. funcInfo->ReleaseTmpRegister(itemLocation);
  5596. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Incr_A, counterLocation, counterLocation);
  5597. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse_ReuseLoc, shouldCallReturnFunctionLocation);
  5598. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse_ReuseLoc, shouldCallReturnFunctionLocationFinally);
  5599. byteCodeGenerator->Writer()->Br(loopTop);
  5600. // iteratorDone:
  5601. byteCodeGenerator->Writer()->MarkLabel(iteratorDone);
  5602. ParseNode *restElem = elem->AsParseNodeUni()->pnode1;
  5603. if (isAssignmentTarget)
  5604. {
  5605. EmitAssignment(nullptr, restElem, restArrayLocation, byteCodeGenerator, funcInfo);
  5606. funcInfo->ReleaseReference(restElem);
  5607. }
  5608. else
  5609. {
  5610. EmitDestructuredElement(restElem, restArrayLocation, byteCodeGenerator, funcInfo);
  5611. }
  5612. funcInfo->ReleaseTmpRegister(restArrayLocation);
  5613. }
  5614. void EmitDestructuredArray(
  5615. ParseNode *lhs,
  5616. Js::RegSlot rhsLocation,
  5617. ByteCodeGenerator *byteCodeGenerator,
  5618. FuncInfo *funcInfo);
  5619. void EmitIteratorCloseIfNotDone(Js::RegSlot iteratorLocation, Js::RegSlot doneLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  5620. {
  5621. Js::ByteCodeLabel skipCloseLabel = byteCodeGenerator->Writer()->DefineLabel();
  5622. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, skipCloseLabel, doneLocation);
  5623. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5624. byteCodeGenerator->Writer()->MarkLabel(skipCloseLabel);
  5625. }
  5626. /*
  5627. EmitDestructuredArray(lhsArray, rhs):
  5628. iterator = rhs[@@iterator]
  5629. if lhsArray empty
  5630. return
  5631. for each element in lhsArray except rest
  5632. value = iterator.next()
  5633. if element is a nested destructured array
  5634. EmitDestructuredArray(element, value)
  5635. else
  5636. if value is undefined and there is an initializer
  5637. evaluate initializer
  5638. evaluate element reference
  5639. element = initializer
  5640. else
  5641. element = value
  5642. if lhsArray has a rest element
  5643. rest = []
  5644. while iterator is not done
  5645. value = iterator.next()
  5646. rest.append(value)
  5647. */
  5648. void EmitDestructuredArrayCore(
  5649. ParseNode* list,
  5650. Js::RegSlot iteratorLocation,
  5651. Js::RegSlot nextMethodReg,
  5652. Js::RegSlot shouldCallReturnFunctionLocation,
  5653. Js::RegSlot shouldCallReturnFunctionLocationFinally,
  5654. ByteCodeGenerator* byteCodeGenerator,
  5655. FuncInfo* funcInfo)
  5656. {
  5657. Assert(list != nullptr);
  5658. ParseNode *elem = nullptr;
  5659. while (list != nullptr)
  5660. {
  5661. ParseNode *init = nullptr;
  5662. if (list->nop == knopList)
  5663. {
  5664. elem = list->AsParseNodeBin()->pnode1;
  5665. }
  5666. else
  5667. {
  5668. elem = list;
  5669. }
  5670. if (elem->nop == knopEllipsis)
  5671. {
  5672. break;
  5673. }
  5674. switch (elem->nop)
  5675. {
  5676. case knopAsg:
  5677. // An assignment node will always have an initializer
  5678. init = elem->AsParseNodeBin()->pnode2;
  5679. elem = elem->AsParseNodeBin()->pnode1;
  5680. break;
  5681. case knopVarDecl:
  5682. case knopLetDecl:
  5683. case knopConstDecl:
  5684. init = elem->AsParseNodeVar()->pnodeInit;
  5685. break;
  5686. default:
  5687. break;
  5688. }
  5689. byteCodeGenerator->StartStatement(elem);
  5690. bool isAssignmentTarget = !(elem->IsPattern() || elem->IsVarLetOrConst());
  5691. if (isAssignmentTarget)
  5692. {
  5693. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue_ReuseLoc, shouldCallReturnFunctionLocation);
  5694. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue_ReuseLoc, shouldCallReturnFunctionLocationFinally);
  5695. EmitReference(elem, byteCodeGenerator, funcInfo);
  5696. }
  5697. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse_ReuseLoc, shouldCallReturnFunctionLocation);
  5698. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse_ReuseLoc, shouldCallReturnFunctionLocationFinally);
  5699. Js::RegSlot itemLocation = funcInfo->AcquireTmpRegister();
  5700. EmitFunctionCall(
  5701. itemLocation,
  5702. nextMethodReg,
  5703. iteratorLocation,
  5704. byteCodeGenerator,
  5705. funcInfo);
  5706. EmitThrowOnNotObject(itemLocation, byteCodeGenerator);
  5707. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  5708. EmitGetObjectProperty(
  5709. doneLocation,
  5710. itemLocation,
  5711. Js::PropertyIds::done,
  5712. byteCodeGenerator,
  5713. funcInfo);
  5714. if (elem->nop == knopEmpty)
  5715. {
  5716. if (list->nop == knopList)
  5717. {
  5718. list = list->AsParseNodeBin()->pnode2;
  5719. funcInfo->ReleaseTmpRegister(doneLocation);
  5720. funcInfo->ReleaseTmpRegister(itemLocation);
  5721. continue;
  5722. }
  5723. else
  5724. {
  5725. Assert(list->nop == knopEmpty);
  5726. EmitIteratorCloseIfNotDone(iteratorLocation, doneLocation, byteCodeGenerator, funcInfo);
  5727. funcInfo->ReleaseTmpRegister(doneLocation);
  5728. funcInfo->ReleaseTmpRegister(itemLocation);
  5729. break;
  5730. }
  5731. }
  5732. // If the iterator hasn't completed, skip assigning undefined.
  5733. Js::ByteCodeLabel iteratorAlreadyDone = byteCodeGenerator->Writer()->DefineLabel();
  5734. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, iteratorAlreadyDone, doneLocation);
  5735. // We're not done with the iterator, so assign the .next() value.
  5736. Js::RegSlot valueLocation = funcInfo->AcquireTmpRegister();
  5737. EmitGetObjectProperty(
  5738. valueLocation,
  5739. itemLocation,
  5740. Js::PropertyIds::value,
  5741. byteCodeGenerator,
  5742. funcInfo);
  5743. Js::ByteCodeLabel beforeDefaultAssign = byteCodeGenerator->Writer()->DefineLabel();
  5744. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue_ReuseLoc, shouldCallReturnFunctionLocation);
  5745. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue_ReuseLoc, shouldCallReturnFunctionLocationFinally);
  5746. byteCodeGenerator->Writer()->Br(beforeDefaultAssign);
  5747. // iteratorAlreadyDone:
  5748. byteCodeGenerator->Writer()->MarkLabel(iteratorAlreadyDone);
  5749. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A_ReuseLoc, valueLocation, funcInfo->undefinedConstantRegister);
  5750. // beforeDefaultAssign:
  5751. byteCodeGenerator->Writer()->MarkLabel(beforeDefaultAssign);
  5752. if (elem->IsPattern())
  5753. {
  5754. // If we get an undefined value and have an initializer, use it in place of undefined.
  5755. if (init != nullptr)
  5756. {
  5757. /*
  5758. the IR builder uses two symbols for a temp register in the if else path
  5759. R9 <- R3
  5760. if (...)
  5761. R9 <- R2
  5762. R10 = R9.<property> // error -> IR creates a new lifetime for the if path, and the direct path dest is not referenced
  5763. hence we have to create a new temp
  5764. TEMP REG USED TO FIX THIS PRODUCES THIS
  5765. R9 <- R3
  5766. if (BrEq_A R9, R3)
  5767. R10 <- R2 :
  5768. else
  5769. R10 <- R9 : skipdefault
  5770. ... = R10[@@iterator] : loadIter
  5771. */
  5772. // Temp Register
  5773. Js::RegSlot valueLocationTmp = funcInfo->AcquireTmpRegister();
  5774. byteCodeGenerator->StartStatement(init);
  5775. Js::ByteCodeLabel skipDefault = byteCodeGenerator->Writer()->DefineLabel();
  5776. Js::ByteCodeLabel loadIter = byteCodeGenerator->Writer()->DefineLabel();
  5777. // check value is undefined
  5778. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrNeq_A, skipDefault, valueLocation, funcInfo->undefinedConstantRegister);
  5779. // Evaluate the default expression and assign it.
  5780. Emit(init, byteCodeGenerator, funcInfo, false);
  5781. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocationTmp, init->location);
  5782. funcInfo->ReleaseLoc(init);
  5783. // jmp to loadIter
  5784. byteCodeGenerator->Writer()->Br(loadIter);
  5785. // skipDefault:
  5786. byteCodeGenerator->Writer()->MarkLabel(skipDefault);
  5787. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A_ReuseLoc, valueLocationTmp, valueLocation);
  5788. // loadIter:
  5789. // @@iterator
  5790. byteCodeGenerator->Writer()->MarkLabel(loadIter);
  5791. byteCodeGenerator->EndStatement(init);
  5792. if (elem->nop == knopObjectPattern)
  5793. {
  5794. EmitDestructuredObject(elem, valueLocationTmp, byteCodeGenerator, funcInfo);
  5795. }
  5796. else
  5797. {
  5798. // Recursively emit a destructured array using the current .next() as the RHS.
  5799. EmitDestructuredArray(elem, valueLocationTmp, byteCodeGenerator, funcInfo);
  5800. }
  5801. funcInfo->ReleaseTmpRegister(valueLocationTmp);
  5802. }
  5803. else
  5804. {
  5805. if (elem->nop == knopObjectPattern)
  5806. {
  5807. EmitDestructuredObject(elem, valueLocation, byteCodeGenerator, funcInfo);
  5808. }
  5809. else
  5810. {
  5811. // Recursively emit a destructured array using the current .next() as the RHS.
  5812. EmitDestructuredArray(elem, valueLocation, byteCodeGenerator, funcInfo);
  5813. }
  5814. }
  5815. }
  5816. else
  5817. {
  5818. EmitDestructuredValueOrInitializer(elem, valueLocation, init, isAssignmentTarget, byteCodeGenerator, funcInfo);
  5819. }
  5820. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse_ReuseLoc, shouldCallReturnFunctionLocation);
  5821. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse_ReuseLoc, shouldCallReturnFunctionLocationFinally);
  5822. if (list->nop != knopList)
  5823. {
  5824. EmitIteratorCloseIfNotDone(iteratorLocation, doneLocation, byteCodeGenerator, funcInfo);
  5825. }
  5826. funcInfo->ReleaseTmpRegister(valueLocation);
  5827. funcInfo->ReleaseTmpRegister(doneLocation);
  5828. funcInfo->ReleaseTmpRegister(itemLocation);
  5829. if (isAssignmentTarget)
  5830. {
  5831. funcInfo->ReleaseReference(elem);
  5832. }
  5833. byteCodeGenerator->EndStatement(elem);
  5834. if (list->nop == knopList)
  5835. {
  5836. list = list->AsParseNodeBin()->pnode2;
  5837. }
  5838. else
  5839. {
  5840. break;
  5841. }
  5842. }
  5843. // If we saw a rest element, emit the rest array.
  5844. if (elem != nullptr && elem->nop == knopEllipsis)
  5845. {
  5846. EmitDestructuredRestArray(
  5847. elem,
  5848. iteratorLocation,
  5849. nextMethodReg,
  5850. shouldCallReturnFunctionLocation,
  5851. shouldCallReturnFunctionLocationFinally,
  5852. byteCodeGenerator,
  5853. funcInfo);
  5854. }
  5855. }
  5856. struct ByteCodeGenerator::TryScopeRecord : public JsUtil::DoublyLinkedListElement<TryScopeRecord>
  5857. {
  5858. Js::OpCode op;
  5859. Js::ByteCodeLabel label;
  5860. Js::RegSlot reg1;
  5861. Js::RegSlot reg2;
  5862. TryScopeRecord(Js::OpCode op, Js::ByteCodeLabel label) : op(op), label(label), reg1(Js::Constants::NoRegister), reg2(Js::Constants::NoRegister) { }
  5863. TryScopeRecord(Js::OpCode op, Js::ByteCodeLabel label, Js::RegSlot r1, Js::RegSlot r2) : op(op), label(label), reg1(r1), reg2(r2) { }
  5864. };
  5865. // Generating
  5866. // try {
  5867. // CallIteratorClose
  5868. // } catch (e) {
  5869. // do nothing
  5870. // }
  5871. void EmitTryCatchAroundIteratorClose(
  5872. Js::RegSlot iteratorLocation,
  5873. Js::ByteCodeLabel endLabel,
  5874. ByteCodeGenerator *byteCodeGenerator,
  5875. FuncInfo *funcInfo,
  5876. bool isAsync)
  5877. {
  5878. Js::ByteCodeLabel catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  5879. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  5880. // Jump cleanup is only needed in a for-await loop since it will await the
  5881. // result of the call to the return method. Otherwise there can be no jump.
  5882. if (isAsync)
  5883. byteCodeGenerator->PushJumpCleanupForTry(Js::OpCode::TryCatch, catchLabel);
  5884. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo, isAsync);
  5885. if (isAsync)
  5886. byteCodeGenerator->PopJumpCleanup();
  5887. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5888. byteCodeGenerator->Writer()->Br(endLabel);
  5889. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  5890. Js::RegSlot catchParamLocation = funcInfo->AcquireTmpRegister();
  5891. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, catchParamLocation);
  5892. funcInfo->ReleaseTmpRegister(catchParamLocation);
  5893. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5894. }
  5895. // Generating
  5896. // catch(e) {
  5897. // if (shouldCallReturn)
  5898. // CallReturnWhichWrappedByTryCatch
  5899. // throw e;
  5900. // }
  5901. void EmitIteratorTopLevelCatch(
  5902. Js::ByteCodeLabel catchLabel,
  5903. Js::RegSlot iteratorLocation,
  5904. Js::RegSlot shouldCallReturnLocation,
  5905. Js::RegSlot shouldCallReturnLocationFinally,
  5906. ByteCodeGenerator* byteCodeGenerator,
  5907. FuncInfo* funcInfo,
  5908. bool isAsync)
  5909. {
  5910. Js::ByteCodeLabel afterCatchBlockLabel = byteCodeGenerator->Writer()->DefineLabel();
  5911. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5912. byteCodeGenerator->Writer()->Br(afterCatchBlockLabel);
  5913. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  5914. Js::RegSlot catchParamLocation = funcInfo->AcquireTmpRegister();
  5915. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, catchParamLocation);
  5916. byteCodeGenerator->PushJumpCleanupForTry(Js::OpCode::ResumeCatch);
  5917. Js::ByteCodeLabel skipCallCloseLabel = byteCodeGenerator->Writer()->DefineLabel();
  5918. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, skipCallCloseLabel, shouldCallReturnLocation);
  5919. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse_ReuseLoc, shouldCallReturnLocationFinally);
  5920. EmitTryCatchAroundIteratorClose(iteratorLocation, skipCallCloseLabel, byteCodeGenerator, funcInfo, isAsync);
  5921. byteCodeGenerator->Writer()->MarkLabel(skipCallCloseLabel);
  5922. // Rethrow the exception
  5923. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Throw, catchParamLocation);
  5924. funcInfo->ReleaseTmpRegister(catchParamLocation);
  5925. byteCodeGenerator->PopJumpCleanup();
  5926. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5927. byteCodeGenerator->Writer()->MarkLabel(afterCatchBlockLabel);
  5928. }
  5929. // Generating
  5930. // finally {
  5931. // if (shouldCallReturn)
  5932. // CallReturn
  5933. // }
  5934. void EmitIteratorTopLevelFinally(
  5935. Js::ByteCodeLabel finallyLabel,
  5936. Js::RegSlot iteratorLocation,
  5937. Js::RegSlot shouldCallReturnLocation,
  5938. Js::RegSlot yieldExceptionLocation,
  5939. Js::RegSlot yieldOffsetLocation,
  5940. ByteCodeGenerator* byteCodeGenerator,
  5941. FuncInfo* funcInfo,
  5942. bool isAsync)
  5943. {
  5944. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  5945. Js::ByteCodeLabel afterFinallyBlockLabel = byteCodeGenerator->Writer()->DefineLabel();
  5946. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5947. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  5948. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  5949. byteCodeGenerator->Writer()->Br(afterFinallyBlockLabel);
  5950. byteCodeGenerator->Writer()->MarkLabel(finallyLabel);
  5951. byteCodeGenerator->Writer()->Empty(Js::OpCode::Finally);
  5952. byteCodeGenerator->PushJumpCleanupForTry(
  5953. Js::OpCode::ResumeFinally,
  5954. finallyLabel,
  5955. yieldExceptionLocation,
  5956. yieldOffsetLocation);
  5957. Js::ByteCodeLabel skipCallCloseLabel = byteCodeGenerator->Writer()->DefineLabel();
  5958. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, skipCallCloseLabel, shouldCallReturnLocation);
  5959. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo, isAsync);
  5960. byteCodeGenerator->Writer()->MarkLabel(skipCallCloseLabel);
  5961. byteCodeGenerator->PopJumpCleanup();
  5962. if (isCoroutine)
  5963. {
  5964. funcInfo->ReleaseTmpRegister(yieldOffsetLocation);
  5965. funcInfo->ReleaseTmpRegister(yieldExceptionLocation);
  5966. }
  5967. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  5968. byteCodeGenerator->Writer()->Empty(Js::OpCode::LeaveNull);
  5969. byteCodeGenerator->Writer()->MarkLabel(afterFinallyBlockLabel);
  5970. }
  5971. void EmitIteratorCatchAndFinally(
  5972. Js::ByteCodeLabel catchLabel,
  5973. Js::ByteCodeLabel finallyLabel,
  5974. Js::RegSlot iteratorLocation,
  5975. Js::RegSlot shouldCallReturnFunctionLocation,
  5976. Js::RegSlot shouldCallReturnFunctionLocationFinally,
  5977. Js::RegSlot yieldExceptionLocation,
  5978. Js::RegSlot yieldOffsetLocation,
  5979. ByteCodeGenerator* byteCodeGenerator,
  5980. FuncInfo* funcInfo,
  5981. bool isAsync = false)
  5982. {
  5983. byteCodeGenerator->PopJumpCleanup();
  5984. EmitIteratorTopLevelCatch(
  5985. catchLabel,
  5986. iteratorLocation,
  5987. shouldCallReturnFunctionLocation,
  5988. shouldCallReturnFunctionLocationFinally,
  5989. byteCodeGenerator,
  5990. funcInfo,
  5991. isAsync);
  5992. byteCodeGenerator->PopJumpCleanup();
  5993. EmitIteratorTopLevelFinally(
  5994. finallyLabel,
  5995. iteratorLocation,
  5996. shouldCallReturnFunctionLocationFinally,
  5997. yieldExceptionLocation,
  5998. yieldOffsetLocation,
  5999. byteCodeGenerator,
  6000. funcInfo,
  6001. isAsync);
  6002. funcInfo->ReleaseTmpRegister(shouldCallReturnFunctionLocationFinally);
  6003. funcInfo->ReleaseTmpRegister(shouldCallReturnFunctionLocation);
  6004. }
  6005. // Emit a wrapper try..finaly block around the destructuring elements
  6006. void EmitDestructuredArray(
  6007. ParseNode *lhs,
  6008. Js::RegSlot rhsLocation,
  6009. ByteCodeGenerator *byteCodeGenerator,
  6010. FuncInfo *funcInfo)
  6011. {
  6012. byteCodeGenerator->StartStatement(lhs);
  6013. Js::RegSlot iteratorLocation = funcInfo->AcquireTmpRegister();
  6014. EmitGetIterator(iteratorLocation, rhsLocation, byteCodeGenerator, funcInfo);
  6015. Assert(lhs->nop == knopArrayPattern);
  6016. ParseNode *list = lhs->AsParseNodeArrLit()->pnode1;
  6017. if (list == nullptr)
  6018. { // Handline this case ([] = obj);
  6019. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  6020. // No elements to bind or assign.
  6021. funcInfo->ReleaseTmpRegister(iteratorLocation);
  6022. byteCodeGenerator->EndStatement(lhs);
  6023. return;
  6024. }
  6025. Js::RegSlot nextMethodReg = funcInfo->AcquireTmpRegister();
  6026. EmitGetObjectMethod(
  6027. nextMethodReg,
  6028. iteratorLocation,
  6029. Js::PropertyIds::next,
  6030. byteCodeGenerator,
  6031. funcInfo);
  6032. // This variable facilitates on when to call the return function (which is Iterator close). When we are emitting bytecode for destructuring element
  6033. // this variable will be set to true.
  6034. Js::RegSlot shouldCallReturnFunctionLocation = funcInfo->AcquireTmpRegister();
  6035. Js::RegSlot shouldCallReturnFunctionLocationFinally = funcInfo->AcquireTmpRegister();
  6036. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  6037. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  6038. byteCodeGenerator->SetHasFinally(true);
  6039. byteCodeGenerator->SetHasTry(true);
  6040. byteCodeGenerator->TopFuncInfo()->byteCodeFunction->SetDontInline(true);
  6041. Js::RegSlot regException = Js::Constants::NoRegister;
  6042. Js::RegSlot regOffset = Js::Constants::NoRegister;
  6043. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  6044. if (isCoroutine)
  6045. {
  6046. regException = funcInfo->AcquireTmpRegister();
  6047. regOffset = funcInfo->AcquireTmpRegister();
  6048. }
  6049. // Insert try node here
  6050. Js::ByteCodeLabel finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  6051. Js::ByteCodeLabel catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  6052. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  6053. if (isCoroutine)
  6054. {
  6055. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  6056. byteCodeGenerator->PushJumpCleanupForTry(
  6057. Js::OpCode::TryFinallyWithYield,
  6058. finallyLabel,
  6059. regException,
  6060. regOffset);
  6061. }
  6062. else
  6063. {
  6064. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  6065. byteCodeGenerator->PushJumpCleanupForTry(Js::OpCode::TryFinally, finallyLabel);
  6066. }
  6067. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  6068. byteCodeGenerator->PushJumpCleanupForTry(Js::OpCode::TryCatch, catchLabel);
  6069. EmitDestructuredArrayCore(
  6070. list,
  6071. iteratorLocation,
  6072. nextMethodReg,
  6073. shouldCallReturnFunctionLocation,
  6074. shouldCallReturnFunctionLocationFinally,
  6075. byteCodeGenerator,
  6076. funcInfo);
  6077. EmitIteratorCatchAndFinally(
  6078. catchLabel,
  6079. finallyLabel,
  6080. iteratorLocation,
  6081. shouldCallReturnFunctionLocation,
  6082. shouldCallReturnFunctionLocationFinally,
  6083. regException,
  6084. regOffset,
  6085. byteCodeGenerator,
  6086. funcInfo);
  6087. funcInfo->ReleaseTmpRegister(nextMethodReg);
  6088. funcInfo->ReleaseTmpRegister(iteratorLocation);
  6089. byteCodeGenerator->EndStatement(lhs);
  6090. }
  6091. void EmitNameInvoke(Js::RegSlot lhsLocation,
  6092. Js::RegSlot objectLocation,
  6093. Js::RegSlot computedPropIdArrLocation,
  6094. uint32 *computedIndex,
  6095. bool hasRest,
  6096. ParseNodePtr nameNode,
  6097. ByteCodeGenerator* byteCodeGenerator,
  6098. FuncInfo* funcInfo)
  6099. {
  6100. Assert(nameNode != nullptr);
  6101. if (nameNode->nop == knopComputedName)
  6102. {
  6103. ParseNodePtr pnode1 = nameNode->AsParseNodeUni()->pnode1;
  6104. Emit(pnode1, byteCodeGenerator, funcInfo, false/*isConstructorCall*/);
  6105. byteCodeGenerator->Writer()->Element(Js::OpCode::LdElemI_A, lhsLocation, objectLocation, pnode1->location);
  6106. if (hasRest)
  6107. {
  6108. byteCodeGenerator->Writer()->Slot(Js::OpCode::StPropIdArrFromVar, pnode1->location, computedPropIdArrLocation, *computedIndex);
  6109. (*computedIndex)++;
  6110. }
  6111. funcInfo->ReleaseLoc(pnode1);
  6112. }
  6113. else
  6114. {
  6115. Assert(nameNode->nop == knopStr);
  6116. Js::PropertyId propertyId = nameNode->AsParseNodeStr()->pid->GetPropertyId();
  6117. uint cacheId = funcInfo->FindOrAddInlineCacheId(objectLocation, propertyId, false/*isLoadMethod*/, false/*isStore*/);
  6118. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, lhsLocation, objectLocation, cacheId);
  6119. }
  6120. }
  6121. void EmitDestructuredValueOrInitializer(ParseNodePtr lhsElementNode,
  6122. Js::RegSlot rhsLocation,
  6123. ParseNodePtr initializer,
  6124. bool isNonPatternAssignmentTarget,
  6125. ByteCodeGenerator *byteCodeGenerator,
  6126. FuncInfo *funcInfo)
  6127. {
  6128. // If we have initializer we need to see if the destructured value is undefined or not - if it is undefined we need to assign initializer
  6129. Js::ByteCodeLabel useDefault = -1;
  6130. Js::ByteCodeLabel end = -1;
  6131. Js::RegSlot rhsLocationTmp = rhsLocation;
  6132. if (initializer != nullptr)
  6133. {
  6134. rhsLocationTmp = funcInfo->AcquireTmpRegister();
  6135. useDefault = byteCodeGenerator->Writer()->DefineLabel();
  6136. end = byteCodeGenerator->Writer()->DefineLabel();
  6137. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, useDefault, rhsLocation, funcInfo->undefinedConstantRegister);
  6138. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocationTmp, rhsLocation);
  6139. byteCodeGenerator->Writer()->Br(end);
  6140. byteCodeGenerator->Writer()->MarkLabel(useDefault);
  6141. Emit(initializer, byteCodeGenerator, funcInfo, false/*isConstructorCall*/);
  6142. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A_ReuseLoc, rhsLocationTmp, initializer->location);
  6143. funcInfo->ReleaseLoc(initializer);
  6144. byteCodeGenerator->Writer()->MarkLabel(end);
  6145. }
  6146. if (lhsElementNode->nop == knopArrayPattern)
  6147. {
  6148. EmitDestructuredArray(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  6149. }
  6150. else if (lhsElementNode->nop == knopObjectPattern)
  6151. {
  6152. EmitDestructuredObject(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  6153. }
  6154. else if (isNonPatternAssignmentTarget)
  6155. {
  6156. EmitAssignment(nullptr, lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  6157. }
  6158. else
  6159. {
  6160. EmitDestructuredElement(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  6161. }
  6162. if (initializer != nullptr)
  6163. {
  6164. funcInfo->ReleaseTmpRegister(rhsLocationTmp);
  6165. }
  6166. }
  6167. void EmitDestructuredObjectMember(ParseNodePtr memberNode,
  6168. Js::RegSlot rhsLocation,
  6169. Js::RegSlot propIdArrLocation,
  6170. Js::RegSlot computedPropIdArrLocation,
  6171. uint32 *computedIndex,
  6172. bool hasRest,
  6173. ByteCodeGenerator *byteCodeGenerator,
  6174. FuncInfo *funcInfo)
  6175. {
  6176. Assert(memberNode->nop == knopObjectPatternMember || memberNode->nop == knopEllipsis);
  6177. Js::RegSlot nameLocation = funcInfo->AcquireTmpRegister();
  6178. ParseNodePtr lhsElementNode = nullptr;
  6179. if (memberNode->nop == knopObjectPatternMember)
  6180. {
  6181. EmitNameInvoke(nameLocation, rhsLocation, computedPropIdArrLocation,
  6182. computedIndex, hasRest, memberNode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo);
  6183. // Imagine we are transforming
  6184. // {x:x1} = {} to x1 = {}.x (here x1 is the second node of the member but that is our lhsnode)
  6185. lhsElementNode = memberNode->AsParseNodeBin()->pnode2;
  6186. }
  6187. else
  6188. {
  6189. // memberNode->nop == knopEllipsis, aka we are performing Rest operation
  6190. byteCodeGenerator->Writer()->Reg1(Js::OpCode::NewScObjectSimple, nameLocation);
  6191. byteCodeGenerator->Writer()->Reg4(Js::OpCode::Restify, rhsLocation, nameLocation, propIdArrLocation, computedPropIdArrLocation);
  6192. lhsElementNode = memberNode->AsParseNodeUni()->pnode1;
  6193. }
  6194. ParseNodePtr init = nullptr;
  6195. if (lhsElementNode->IsVarLetOrConst())
  6196. {
  6197. init = lhsElementNode->AsParseNodeVar()->pnodeInit;
  6198. }
  6199. else if (lhsElementNode->nop == knopAsg)
  6200. {
  6201. init = lhsElementNode->AsParseNodeBin()->pnode2;
  6202. lhsElementNode = lhsElementNode->AsParseNodeBin()->pnode1;
  6203. }
  6204. EmitDestructuredValueOrInitializer(lhsElementNode, nameLocation, init, false /*isNonPatternAssignmentTarget*/, byteCodeGenerator, funcInfo);
  6205. funcInfo->ReleaseTmpRegister(nameLocation);
  6206. }
  6207. void EmitObjectPropertyIdsToArray(ByteCodeGenerator *byteCodeGenerator,
  6208. Js::PropertyId *ids,
  6209. ParseNodePtr memberNodes,
  6210. uint32 staticCount,
  6211. bool *hasComputedProps)
  6212. {
  6213. uint32 index = 0;
  6214. Parser::ForEachItemInList(memberNodes, [&](ParseNodePtr current) {
  6215. if (current->nop != knopEllipsis)
  6216. {
  6217. ParseNodePtr nameNode = current->AsParseNodeBin()->pnode1;
  6218. Assert(nameNode != nullptr);
  6219. Assert(nameNode->nop == knopComputedName || nameNode->nop == knopStr);
  6220. if (nameNode->nop == knopStr)
  6221. {
  6222. if (index >= staticCount)
  6223. {
  6224. Js::Throw::InternalError();
  6225. return;
  6226. }
  6227. ids[index] = nameNode->AsParseNodeStr()->pid->GetPropertyId();
  6228. index++;
  6229. }
  6230. else
  6231. {
  6232. *hasComputedProps = true;
  6233. }
  6234. }
  6235. });
  6236. }
  6237. void EmitDestructuredObject(ParseNode *lhs,
  6238. Js::RegSlot rhsLocationOrig,
  6239. ByteCodeGenerator *byteCodeGenerator,
  6240. FuncInfo *funcInfo)
  6241. {
  6242. Assert(lhs->nop == knopObjectPattern);
  6243. ParseNodeObjLit *pnodeObjLit = lhs->AsParseNodeObjLit();
  6244. ParseNodePtr pnode1 = pnodeObjLit->pnode1;
  6245. uint32 staticCount = pnodeObjLit->staticCount;
  6246. uint32 computedCount = pnodeObjLit->computedCount;
  6247. bool hasRest = pnodeObjLit->hasRest;
  6248. bool hasComputedProps = false;
  6249. byteCodeGenerator->StartStatement(lhs);
  6250. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  6251. Js::RegSlot rhsLocation = funcInfo->AcquireTmpRegister();
  6252. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocation, rhsLocationOrig);
  6253. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrNeq_A, skipThrow, rhsLocation, funcInfo->undefinedConstantRegister);
  6254. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ObjectCoercible));
  6255. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  6256. if (pnode1 != nullptr)
  6257. {
  6258. Js::RegSlot propIdArrLocation = Js::Constants::NoRegister;
  6259. Js::RegSlot computedPropIdArrLocation = Js::Constants::NoRegister;
  6260. if (hasRest)
  6261. {
  6262. uint extraAlloc = UInt32Math::Mul(staticCount, sizeof(Js::PropertyId));
  6263. uint auxSize = UInt32Math::Add(sizeof(Js::PropertyIdArray), extraAlloc);
  6264. Js::PropertyIdArray *propIds = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::PropertyIdArray, staticCount, 0);
  6265. Assert(pnode1->nop == knopList || pnode1->nop == knopObjectPatternMember || pnode1->nop == knopEllipsis);
  6266. EmitObjectPropertyIdsToArray(byteCodeGenerator, propIds->elements, pnode1, staticCount, &hasComputedProps);
  6267. // Load static PropertyIdArray here
  6268. propIdArrLocation = funcInfo->AcquireTmpRegister();
  6269. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::LdPropIds, propIdArrLocation, propIds, auxSize, staticCount);
  6270. if (hasComputedProps)
  6271. {
  6272. computedPropIdArrLocation = funcInfo->AcquireTmpRegister();
  6273. byteCodeGenerator->Writer()->Reg1Unsigned1(Js::OpCode::NewPropIdArrForCompProps, computedPropIdArrLocation, computedCount);
  6274. }
  6275. else
  6276. {
  6277. computedPropIdArrLocation = propIdArrLocation;
  6278. }
  6279. }
  6280. uint32 index = 0;
  6281. Parser::ForEachItemInList(pnode1, [&](ParseNodePtr memberNode) {
  6282. EmitDestructuredObjectMember(memberNode, rhsLocation, propIdArrLocation, computedPropIdArrLocation,
  6283. &index, hasRest, byteCodeGenerator, funcInfo);
  6284. });
  6285. if (hasRest)
  6286. {
  6287. if (hasComputedProps)
  6288. {
  6289. funcInfo->ReleaseTmpRegister(computedPropIdArrLocation);
  6290. }
  6291. funcInfo->ReleaseTmpRegister(propIdArrLocation);
  6292. }
  6293. }
  6294. funcInfo->ReleaseTmpRegister(rhsLocation);
  6295. byteCodeGenerator->EndStatement(lhs);
  6296. }
  6297. void EmitAssignment(
  6298. ParseNode *asgnNode,
  6299. ParseNode *lhs,
  6300. Js::RegSlot rhsLocation,
  6301. ByteCodeGenerator *byteCodeGenerator,
  6302. FuncInfo *funcInfo)
  6303. {
  6304. switch (lhs->nop)
  6305. {
  6306. // assignment to a local or global variable
  6307. case knopVarDecl:
  6308. case knopLetDecl:
  6309. case knopConstDecl:
  6310. {
  6311. Symbol *sym = lhs->AsParseNodeVar()->sym;
  6312. Assert(sym != nullptr);
  6313. byteCodeGenerator->EmitPropStore(rhsLocation, sym, nullptr, funcInfo, lhs->nop == knopLetDecl, lhs->nop == knopConstDecl);
  6314. break;
  6315. }
  6316. case knopName:
  6317. {
  6318. // Special names like 'this' or 'new.target' cannot be assigned to
  6319. ParseNodeName * pnodeNameLhs = lhs->AsParseNodeName();
  6320. if (pnodeNameLhs->IsSpecialName())
  6321. {
  6322. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  6323. }
  6324. else
  6325. {
  6326. byteCodeGenerator->EmitPropStore(rhsLocation, pnodeNameLhs->sym, pnodeNameLhs->pid, funcInfo);
  6327. }
  6328. break;
  6329. }
  6330. // x.y =
  6331. case knopDot:
  6332. {
  6333. // PutValue(x, "y", rhs)
  6334. Js::PropertyId propertyId = lhs->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6335. if (ByteCodeGenerator::IsSuper(lhs->AsParseNodeBin()->pnode1))
  6336. {
  6337. Emit(lhs->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  6338. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, lhs->AsParseNodeBin()->pnode1->location, funcInfo);
  6339. funcInfo->ReleaseLoc(lhs->AsParseNodeSuperReference()->pnodeThis);
  6340. uint cacheId = funcInfo->FindOrAddInlineCacheId(tmpReg, propertyId, false, true);
  6341. Js::OpCode stFldOpCode = funcInfo->GetIsStrictMode() ? Js::OpCode::StSuperFldStrict : Js::OpCode::StSuperFld;
  6342. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(stFldOpCode, rhsLocation, tmpReg, lhs->AsParseNodeSuperReference()->pnodeThis->location, cacheId);
  6343. }
  6344. else
  6345. {
  6346. uint cacheId = funcInfo->FindOrAddInlineCacheId(lhs->AsParseNodeBin()->pnode1->location, propertyId, false, true);
  6347. byteCodeGenerator->Writer()->PatchableProperty(
  6348. ByteCodeGenerator::GetStFldOpCode(funcInfo, false, false, false, false, byteCodeGenerator->forceStrictModeForClassComputedPropertyName), rhsLocation, lhs->AsParseNodeBin()->pnode1->location, cacheId);
  6349. }
  6350. break;
  6351. }
  6352. case knopIndex:
  6353. {
  6354. Js::RegSlot targetLocation = lhs->AsParseNodeBin()->pnode1->location;
  6355. if (ByteCodeGenerator::IsSuper(lhs->AsParseNodeBin()->pnode1))
  6356. {
  6357. // We need to emit the 'this' node for the super reference even if we aren't planning to use the 'this' value.
  6358. // This is because we might be in a derived class constructor where we haven't yet called super() to bind the 'this' value.
  6359. // See ecma262 abstract operation 'MakeSuperPropertyReference'
  6360. Emit(lhs->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  6361. funcInfo->ReleaseLoc(lhs->AsParseNodeSuperReference()->pnodeThis);
  6362. targetLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, targetLocation, funcInfo);
  6363. }
  6364. byteCodeGenerator->Writer()->Element(
  6365. ByteCodeGenerator::GetStElemIOpCode(funcInfo),
  6366. rhsLocation, targetLocation, lhs->AsParseNodeBin()->pnode2->location);
  6367. break;
  6368. }
  6369. case knopObjectPattern:
  6370. {
  6371. // Copy the rhs value to be the result of the assignment if needed.
  6372. if (asgnNode != nullptr)
  6373. {
  6374. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  6375. }
  6376. return EmitDestructuredObject(lhs, rhsLocation, byteCodeGenerator, funcInfo);
  6377. }
  6378. case knopArrayPattern:
  6379. {
  6380. // Copy the rhs value to be the result of the assignment if needed.
  6381. if (asgnNode != nullptr)
  6382. {
  6383. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  6384. }
  6385. return EmitDestructuredArray(lhs, rhsLocation, byteCodeGenerator, funcInfo);
  6386. }
  6387. case knopArray:
  6388. case knopObject:
  6389. // Assignment to array/object can get through to byte code gen when the parser fails to convert destructuring
  6390. // assignment to pattern (because of structural mismatch between LHS & RHS?). Revisit when we nail
  6391. // down early vs. runtime errors for destructuring.
  6392. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  6393. break;
  6394. default:
  6395. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  6396. break;
  6397. }
  6398. if (asgnNode != nullptr)
  6399. {
  6400. // We leave it up to the caller to pass this node only if the assignment expression is used.
  6401. if (asgnNode->location != rhsLocation)
  6402. {
  6403. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  6404. }
  6405. }
  6406. }
  6407. void EmitLoad(
  6408. ParseNode *lhs,
  6409. ByteCodeGenerator *byteCodeGenerator,
  6410. FuncInfo *funcInfo)
  6411. {
  6412. // Emit the instructions to load the value into the LHS location. Do not assign/free any temps
  6413. // in the process.
  6414. // We usually get here as part of an op-equiv expression: x.y += z;
  6415. // In such a case, x has to be emitted first, then the value of x.y loaded (by this function), then z emitted.
  6416. switch (lhs->nop)
  6417. {
  6418. // load of a local or global variable
  6419. case knopName:
  6420. {
  6421. funcInfo->AcquireLoc(lhs);
  6422. byteCodeGenerator->EmitPropLoad(lhs->location, lhs->AsParseNodeName()->sym, lhs->AsParseNodeName()->pid, funcInfo);
  6423. break;
  6424. }
  6425. // = x.y
  6426. case knopDot:
  6427. {
  6428. // get field id for "y"
  6429. Js::PropertyId propertyId = lhs->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6430. funcInfo->AcquireLoc(lhs);
  6431. EmitReference(lhs, byteCodeGenerator, funcInfo);
  6432. uint cacheId = funcInfo->FindOrAddInlineCacheId(lhs->AsParseNodeBin()->pnode1->location, propertyId, false, false);
  6433. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, lhs->location, lhs->AsParseNodeBin()->pnode1->location, cacheId);
  6434. break;
  6435. }
  6436. case knopIndex:
  6437. funcInfo->AcquireLoc(lhs);
  6438. EmitReference(lhs, byteCodeGenerator, funcInfo);
  6439. byteCodeGenerator->Writer()->Element(
  6440. Js::OpCode::LdElemI_A, lhs->location, lhs->AsParseNodeBin()->pnode1->location, lhs->AsParseNodeBin()->pnode2->location);
  6441. break;
  6442. // f(x) +=
  6443. case knopCall:
  6444. {
  6445. ParseNodeCall * pnodeCallLhs = lhs->AsParseNodeCall();
  6446. if (pnodeCallLhs->isSuperCall)
  6447. {
  6448. funcInfo->AcquireLoc(pnodeCallLhs);
  6449. EmitReference(pnodeCallLhs, byteCodeGenerator, funcInfo);
  6450. byteCodeGenerator->EmitSuperCall(funcInfo, pnodeCallLhs->AsParseNodeSuperCall(), /*fReturnValue=*/ false, /*fEvaluateComponents=*/ false);
  6451. }
  6452. else if (pnodeCallLhs->pnodeTarget->nop == knopImport)
  6453. {
  6454. ParseNodePtr args = pnodeCallLhs->pnodeArgs;
  6455. Assert(CountArguments(args) == 2); // import() takes one argument
  6456. Emit(args, byteCodeGenerator, funcInfo, false);
  6457. funcInfo->ReleaseLoc(args);
  6458. funcInfo->AcquireLoc(pnodeCallLhs);
  6459. byteCodeGenerator->Writer()->Reg2(Js::OpCode::ImportCall, pnodeCallLhs->location, args->location);
  6460. }
  6461. else
  6462. {
  6463. funcInfo->AcquireLoc(pnodeCallLhs);
  6464. EmitReference(pnodeCallLhs, byteCodeGenerator, funcInfo);
  6465. EmitCall(pnodeCallLhs, byteCodeGenerator, funcInfo, /*fReturnValue=*/ false, /*fEvaluateComponents=*/ false);
  6466. }
  6467. break;
  6468. }
  6469. default:
  6470. funcInfo->AcquireLoc(lhs);
  6471. Emit(lhs, byteCodeGenerator, funcInfo, false);
  6472. break;
  6473. }
  6474. }
  6475. void EmitList(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  6476. {
  6477. if (pnode != nullptr)
  6478. {
  6479. while (pnode->nop == knopList)
  6480. {
  6481. byteCodeGenerator->EmitTopLevelStatement(pnode->AsParseNodeBin()->pnode1, funcInfo, false);
  6482. pnode = pnode->AsParseNodeBin()->pnode2;
  6483. }
  6484. byteCodeGenerator->EmitTopLevelStatement(pnode, funcInfo, false);
  6485. }
  6486. }
  6487. void EmitOneArg(
  6488. ParseNode *pnode,
  6489. BOOL fAssignRegs,
  6490. ByteCodeGenerator *byteCodeGenerator,
  6491. FuncInfo *funcInfo,
  6492. Js::ProfileId callSiteId,
  6493. Js::ArgSlot &argIndex,
  6494. Js::ArgSlot &spreadIndex,
  6495. Js::RegSlot argTempLocation,
  6496. bool emitProfiledArgout,
  6497. Js::AuxArray<uint32> *spreadIndices = nullptr
  6498. )
  6499. {
  6500. bool noArgOuts = argTempLocation != Js::Constants::NoRegister;
  6501. // If this is a put, the arguments have already been evaluated (see EmitReference).
  6502. // We just need to emit the ArgOut instructions.
  6503. if (fAssignRegs)
  6504. {
  6505. Emit(pnode, byteCodeGenerator, funcInfo, false);
  6506. }
  6507. if (pnode->nop == knopEllipsis)
  6508. {
  6509. Assert(spreadIndices != nullptr);
  6510. spreadIndices->elements[spreadIndex++] = argIndex + 1; // account for 'this'
  6511. Js::RegSlot regVal = funcInfo->AcquireTmpRegister();
  6512. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, pnode->location);
  6513. if (noArgOuts)
  6514. {
  6515. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, argTempLocation, regVal);
  6516. }
  6517. else
  6518. {
  6519. byteCodeGenerator->Writer()->ArgOut<true>(argIndex + 1, regVal, callSiteId, emitProfiledArgout);
  6520. }
  6521. funcInfo->ReleaseTmpRegister(regVal);
  6522. }
  6523. else
  6524. {
  6525. if (noArgOuts)
  6526. {
  6527. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, argTempLocation, pnode->location);
  6528. }
  6529. else
  6530. {
  6531. byteCodeGenerator->Writer()->ArgOut<true>(argIndex + 1, pnode->location, callSiteId, emitProfiledArgout);
  6532. }
  6533. }
  6534. argIndex++;
  6535. if (fAssignRegs)
  6536. {
  6537. funcInfo->ReleaseLoc(pnode);
  6538. }
  6539. }
  6540. size_t EmitArgsWithArgOutsAtEnd(
  6541. ParseNode *pnode,
  6542. BOOL fAssignRegs,
  6543. ByteCodeGenerator *byteCodeGenerator,
  6544. FuncInfo *funcInfo,
  6545. Js::ProfileId callSiteId,
  6546. Js::RegSlot thisLocation,
  6547. Js::ArgSlot argsCountForStartCall,
  6548. bool emitProfiledArgouts,
  6549. Js::AuxArray<uint32> *spreadIndices = nullptr
  6550. )
  6551. {
  6552. AssertOrFailFast(pnode != nullptr);
  6553. Js::ArgSlot argIndex = 0;
  6554. Js::ArgSlot spreadIndex = 0;
  6555. Js::RegSlot argTempLocation = funcInfo->AcquireTmpRegister();
  6556. Js::RegSlot firstArgTempLocation = argTempLocation;
  6557. while (pnode->nop == knopList)
  6558. {
  6559. EmitOneArg(pnode->AsParseNodeBin()->pnode1, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, argTempLocation, false /*emitProfiledArgout*/, spreadIndices);
  6560. pnode = pnode->AsParseNodeBin()->pnode2;
  6561. argTempLocation = funcInfo->AcquireTmpRegister();
  6562. }
  6563. EmitOneArg(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, argTempLocation, false /*emitProfiledArgout*/, spreadIndices);
  6564. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argsCountForStartCall);
  6565. // Emit all argOuts now
  6566. if (thisLocation != Js::Constants::NoRegister)
  6567. {
  6568. // Emit the "this" object.
  6569. byteCodeGenerator->Writer()->ArgOut<true>(0, thisLocation, callSiteId, false /*emitProfiledArgouts*/);
  6570. }
  6571. for (Js::ArgSlot index = 0; index < argIndex; index++)
  6572. {
  6573. byteCodeGenerator->Writer()->ArgOut<true>(index + 1, firstArgTempLocation + index, callSiteId, emitProfiledArgouts);
  6574. }
  6575. // Now release all those temps register
  6576. for (Js::ArgSlot index = argIndex; index > 0; index--)
  6577. {
  6578. funcInfo->ReleaseTmpRegister(argTempLocation--);
  6579. }
  6580. return argIndex;
  6581. }
  6582. size_t EmitArgs(
  6583. ParseNode *pnode,
  6584. BOOL fAssignRegs,
  6585. ByteCodeGenerator *byteCodeGenerator,
  6586. FuncInfo *funcInfo,
  6587. Js::ProfileId callSiteId,
  6588. bool emitProfiledArgouts,
  6589. Js::AuxArray<uint32> *spreadIndices = nullptr
  6590. )
  6591. {
  6592. Js::ArgSlot argIndex = 0;
  6593. Js::ArgSlot spreadIndex = 0;
  6594. if (pnode != nullptr)
  6595. {
  6596. while (pnode->nop == knopList)
  6597. {
  6598. EmitOneArg(pnode->AsParseNodeBin()->pnode1, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, Js::Constants::NoRegister, emitProfiledArgouts, spreadIndices);
  6599. pnode = pnode->AsParseNodeBin()->pnode2;
  6600. }
  6601. EmitOneArg(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, Js::Constants::NoRegister, emitProfiledArgouts, spreadIndices);
  6602. }
  6603. return argIndex;
  6604. }
  6605. void EmitArgListStart(
  6606. Js::RegSlot thisLocation,
  6607. ByteCodeGenerator *byteCodeGenerator,
  6608. FuncInfo *funcInfo,
  6609. Js::ProfileId callSiteId)
  6610. {
  6611. if (thisLocation != Js::Constants::NoRegister)
  6612. {
  6613. // Emit the "this" object.
  6614. byteCodeGenerator->Writer()->ArgOut<true>(0, thisLocation, callSiteId, false /*emitProfiledArgout*/);
  6615. }
  6616. }
  6617. Js::ArgSlot EmitArgListEnd(
  6618. ParseNode *pnode,
  6619. Js::RegSlot thisLocation,
  6620. Js::RegSlot evalLocation,
  6621. Js::RegSlot newTargetLocation,
  6622. ByteCodeGenerator *byteCodeGenerator,
  6623. FuncInfo *funcInfo,
  6624. size_t argIndex,
  6625. Js::ProfileId callSiteId)
  6626. {
  6627. BOOL fEvalInModule = false;
  6628. BOOL fIsEval = (evalLocation != Js::Constants::NoRegister);
  6629. BOOL fHasNewTarget = (newTargetLocation != Js::Constants::NoRegister);
  6630. static const size_t maxExtraArgSlot = 4; // max(extraEvalArg, extraArg), where extraEvalArg==2 (moduleRoot,env), extraArg==4 (this, eval, evalInModule, newTarget)
  6631. AssertOrFailFastMsg(argIndex < Js::Constants::UShortMaxValue - maxExtraArgSlot, "Number of allowed arguments are already capped at parser level");
  6632. Js::ArgSlot argSlotIndex = (Js::ArgSlot) argIndex;
  6633. Js::ArgSlot evalIndex;
  6634. if (fIsEval && argSlotIndex > 0)
  6635. {
  6636. Assert(!fHasNewTarget);
  6637. // Pass the frame display as an extra argument to "eval".
  6638. // Do this only if eval is called with some args
  6639. Js::RegSlot evalEnv;
  6640. if (funcInfo->IsGlobalFunction() && !(funcInfo->GetIsStrictMode() && byteCodeGenerator->GetFlags() & fscrEval))
  6641. {
  6642. // Use current environment as the environment for the function being called when:
  6643. // - this is the root global function (not an eval's global function)
  6644. // - this is an eval's global function that is not in strict mode (see else block)
  6645. evalEnv = funcInfo->GetEnvRegister();
  6646. }
  6647. else
  6648. {
  6649. // Use the frame display as the environment for the function being called when:
  6650. // - this is not a global function and thus it will have its own scope
  6651. // - this is an eval's global function that is in strict mode, since in strict mode the eval's global function
  6652. // has its own scope
  6653. evalEnv = funcInfo->frameDisplayRegister;
  6654. }
  6655. evalEnv = byteCodeGenerator->PrependLocalScopes(evalEnv, evalLocation, funcInfo);
  6656. // Passing the FrameDisplay as an extra argument
  6657. evalIndex = argSlotIndex + 1;
  6658. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  6659. {
  6660. byteCodeGenerator->Writer()->ArgOutEnv(evalIndex);
  6661. }
  6662. else
  6663. {
  6664. byteCodeGenerator->Writer()->ArgOut<false>(evalIndex, evalEnv, callSiteId, false /*emitProfiledArgout*/);
  6665. }
  6666. }
  6667. if (fHasNewTarget)
  6668. {
  6669. Assert(!fIsEval);
  6670. byteCodeGenerator->Writer()->ArgOut<true>(argSlotIndex + 1, newTargetLocation, callSiteId, false /*emitProfiledArgout*/);
  6671. }
  6672. Js::ArgSlot argIntCount = argSlotIndex + 1 + (Js::ArgSlot)fIsEval + (Js::ArgSlot)fEvalInModule + (Js::ArgSlot)fHasNewTarget;
  6673. // eval and no args passed, return 1 as argument count
  6674. if (fIsEval && pnode == nullptr)
  6675. {
  6676. return 1;
  6677. }
  6678. return argIntCount;
  6679. }
  6680. Js::ArgSlot EmitArgList(
  6681. ParseNode *pnode,
  6682. Js::RegSlot thisLocation,
  6683. Js::RegSlot newTargetLocation,
  6684. BOOL fIsEval,
  6685. BOOL fAssignRegs,
  6686. ByteCodeGenerator *byteCodeGenerator,
  6687. FuncInfo *funcInfo,
  6688. Js::ProfileId callSiteId,
  6689. Js::ArgSlot argsCountForStartCall,
  6690. bool emitArgOutsAtEnd,
  6691. bool emitProfiledArgouts,
  6692. uint16 spreadArgCount = 0,
  6693. Js::AuxArray<uint32> **spreadIndices = nullptr)
  6694. {
  6695. // This function emits the arguments for a call.
  6696. // ArgOut's with uses immediately following defs.
  6697. if (!emitArgOutsAtEnd)
  6698. {
  6699. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argsCountForStartCall);
  6700. EmitArgListStart(thisLocation, byteCodeGenerator, funcInfo, callSiteId);
  6701. }
  6702. Js::RegSlot evalLocation = Js::Constants::NoRegister;
  6703. //
  6704. // If Emitting arguments for eval and assigning registers, get a tmpLocation for eval.
  6705. // This would be used while generating frameDisplay in EmitArgListEnd.
  6706. //
  6707. if (fIsEval)
  6708. {
  6709. evalLocation = funcInfo->AcquireTmpRegister();
  6710. }
  6711. if (spreadArgCount > 0)
  6712. {
  6713. const size_t extraAlloc = UInt32Math::Mul(spreadArgCount, sizeof(uint32));
  6714. Assert(spreadIndices != nullptr);
  6715. *spreadIndices = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<uint32>, spreadArgCount);
  6716. }
  6717. size_t argIndex = 0;
  6718. if (emitArgOutsAtEnd)
  6719. {
  6720. argIndex = EmitArgsWithArgOutsAtEnd(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, thisLocation, argsCountForStartCall, emitProfiledArgouts, spreadIndices == nullptr ? nullptr : *spreadIndices);
  6721. }
  6722. else
  6723. {
  6724. argIndex = EmitArgs(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, emitProfiledArgouts, spreadIndices == nullptr ? nullptr : *spreadIndices);
  6725. }
  6726. Js::ArgSlot argumentsCount = EmitArgListEnd(pnode, thisLocation, evalLocation, newTargetLocation, byteCodeGenerator, funcInfo, argIndex, callSiteId);
  6727. if (fIsEval)
  6728. {
  6729. funcInfo->ReleaseTmpRegister(evalLocation);
  6730. }
  6731. return argumentsCount;
  6732. }
  6733. void EmitConstantArgsToVarArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) Js::Var *vars, ParseNode *args, uint argCount)
  6734. {
  6735. uint index = 0;
  6736. while (args->nop == knopList && index < argCount)
  6737. {
  6738. if (args->AsParseNodeBin()->pnode1->nop == knopInt)
  6739. {
  6740. int value = args->AsParseNodeBin()->pnode1->AsParseNodeInt()->lw;
  6741. vars[index++] = Js::TaggedInt::ToVarUnchecked(value);
  6742. }
  6743. else if (args->AsParseNodeBin()->pnode1->nop == knopFlt)
  6744. {
  6745. Js::Var number = Js::JavascriptNumber::New(args->AsParseNodeBin()->pnode1->AsParseNodeFloat()->dbl, byteCodeGenerator->GetScriptContext());
  6746. #if ! FLOATVAR
  6747. byteCodeGenerator->GetScriptContext()->BindReference(number);
  6748. #endif
  6749. vars[index++] = number;
  6750. }
  6751. else
  6752. {
  6753. AnalysisAssert(false);
  6754. }
  6755. args = args->AsParseNodeBin()->pnode2;
  6756. }
  6757. if (index == argCount)
  6758. {
  6759. Assert(false);
  6760. Js::Throw::InternalError();
  6761. return;
  6762. }
  6763. if (args->nop == knopInt)
  6764. {
  6765. int value = args->AsParseNodeInt()->lw;
  6766. vars[index++] = Js::TaggedInt::ToVarUnchecked(value);
  6767. }
  6768. else if (args->nop == knopFlt)
  6769. {
  6770. Js::Var number = Js::JavascriptNumber::New(args->AsParseNodeFloat()->dbl, byteCodeGenerator->GetScriptContext());
  6771. #if ! FLOATVAR
  6772. byteCodeGenerator->GetScriptContext()->BindReference(number);
  6773. #endif
  6774. vars[index++] = number;
  6775. }
  6776. else
  6777. {
  6778. AnalysisAssert(false);
  6779. }
  6780. }
  6781. void EmitConstantArgsToIntArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) int32 *vars, ParseNode *args, uint argCount)
  6782. {
  6783. uint index = 0;
  6784. while (args->nop == knopList && index < argCount)
  6785. {
  6786. Assert(args->AsParseNodeBin()->pnode1->nop == knopInt);
  6787. vars[index++] = args->AsParseNodeBin()->pnode1->AsParseNodeInt()->lw;
  6788. args = args->AsParseNodeBin()->pnode2;
  6789. }
  6790. if (index >= argCount)
  6791. {
  6792. Js::Throw::InternalError();
  6793. return;
  6794. }
  6795. Assert(args->nop == knopInt);
  6796. vars[index++] = args->AsParseNodeInt()->lw;
  6797. Assert(index == argCount);
  6798. }
  6799. void EmitConstantArgsToFltArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) double *vars, ParseNode *args, uint argCount)
  6800. {
  6801. uint index = 0;
  6802. while (args->nop == knopList && index < argCount)
  6803. {
  6804. OpCode nop = args->AsParseNodeBin()->pnode1->nop;
  6805. if (nop == knopInt)
  6806. {
  6807. vars[index++] = (double)args->AsParseNodeBin()->pnode1->AsParseNodeInt()->lw;
  6808. }
  6809. else
  6810. {
  6811. Assert(nop == knopFlt);
  6812. vars[index++] = args->AsParseNodeBin()->pnode1->AsParseNodeFloat()->dbl;
  6813. }
  6814. args = args->AsParseNodeBin()->pnode2;
  6815. }
  6816. if (index >= argCount)
  6817. {
  6818. Js::Throw::InternalError();
  6819. return;
  6820. }
  6821. if (args->nop == knopInt)
  6822. {
  6823. vars[index++] = (double)args->AsParseNodeInt()->lw;
  6824. }
  6825. else
  6826. {
  6827. Assert(args->nop == knopFlt);
  6828. vars[index++] = args->AsParseNodeFloat()->dbl;
  6829. }
  6830. Assert(index == argCount);
  6831. }
  6832. //
  6833. // Called when we have new Ctr(constant, constant...)
  6834. //
  6835. Js::ArgSlot EmitNewObjectOfConstants(
  6836. ParseNode *pnode,
  6837. ByteCodeGenerator *byteCodeGenerator,
  6838. FuncInfo *funcInfo,
  6839. unsigned int argCount)
  6840. {
  6841. EmitArgListStart(Js::Constants::NoRegister, byteCodeGenerator, funcInfo, Js::Constants::NoProfileId);
  6842. // Create the vars array
  6843. Js::VarArrayVarCount *vars = AnewPlus(byteCodeGenerator->GetAllocator(), UInt32Math::Mul((argCount - 1), sizeof(Js::Var)), Js::VarArrayVarCount, Js::TaggedInt::ToVarUnchecked(argCount - 1));
  6844. // Emit all constants to the vars array
  6845. EmitConstantArgsToVarArray(byteCodeGenerator, vars->elements, pnode->AsParseNodeCall()->pnodeArgs, argCount - 1);
  6846. // Finish the arg list
  6847. Js::ArgSlot actualArgCount = EmitArgListEnd(
  6848. pnode->AsParseNodeCall()->pnodeArgs,
  6849. Js::Constants::NoRegister,
  6850. Js::Constants::NoRegister,
  6851. Js::Constants::NoRegister,
  6852. byteCodeGenerator,
  6853. funcInfo,
  6854. argCount - 1,
  6855. Js::Constants::NoProfileId);
  6856. // Make sure the cacheId to regSlot map in the ByteCodeWriter is left in a consistent state after writing NewScObject_A
  6857. byteCodeGenerator->Writer()->RemoveEntryForRegSlotFromCacheIdMap(pnode->AsParseNodeCall()->pnodeTarget->location);
  6858. // Generate the opcode with vars
  6859. byteCodeGenerator->Writer()->AuxiliaryContext(
  6860. Js::OpCode::NewScObject_A,
  6861. funcInfo->AcquireLoc(pnode),
  6862. vars,
  6863. UInt32Math::MulAdd<sizeof(Js::Var), sizeof(Js::VarArray)>((argCount-1)),
  6864. pnode->AsParseNodeCall()->pnodeTarget->location);
  6865. AdeletePlus(byteCodeGenerator->GetAllocator(), UInt32Math::Mul((argCount-1), sizeof(Js::VarArrayVarCount)), vars);
  6866. return actualArgCount;
  6867. }
  6868. void EmitMethodFld(bool isRoot, bool isScoped, Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, bool registerCacheIdForCall = true)
  6869. {
  6870. Js::OpCode opcode;
  6871. if (!isRoot)
  6872. {
  6873. if (callObjLocation == funcInfo->frameObjRegister)
  6874. {
  6875. opcode = Js::OpCode::LdLocalMethodFld;
  6876. }
  6877. else
  6878. {
  6879. opcode = Js::OpCode::LdMethodFld;
  6880. }
  6881. }
  6882. else if (isScoped)
  6883. {
  6884. opcode = Js::OpCode::ScopedLdMethodFld;
  6885. }
  6886. else
  6887. {
  6888. opcode = Js::OpCode::LdRootMethodFld;
  6889. }
  6890. if (isScoped || !isRoot)
  6891. {
  6892. Assert(isScoped || !isRoot || callObjLocation == ByteCodeGenerator::RootObjectRegister);
  6893. uint cacheId = funcInfo->FindOrAddInlineCacheId(callObjLocation, propertyId, true, false);
  6894. if (callObjLocation == funcInfo->frameObjRegister)
  6895. {
  6896. byteCodeGenerator->Writer()->ElementP(opcode, location, cacheId, false /*isCtor*/, registerCacheIdForCall);
  6897. }
  6898. else
  6899. {
  6900. byteCodeGenerator->Writer()->PatchableProperty(opcode, location, callObjLocation, cacheId, false /*isCtor*/, registerCacheIdForCall);
  6901. }
  6902. }
  6903. else
  6904. {
  6905. uint cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, true, false);
  6906. byteCodeGenerator->Writer()->PatchableRootProperty(opcode, location, cacheId, true, false, registerCacheIdForCall);
  6907. }
  6908. }
  6909. void EmitMethodFld(ParseNode *pnode, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, bool registerCacheIdForCall = true)
  6910. {
  6911. // Load a call target of the form x.y(). (Call target may be a plain knopName if we're getting it from
  6912. // the global object, etc.)
  6913. bool isRoot = pnode->nop == knopName && (pnode->AsParseNodeName()->sym == nullptr || pnode->AsParseNodeName()->sym->GetIsGlobal());
  6914. bool isScoped = (byteCodeGenerator->GetFlags() & fscrEval) != 0 ||
  6915. (isRoot && callObjLocation != ByteCodeGenerator::RootObjectRegister);
  6916. EmitMethodFld(isRoot, isScoped, pnode->location, callObjLocation, propertyId, byteCodeGenerator, funcInfo, registerCacheIdForCall);
  6917. }
  6918. // lhs.apply(this, arguments);
  6919. void EmitApplyCall(ParseNodeCall* pnodeCall, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue)
  6920. {
  6921. ParseNode* applyNode = pnodeCall->pnodeTarget;
  6922. ParseNode* thisNode = pnodeCall->pnodeArgs->AsParseNodeBin()->pnode1;
  6923. Assert(applyNode->nop == knopDot);
  6924. ParseNode* funcNode = applyNode->AsParseNodeBin()->pnode1;
  6925. Js::ByteCodeLabel slowPath = byteCodeGenerator->Writer()->DefineLabel();
  6926. Js::ByteCodeLabel afterSlowPath = byteCodeGenerator->Writer()->DefineLabel();
  6927. Js::ByteCodeLabel argsAlreadyCreated = byteCodeGenerator->Writer()->DefineLabel();
  6928. Assert(applyNode->nop == knopDot);
  6929. Emit(funcNode, byteCodeGenerator, funcInfo, false);
  6930. funcInfo->AcquireLoc(applyNode);
  6931. Js::PropertyId propertyId = applyNode->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6932. // As we won't be emitting a call instruction for apply, no need to register the cacheId for apply
  6933. // load to be associated with the call. This is also required, as in the absence of a corresponding
  6934. // call for apply, we won't remove the entry for "apply" cacheId from
  6935. // ByteCodeWriter::callRegToLdFldCacheIndexMap, which is contrary to our assumption that we would
  6936. // have removed an entry from a map upon seeing its corresponding call.
  6937. EmitMethodFld(applyNode, funcNode->location, propertyId, byteCodeGenerator, funcInfo, false /*registerCacheIdForCall*/);
  6938. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  6939. Assert(argSym && argSym->IsArguments());
  6940. Js::RegSlot argumentsLoc = argSym->GetLocation();
  6941. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdArgumentsFromFrame, argumentsLoc);
  6942. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrNotNull_A, argsAlreadyCreated, argumentsLoc);
  6943. // If apply is overridden, bail to slow path.
  6944. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFncNeqApply, slowPath, applyNode->location);
  6945. // Note: acquire and release a temp register for this stack arg pointer instead of trying to stash it
  6946. // in funcInfo->stackArgReg. Otherwise, we'll needlessly load and store it in jitted loop bodies and
  6947. // may crash if we try to unbox it on the store.
  6948. Js::RegSlot stackArgReg = funcInfo->AcquireTmpRegister();
  6949. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdStackArgPtr, stackArgReg);
  6950. Js::RegSlot argCountLocation = funcInfo->AcquireTmpRegister();
  6951. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdArgCnt, argCountLocation);
  6952. byteCodeGenerator->Writer()->Reg5(Js::OpCode::ApplyArgs, funcNode->location, funcNode->location, thisNode->location, stackArgReg, argCountLocation);
  6953. funcInfo->ReleaseTmpRegister(argCountLocation);
  6954. funcInfo->ReleaseTmpRegister(stackArgReg);
  6955. funcInfo->ReleaseLoc(applyNode);
  6956. funcInfo->ReleaseLoc(funcNode);
  6957. // Clear these nodes as they are going to be used to re-generate the slow path.
  6958. VisitClearTmpRegs(applyNode, byteCodeGenerator, funcInfo);
  6959. VisitClearTmpRegs(funcNode, byteCodeGenerator, funcInfo);
  6960. byteCodeGenerator->Writer()->Br(afterSlowPath);
  6961. // slow path
  6962. byteCodeGenerator->Writer()->MarkLabel(slowPath);
  6963. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  6964. {
  6965. byteCodeGenerator->EmitScopeObjectInit(funcInfo);
  6966. }
  6967. byteCodeGenerator->LoadHeapArguments(funcInfo);
  6968. byteCodeGenerator->Writer()->MarkLabel(argsAlreadyCreated);
  6969. EmitCall(pnodeCall, byteCodeGenerator, funcInfo, fReturnValue, /*fEvaluateComponents*/true);
  6970. byteCodeGenerator->Writer()->MarkLabel(afterSlowPath);
  6971. }
  6972. void EmitMethodElem(ParseNode *pnode, Js::RegSlot callObjLocation, Js::RegSlot indexLocation, ByteCodeGenerator *byteCodeGenerator)
  6973. {
  6974. // Load a call target of the form x[y]().
  6975. byteCodeGenerator->Writer()->Element(Js::OpCode::LdMethodElem, pnode->location, callObjLocation, indexLocation);
  6976. }
  6977. void EmitCallTargetNoEvalComponents(
  6978. ParseNode *pnodeTarget,
  6979. BOOL fSideEffectArgs,
  6980. Js::RegSlot *thisLocation,
  6981. bool *releaseThisLocation,
  6982. Js::RegSlot *callObjLocation,
  6983. ByteCodeGenerator *byteCodeGenerator,
  6984. FuncInfo *funcInfo)
  6985. {
  6986. // We first get a reference to the call target, then evaluate the arguments, then
  6987. // evaluate the call target.
  6988. // - emit reference to target
  6989. // - copy instance to scratch reg if necessary.
  6990. // - assign this
  6991. // - assign instance for dynamic/global name
  6992. // - emit args
  6993. // - do call (CallFld/Elem/I)
  6994. *releaseThisLocation = true;
  6995. switch (pnodeTarget->nop)
  6996. {
  6997. case knopDot:
  6998. *thisLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6999. *callObjLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  7000. break;
  7001. case knopIndex:
  7002. *thisLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  7003. *callObjLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  7004. break;
  7005. case knopName:
  7006. // If the call target is a name, do some extra work to get its instance and the "this" pointer.
  7007. byteCodeGenerator->EmitLoadInstance(pnodeTarget->AsParseNodeName()->sym, pnodeTarget->AsParseNodeName()->pid, thisLocation, callObjLocation, funcInfo);
  7008. if (*thisLocation == Js::Constants::NoRegister)
  7009. {
  7010. *thisLocation = funcInfo->undefinedConstantRegister;
  7011. }
  7012. break;
  7013. default:
  7014. *thisLocation = funcInfo->undefinedConstantRegister;
  7015. break;
  7016. }
  7017. }
  7018. void EmitCallTarget(
  7019. ParseNode *pnodeTarget,
  7020. BOOL fSideEffectArgs,
  7021. Js::RegSlot *thisLocation,
  7022. bool *releaseThisLocation,
  7023. Js::RegSlot *callObjLocation,
  7024. ByteCodeGenerator *byteCodeGenerator,
  7025. FuncInfo *funcInfo,
  7026. Js::ProfileId * callApplyCallSiteId)
  7027. {
  7028. // - emit target
  7029. // - assign this
  7030. // - emit args
  7031. // - do call
  7032. // The call target is fully evaluated before the argument list. Note that we're not handling
  7033. // put-call cases here currently, as such cases only apply to host objects
  7034. // and are very unlikely to behave differently depending on the order of evaluation.
  7035. *releaseThisLocation = true;
  7036. switch (pnodeTarget->nop)
  7037. {
  7038. case knopDot:
  7039. {
  7040. ParseNodeBin * pnodeBinTarget = pnodeTarget->AsParseNodeBin();
  7041. funcInfo->AcquireLoc(pnodeBinTarget);
  7042. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  7043. // them from side-effects.
  7044. if (fSideEffectArgs)
  7045. {
  7046. // Though we're done with target evaluation after this point, still protect opnd1 from
  7047. // arg side-effects as it's the "this" pointer.
  7048. SaveOpndValue(pnodeBinTarget->pnode1, funcInfo);
  7049. }
  7050. Assert(pnodeBinTarget->pnode2->nop == knopName);
  7051. if ((pnodeBinTarget->pnode2->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::apply) || (pnodeTarget->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::call))
  7052. {
  7053. funcInfo->EnsureCallSiteToCallApplyCallSiteMap();
  7054. *callApplyCallSiteId = byteCodeGenerator->GetNextCallApplyCallSiteId(Js::OpCode::CallI);
  7055. pnodeBinTarget->pnode1->SetIsCallApplyTargetLoad();
  7056. }
  7057. Emit(pnodeBinTarget->pnode1, byteCodeGenerator, funcInfo, false);
  7058. Js::PropertyId propertyId = pnodeBinTarget->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  7059. Js::RegSlot protoLocation = pnodeBinTarget->pnode1->location;
  7060. if (ByteCodeGenerator::IsSuper(pnodeBinTarget->pnode1))
  7061. {
  7062. Emit(pnodeBinTarget->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  7063. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, protoLocation, funcInfo);
  7064. funcInfo->ReleaseLoc(pnodeBinTarget->AsParseNodeSuperReference()->pnodeThis);
  7065. funcInfo->ReleaseLoc(pnodeBinTarget->pnode1);
  7066. // Function calls on the 'super' object should maintain current 'this' pointer.
  7067. *thisLocation = pnodeBinTarget->AsParseNodeSuperReference()->pnodeThis->location;
  7068. *releaseThisLocation = false;
  7069. uint cacheId = funcInfo->FindOrAddInlineCacheId(protoLocation, propertyId, false, false);
  7070. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(Js::OpCode::LdSuperFld,
  7071. pnodeTarget->location, protoLocation, *thisLocation, cacheId, false);
  7072. }
  7073. else
  7074. {
  7075. *thisLocation = pnodeBinTarget->pnode1->location;
  7076. EmitMethodFld(pnodeBinTarget, protoLocation, propertyId, byteCodeGenerator, funcInfo);
  7077. }
  7078. break;
  7079. }
  7080. case knopIndex:
  7081. {
  7082. funcInfo->AcquireLoc(pnodeTarget);
  7083. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  7084. // them from side-effects.
  7085. if (fSideEffectArgs || !(ParseNode::Grfnop(pnodeTarget->AsParseNodeBin()->pnode2->nop) & fnopLeaf))
  7086. {
  7087. // Though we're done with target evaluation after this point, still protect opnd1 from
  7088. // arg or opnd2 side-effects as it's the "this" pointer.
  7089. SaveOpndValue(pnodeTarget->AsParseNodeBin()->pnode1, funcInfo);
  7090. }
  7091. Emit(pnodeTarget->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  7092. Emit(pnodeTarget->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo, false);
  7093. Js::RegSlot indexLocation = pnodeTarget->AsParseNodeBin()->pnode2->location;
  7094. Js::RegSlot protoLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  7095. if (ByteCodeGenerator::IsSuper(pnodeTarget->AsParseNodeBin()->pnode1))
  7096. {
  7097. Emit(pnodeTarget->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  7098. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, protoLocation, funcInfo);
  7099. funcInfo->ReleaseLoc(pnodeTarget->AsParseNodeSuperReference()->pnodeThis);
  7100. // Function calls on the 'super' object should maintain current 'this' pointer
  7101. *thisLocation = pnodeTarget->AsParseNodeSuperReference()->pnodeThis->location;
  7102. *releaseThisLocation = false;
  7103. }
  7104. else
  7105. {
  7106. *thisLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  7107. }
  7108. EmitMethodElem(pnodeTarget, protoLocation, indexLocation, byteCodeGenerator);
  7109. funcInfo->ReleaseLoc(pnodeTarget->AsParseNodeBin()->pnode2); // don't release indexLocation until after we use it.
  7110. if (ByteCodeGenerator::IsSuper(pnodeTarget->AsParseNodeBin()->pnode1))
  7111. {
  7112. funcInfo->ReleaseLoc(pnodeTarget->AsParseNodeBin()->pnode1);
  7113. }
  7114. break;
  7115. }
  7116. case knopName:
  7117. {
  7118. ParseNodeName * pnodeNameTarget = pnodeTarget->AsParseNodeName();
  7119. if (!pnodeNameTarget->IsSpecialName())
  7120. {
  7121. funcInfo->AcquireLoc(pnodeNameTarget);
  7122. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  7123. // them from side-effects.
  7124. if (fSideEffectArgs)
  7125. {
  7126. SaveOpndValue(pnodeNameTarget, funcInfo);
  7127. }
  7128. byteCodeGenerator->EmitLoadInstance(pnodeNameTarget->sym, pnodeNameTarget->pid, thisLocation, callObjLocation, funcInfo);
  7129. if (*callObjLocation != Js::Constants::NoRegister)
  7130. {
  7131. // Load the call target as a property of the instance.
  7132. Js::PropertyId propertyId = pnodeNameTarget->PropertyIdFromNameNode();
  7133. EmitMethodFld(pnodeNameTarget, *callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7134. break;
  7135. }
  7136. }
  7137. // FALL THROUGH to evaluate call target.
  7138. }
  7139. default:
  7140. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  7141. // them from side-effects.
  7142. Emit(pnodeTarget, byteCodeGenerator, funcInfo, false);
  7143. *thisLocation = funcInfo->undefinedConstantRegister;
  7144. break;
  7145. }
  7146. // "This" pointer should have been assigned by the above.
  7147. Assert(*thisLocation != Js::Constants::NoRegister);
  7148. }
  7149. void EmitCallI(
  7150. ParseNodeCall *pnodeCall,
  7151. BOOL fEvaluateComponents,
  7152. BOOL fIsEval,
  7153. BOOL fHasNewTarget,
  7154. uint32 actualArgCount,
  7155. ByteCodeGenerator *byteCodeGenerator,
  7156. FuncInfo *funcInfo,
  7157. Js::ProfileId callSiteId,
  7158. Js::AuxArray<uint32> *spreadIndices = nullptr)
  7159. {
  7160. // Emit a call where the target is in a register, because it's either a local name or an expression we've
  7161. // already evaluated.
  7162. ParseNode *pnodeTarget = pnodeCall->pnodeTarget;
  7163. Js::OpCode op;
  7164. Js::CallFlags callFlags = Js::CallFlags::CallFlags_None;
  7165. uint spreadExtraAlloc = 0;
  7166. bool isSuperCall = pnodeCall->isSuperCall;
  7167. Js::ArgSlot actualArgSlotCount = (Js::ArgSlot) actualArgCount;
  7168. // check for integer overflow
  7169. if ((size_t)actualArgSlotCount != actualArgCount)
  7170. {
  7171. Js::Throw::OutOfMemory();
  7172. }
  7173. if (fEvaluateComponents && !isSuperCall)
  7174. {
  7175. // Release the call target operands we assigned above. If we didn't assign them here,
  7176. // we'll need them later, so we can't re-use them for the result of the call.
  7177. funcInfo->ReleaseLoc(pnodeTarget);
  7178. }
  7179. // Grab a register for the call result.
  7180. if (pnodeCall->isUsed)
  7181. {
  7182. funcInfo->AcquireLoc(pnodeCall);
  7183. }
  7184. if (fIsEval)
  7185. {
  7186. op = Js::OpCode::CallIExtendedFlags;
  7187. callFlags = Js::CallFlags::CallFlags_ExtraArg;
  7188. }
  7189. else
  7190. {
  7191. if (isSuperCall)
  7192. {
  7193. callFlags = Js::CallFlags_New;
  7194. }
  7195. if (fHasNewTarget)
  7196. {
  7197. callFlags = (Js::CallFlags) (callFlags | Js::CallFlags::CallFlags_ExtraArg | Js::CallFlags::CallFlags_NewTarget);
  7198. }
  7199. if (pnodeCall->spreadArgCount > 0)
  7200. {
  7201. op = (isSuperCall || fHasNewTarget) ? Js::OpCode::CallIExtendedFlags : Js::OpCode::CallIExtended;
  7202. }
  7203. else
  7204. {
  7205. op = (isSuperCall || fHasNewTarget) ? Js::OpCode::CallIFlags : Js::OpCode::CallI;
  7206. }
  7207. }
  7208. if (op == Js::OpCode::CallI || op == Js::OpCode::CallIFlags)
  7209. {
  7210. if (isSuperCall)
  7211. {
  7212. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdFuncObjProto, pnodeTarget->location, funcInfo);
  7213. byteCodeGenerator->Writer()->CallI(op, pnodeCall->location, tmpReg, actualArgSlotCount, callSiteId, callFlags);
  7214. }
  7215. else
  7216. {
  7217. byteCodeGenerator->Writer()->CallI(op, pnodeCall->location, pnodeTarget->location, actualArgSlotCount, callSiteId, callFlags);
  7218. }
  7219. }
  7220. else
  7221. {
  7222. uint spreadIndicesSize = 0;
  7223. Js::CallIExtendedOptions options = Js::CallIExtended_None;
  7224. if (pnodeCall->spreadArgCount > 0)
  7225. {
  7226. Assert(spreadIndices != nullptr);
  7227. spreadExtraAlloc = UInt32Math::Mul(spreadIndices->count, sizeof(uint32));
  7228. spreadIndicesSize = UInt32Math::Add(sizeof(*spreadIndices), spreadExtraAlloc);
  7229. options = Js::CallIExtended_SpreadArgs;
  7230. }
  7231. if (isSuperCall)
  7232. {
  7233. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdFuncObjProto, pnodeTarget->location, funcInfo);
  7234. byteCodeGenerator->Writer()->CallIExtended(op, pnodeCall->location, tmpReg, actualArgSlotCount, options, spreadIndices, spreadIndicesSize, callSiteId, callFlags);
  7235. }
  7236. else
  7237. {
  7238. byteCodeGenerator->Writer()->CallIExtended(op, pnodeCall->location, pnodeTarget->location, actualArgSlotCount, options, spreadIndices, spreadIndicesSize, callSiteId, callFlags);
  7239. }
  7240. }
  7241. if (pnodeCall->spreadArgCount > 0)
  7242. {
  7243. Assert(spreadExtraAlloc != 0);
  7244. AdeletePlus(byteCodeGenerator->GetAllocator(), spreadExtraAlloc, spreadIndices);
  7245. }
  7246. }
  7247. void EmitCallInstrNoEvalComponents(
  7248. ParseNodeCall *pnodeCall,
  7249. BOOL fIsEval,
  7250. BOOL fHasNewTarget,
  7251. Js::RegSlot thisLocation,
  7252. Js::RegSlot callObjLocation,
  7253. uint32 actualArgCount,
  7254. ByteCodeGenerator *byteCodeGenerator,
  7255. FuncInfo *funcInfo,
  7256. Js::ProfileId callSiteId,
  7257. Js::AuxArray<uint32> *spreadIndices = nullptr)
  7258. {
  7259. // Emit the call instruction. The call target is a reference at this point, and we evaluate
  7260. // it as part of doing the actual call.
  7261. // Note that we don't handle the (fEvaluateComponents == TRUE) case in this function.
  7262. // (This function is only called on the !fEvaluateComponents branch in EmitCall.)
  7263. ParseNode *pnodeTarget = pnodeCall->pnodeTarget;
  7264. switch (pnodeTarget->nop)
  7265. {
  7266. case knopDot:
  7267. {
  7268. Assert(pnodeTarget->AsParseNodeBin()->pnode2->nop == knopName);
  7269. Js::PropertyId propertyId = pnodeTarget->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  7270. EmitMethodFld(pnodeTarget, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7271. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, fHasNewTarget, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7272. }
  7273. break;
  7274. case knopIndex:
  7275. {
  7276. EmitMethodElem(pnodeTarget, pnodeTarget->AsParseNodeBin()->pnode1->location, pnodeTarget->AsParseNodeBin()->pnode2->location, byteCodeGenerator);
  7277. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, fHasNewTarget, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7278. }
  7279. break;
  7280. case knopName:
  7281. {
  7282. if (callObjLocation != Js::Constants::NoRegister)
  7283. {
  7284. // We still have to get the property from its instance, so emit CallFld.
  7285. if (thisLocation != callObjLocation)
  7286. {
  7287. funcInfo->ReleaseTmpRegister(thisLocation);
  7288. }
  7289. funcInfo->ReleaseTmpRegister(callObjLocation);
  7290. Js::PropertyId propertyId = pnodeTarget->AsParseNodeName()->PropertyIdFromNameNode();
  7291. EmitMethodFld(pnodeTarget, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7292. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, fHasNewTarget, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7293. break;
  7294. }
  7295. }
  7296. // FALL THROUGH
  7297. default:
  7298. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, fHasNewTarget, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7299. break;
  7300. }
  7301. }
  7302. void EmitCallInstr(
  7303. ParseNodeCall *pnodeCall,
  7304. BOOL fIsEval,
  7305. BOOL fHasNewTarget,
  7306. Js::RegSlot thisLocation,
  7307. Js::RegSlot callObjLocation,
  7308. uint32 actualArgCount,
  7309. ByteCodeGenerator *byteCodeGenerator,
  7310. FuncInfo *funcInfo,
  7311. Js::ProfileId callSiteId,
  7312. Js::AuxArray<uint32> *spreadIndices = nullptr)
  7313. {
  7314. // Emit a call instruction. The call target has been fully evaluated already, so we always
  7315. // emit a CallI through the register that holds the target value.
  7316. // Note that we don't handle !fEvaluateComponents cases at this point.
  7317. // (This function is only called on the fEvaluateComponents branch in EmitCall.)
  7318. if (thisLocation != Js::Constants::NoRegister)
  7319. {
  7320. funcInfo->ReleaseTmpRegister(thisLocation);
  7321. }
  7322. if (callObjLocation != Js::Constants::NoRegister &&
  7323. callObjLocation != thisLocation)
  7324. {
  7325. funcInfo->ReleaseTmpRegister(callObjLocation);
  7326. }
  7327. EmitCallI(pnodeCall, /*fEvaluateComponents*/ TRUE, fIsEval, fHasNewTarget, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7328. }
  7329. void EmitNew(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  7330. {
  7331. Js::ArgSlot argCount = pnode->AsParseNodeCall()->argCount;
  7332. argCount++; // include "this"
  7333. BOOL fSideEffectArgs = FALSE;
  7334. unsigned int tmpCount = CountArguments(pnode->AsParseNodeCall()->pnodeArgs, &fSideEffectArgs);
  7335. AssertOrFailFastMsg(argCount == tmpCount, "argCount cannot overflow as max args capped at parser level");
  7336. byteCodeGenerator->StartStatement(pnode);
  7337. // Start call, allocate out param space
  7338. funcInfo->StartRecordingOutArgs(argCount);
  7339. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  7340. // them from side-effects.
  7341. if (fSideEffectArgs)
  7342. {
  7343. SaveOpndValue(pnode->AsParseNodeCall()->pnodeTarget, funcInfo);
  7344. }
  7345. Emit(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo, false, true);
  7346. if (pnode->AsParseNodeCall()->pnodeArgs == nullptr)
  7347. {
  7348. funcInfo->ReleaseLoc(pnode->AsParseNodeCall()->pnodeTarget);
  7349. Js::OpCode op = (CreateNativeArrays(byteCodeGenerator, funcInfo)
  7350. && CallTargetIsArray(pnode->AsParseNodeCall()->pnodeTarget))
  7351. ? Js::OpCode::NewScObjArray : Js::OpCode::NewScObject;
  7352. Assert(argCount == 1);
  7353. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(op);
  7354. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argCount);
  7355. byteCodeGenerator->Writer()->CallI(op, funcInfo->AcquireLoc(pnode),
  7356. pnode->AsParseNodeCall()->pnodeTarget->location, argCount, callSiteId);
  7357. }
  7358. else
  7359. {
  7360. uint32 actualArgCount = 0;
  7361. if (IsCallOfConstants(pnode))
  7362. {
  7363. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argCount);
  7364. funcInfo->ReleaseLoc(pnode->AsParseNodeCall()->pnodeTarget);
  7365. actualArgCount = EmitNewObjectOfConstants(pnode, byteCodeGenerator, funcInfo, argCount);
  7366. }
  7367. else
  7368. {
  7369. Js::OpCode op;
  7370. if ((CreateNativeArrays(byteCodeGenerator, funcInfo) && CallTargetIsArray(pnode->AsParseNodeCall()->pnodeTarget)))
  7371. {
  7372. op = pnode->AsParseNodeCall()->spreadArgCount > 0 ? Js::OpCode::NewScObjArraySpread : Js::OpCode::NewScObjArray;
  7373. }
  7374. else
  7375. {
  7376. op = pnode->AsParseNodeCall()->spreadArgCount > 0 ? Js::OpCode::NewScObjectSpread : Js::OpCode::NewScObject;
  7377. }
  7378. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(op);
  7379. // Only emit profiled argouts if we're going to profile this call.
  7380. bool emitProfiledArgouts = callSiteId != byteCodeGenerator->GetCurrentCallSiteId();
  7381. Js::AuxArray<uint32> *spreadIndices = nullptr;
  7382. // Emit argouts at end for generators so that we don't need to restore them when bailing in
  7383. bool emitArgOutsAtEnd = pnode->AsParseNodeCall()->hasDestructuring || (funcInfo->byteCodeFunction->IsCoroutine() && pnode->AsParseNodeCall()->pnodeArgs != nullptr);
  7384. actualArgCount = EmitArgList(pnode->AsParseNodeCall()->pnodeArgs, Js::Constants::NoRegister, Js::Constants::NoRegister,
  7385. false, true, byteCodeGenerator, funcInfo, callSiteId, argCount, emitArgOutsAtEnd, emitProfiledArgouts, pnode->AsParseNodeCall()->spreadArgCount, &spreadIndices);
  7386. funcInfo->ReleaseLoc(pnode->AsParseNodeCall()->pnodeTarget);
  7387. if (pnode->AsParseNodeCall()->spreadArgCount > 0)
  7388. {
  7389. Assert(spreadIndices != nullptr);
  7390. uint spreadExtraAlloc = UInt32Math::Mul(spreadIndices->count, sizeof(uint32));
  7391. uint spreadIndicesSize = UInt32Math::Add(sizeof(*spreadIndices), spreadExtraAlloc);
  7392. byteCodeGenerator->Writer()->CallIExtended(op, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeCall()->pnodeTarget->location,
  7393. (uint16)actualArgCount, Js::CallIExtended_SpreadArgs,
  7394. spreadIndices, spreadIndicesSize, callSiteId);
  7395. }
  7396. else
  7397. {
  7398. byteCodeGenerator->Writer()->CallI(op, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeCall()->pnodeTarget->location,
  7399. (uint16)actualArgCount, callSiteId);
  7400. }
  7401. }
  7402. Assert(argCount == actualArgCount);
  7403. }
  7404. // End call, pop param space
  7405. funcInfo->EndRecordingOutArgs(argCount);
  7406. return;
  7407. }
  7408. void EmitCall(
  7409. ParseNodeCall * pnodeCall,
  7410. ByteCodeGenerator* byteCodeGenerator,
  7411. FuncInfo* funcInfo,
  7412. BOOL fReturnValue,
  7413. BOOL fEvaluateComponents,
  7414. Js::RegSlot overrideThisLocation,
  7415. Js::RegSlot newTargetLocation)
  7416. {
  7417. // If the call returns a float, we'll note this in the byte code.
  7418. Js::RegSlot thisLocation = Js::Constants::NoRegister;
  7419. Js::RegSlot callObjLocation = Js::Constants::NoRegister;
  7420. BOOL fHasNewTarget = newTargetLocation != Js::Constants::NoRegister;
  7421. BOOL fSideEffectArgs = FALSE;
  7422. BOOL fIsSuperCall = pnodeCall->isSuperCall;
  7423. ParseNode *pnodeTarget = pnodeCall->pnodeTarget;
  7424. ParseNode *pnodeArgs = pnodeCall->pnodeArgs;
  7425. uint16 spreadArgCount = pnodeCall->spreadArgCount;
  7426. if (CreateNativeArrays(byteCodeGenerator, funcInfo) && CallTargetIsArray(pnodeTarget)) {
  7427. // some minifiers (potentially incorrectly) assume that "v = new Array()" and "v = Array()" are equivalent,
  7428. // and replace the former with the latter to save 4 characters. What that means for us is that it, at least
  7429. // initially, uses the "Call" path. We want to guess that it _is_ just "new Array()" and change over to the
  7430. // "new" path, since then our native array handling can kick in.
  7431. /*EmitNew(pnode, byteCodeGenerator, funcInfo);
  7432. return;*/
  7433. }
  7434. unsigned int argCount = CountArguments(pnodeArgs, &fSideEffectArgs);
  7435. BOOL fIsEval = pnodeCall->isEvalCall;
  7436. Js::ArgSlot argSlotCount = (Js::ArgSlot)argCount;
  7437. if (fIsEval)
  7438. {
  7439. Assert(!fHasNewTarget);
  7440. //
  7441. // "eval" takes the closure environment as an extra argument
  7442. // Pass the closure env only if some argument is passed
  7443. // For just eval(), don't pass the closure environment
  7444. //
  7445. if (argCount > 1)
  7446. {
  7447. argCount++;
  7448. }
  7449. }
  7450. else if (fHasNewTarget)
  7451. {
  7452. // When we need to pass new.target explicitly, it is passed as an extra argument.
  7453. // This is similar to how eval passes an extra argument for the frame display and is
  7454. // used to support cases where we need to pass both 'this' and new.target as part of
  7455. // a function call.
  7456. // OpCode::LdNewTarget knows how to look at the call flags and fetch this argument.
  7457. argCount++;
  7458. }
  7459. // argCount indicates the total arguments count including the extra arguments.
  7460. // argSlotCount indicates the actual arguments count. So argCount should always never be les sthan argSlotCount.
  7461. if (argCount < (unsigned int)argSlotCount)
  7462. {
  7463. Js::Throw::OutOfMemory();
  7464. }
  7465. if (fReturnValue)
  7466. {
  7467. pnodeCall->isUsed = true;
  7468. }
  7469. //
  7470. // Set up the call.
  7471. //
  7472. bool releaseThisLocation = true;
  7473. // We already emit the call target for super calls in EmitSuperCall
  7474. Js::ProfileId callApplyCallSiteId = Js::Constants::NoProfileId;
  7475. if (!fIsSuperCall)
  7476. {
  7477. if (!fEvaluateComponents)
  7478. {
  7479. EmitCallTargetNoEvalComponents(pnodeTarget, fSideEffectArgs, &thisLocation, &releaseThisLocation, &callObjLocation, byteCodeGenerator, funcInfo);
  7480. }
  7481. else
  7482. {
  7483. EmitCallTarget(pnodeTarget, fSideEffectArgs, &thisLocation, &releaseThisLocation, &callObjLocation, byteCodeGenerator, funcInfo, &callApplyCallSiteId);
  7484. }
  7485. }
  7486. // If we are strictly overriding the this location, ignore what the call target set this location to.
  7487. if (overrideThisLocation != Js::Constants::NoRegister)
  7488. {
  7489. thisLocation = overrideThisLocation;
  7490. releaseThisLocation = false;
  7491. }
  7492. // Evaluate the arguments (nothing mode-specific here).
  7493. // Start call, allocate out param space
  7494. // We have to use the arguments count including the extra args to Start Call as we use it to allocated space for all the args
  7495. funcInfo->StartRecordingOutArgs(argCount);
  7496. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  7497. if (callApplyCallSiteId != Js::Constants::NoProfileId)
  7498. {
  7499. funcInfo->callSiteToCallApplyCallSiteMap->AddNew(callSiteId, callApplyCallSiteId);
  7500. }
  7501. // Only emit profiled argouts if we're going to allocate callSiteInfo (on the DynamicProfileInfo) for this call.
  7502. bool emitProfiledArgouts = callSiteId != byteCodeGenerator->GetCurrentCallSiteId();
  7503. // Emit argouts at end for generators so that we don't need to restore them when bailing in
  7504. bool emitArgOutsAtEnd = pnodeCall->hasDestructuring || (funcInfo->byteCodeFunction->IsCoroutine() && pnodeCall->pnodeArgs != nullptr);
  7505. Js::AuxArray<uint32> *spreadIndices;
  7506. EmitArgList(pnodeArgs, thisLocation, newTargetLocation, fIsEval, fEvaluateComponents, byteCodeGenerator, funcInfo, callSiteId, (Js::ArgSlot)argCount, emitArgOutsAtEnd, emitProfiledArgouts, spreadArgCount, &spreadIndices);
  7507. if (!fEvaluateComponents)
  7508. {
  7509. EmitCallInstrNoEvalComponents(pnodeCall, fIsEval, fHasNewTarget, thisLocation, callObjLocation, argSlotCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7510. }
  7511. else
  7512. {
  7513. EmitCallInstr(pnodeCall, fIsEval, fHasNewTarget, releaseThisLocation ? thisLocation : Js::Constants::NoRegister, callObjLocation, argSlotCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7514. }
  7515. // End call, pop param space
  7516. funcInfo->EndRecordingOutArgs((Js::ArgSlot)argCount);
  7517. }
  7518. void EmitInvoke(
  7519. Js::RegSlot location,
  7520. Js::RegSlot callObjLocation,
  7521. Js::PropertyId propertyId,
  7522. ByteCodeGenerator* byteCodeGenerator,
  7523. FuncInfo* funcInfo)
  7524. {
  7525. EmitMethodFld(false, false, location, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7526. funcInfo->StartRecordingOutArgs(1);
  7527. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  7528. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, 1);
  7529. EmitArgListStart(callObjLocation, byteCodeGenerator, funcInfo, callSiteId);
  7530. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallI, location, location, 1, callSiteId);
  7531. }
  7532. void EmitInvoke(
  7533. Js::RegSlot location,
  7534. Js::RegSlot callObjLocation,
  7535. Js::PropertyId propertyId,
  7536. ByteCodeGenerator* byteCodeGenerator,
  7537. FuncInfo* funcInfo,
  7538. Js::RegSlot arg1Location)
  7539. {
  7540. EmitMethodFld(false, false, location, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7541. funcInfo->StartRecordingOutArgs(2);
  7542. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  7543. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, 2);
  7544. EmitArgListStart(callObjLocation, byteCodeGenerator, funcInfo, callSiteId);
  7545. byteCodeGenerator->Writer()->ArgOut<true>(1, arg1Location, callSiteId, false /*emitProfiledArgout*/);
  7546. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallI, location, location, 2, callSiteId);
  7547. }
  7548. void EmitMemberNode(ParseNode *memberNode, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, ParseNode* parentNode, bool useStore, bool* isObjectEmpty = nullptr)
  7549. {
  7550. ParseNode *nameNode = memberNode->AsParseNodeBin()->pnode1;
  7551. ParseNode *exprNode = memberNode->AsParseNodeBin()->pnode2;
  7552. bool isFncDecl = exprNode->nop == knopFncDecl;
  7553. bool isClassMember = isFncDecl && exprNode->AsParseNodeFnc()->IsClassMember();
  7554. if (isFncDecl)
  7555. {
  7556. Assert(exprNode->AsParseNodeFnc()->HasHomeObj());
  7557. exprNode->AsParseNodeFnc()->SetHomeObjLocation(objectLocation);
  7558. }
  7559. Js::RegSlot computedNamePropertyKey = Js::Constants::NoRegister;
  7560. // Moved SetComputedNameVar before LdFld of prototype because loading the prototype undefers the function TypeHandler
  7561. // which makes this bytecode too late to influence the function.name.
  7562. if (nameNode->nop == knopComputedName)
  7563. {
  7564. // Computed property name
  7565. // Transparently pass the name expr
  7566. // The Emit will replace this with a temp register if necessary to preserve the value.
  7567. nameNode->location = nameNode->AsParseNodeUni()->pnode1->location;
  7568. // Save the previous value of the flag to be restored later.
  7569. bool prevFlag = byteCodeGenerator->forceStrictModeForClassComputedPropertyName;
  7570. // Strict mode must be enforced on the evaluation of computed property names inside
  7571. // classes, thus enable the flag if the computed property name is a class member.
  7572. byteCodeGenerator->forceStrictModeForClassComputedPropertyName = isClassMember || prevFlag;
  7573. computedNamePropertyKey = funcInfo->AcquireTmpRegister();
  7574. EmitBinaryOpnds(nameNode, exprNode, byteCodeGenerator, funcInfo, computedNamePropertyKey);
  7575. // Restore the flag's previous value.
  7576. byteCodeGenerator->forceStrictModeForClassComputedPropertyName = prevFlag;
  7577. if (isFncDecl)
  7578. {
  7579. if (exprNode->AsParseNodeFnc()->pnodeName == nullptr)
  7580. {
  7581. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SetComputedNameVar, exprNode->location, computedNamePropertyKey);
  7582. exprNode->AsParseNodeFnc()->SetHasComputedName();
  7583. }
  7584. }
  7585. else if (exprNode->nop == knopClassDecl)
  7586. {
  7587. if (exprNode->AsParseNodeClass()->pnodeName == nullptr)
  7588. {
  7589. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SetComputedNameVar, exprNode->location, computedNamePropertyKey);
  7590. exprNode->AsParseNodeClass()->pnodeConstructor->SetHasComputedName();
  7591. }
  7592. }
  7593. }
  7594. if (nameNode->nop == knopComputedName)
  7595. {
  7596. AssertOrFailFast(memberNode->nop == knopGetMember || memberNode->nop == knopSetMember || memberNode->nop == knopMember);
  7597. Js::OpCode setOp = memberNode->nop == knopGetMember ?
  7598. (isClassMember ? Js::OpCode::InitClassMemberGetComputedName : Js::OpCode::InitGetElemI) :
  7599. memberNode->nop == knopSetMember ?
  7600. (isClassMember ? Js::OpCode::InitClassMemberSetComputedName : Js::OpCode::InitSetElemI) :
  7601. (isClassMember ? Js::OpCode::InitClassMemberComputedName : Js::OpCode::InitComputedProperty);
  7602. // Save the previous value of the flag to be restored later.
  7603. bool prevFlag = byteCodeGenerator->forceStrictModeForClassComputedPropertyName;
  7604. byteCodeGenerator->forceStrictModeForClassComputedPropertyName = isClassMember || prevFlag;
  7605. // Strict mode must be enforced on the evaluation of computed property names inside
  7606. // classes, thus enable the flag if the computed property name is a class member.
  7607. byteCodeGenerator->Writer()->Element(setOp, exprNode->location, objectLocation, computedNamePropertyKey, true,
  7608. byteCodeGenerator->forceStrictModeForClassComputedPropertyName);
  7609. // Restore the flag's previous value.
  7610. byteCodeGenerator->forceStrictModeForClassComputedPropertyName = prevFlag;
  7611. funcInfo->ReleaseLoc(exprNode);
  7612. funcInfo->ReleaseLoc(nameNode);
  7613. funcInfo->ReleaseTmpRegister(computedNamePropertyKey);
  7614. return;
  7615. }
  7616. Js::OpCode stFldOpCode = (Js::OpCode)0;
  7617. if (useStore)
  7618. {
  7619. stFldOpCode = ByteCodeGenerator::GetStFldOpCode(funcInfo, false, false, false, isClassMember);
  7620. }
  7621. Emit(exprNode, byteCodeGenerator, funcInfo, false);
  7622. Js::PropertyId propertyId = nameNode->AsParseNodeStr()->pid->GetPropertyId();
  7623. if (Js::PropertyIds::name == propertyId
  7624. && exprNode->nop == knopFncDecl
  7625. && exprNode->AsParseNodeFnc()->IsStaticMember()
  7626. && parentNode != nullptr && parentNode->nop == knopClassDecl
  7627. && parentNode->AsParseNodeClass()->pnodeConstructor != nullptr)
  7628. {
  7629. Js::ParseableFunctionInfo* nameFunc = parentNode->AsParseNodeClass()->pnodeConstructor->funcInfo->byteCodeFunction->GetParseableFunctionInfo();
  7630. nameFunc->SetIsStaticNameFunction(true);
  7631. }
  7632. if (memberNode->nop == knopMember || memberNode->nop == knopMemberShort)
  7633. {
  7634. // The internal prototype should be set only if the production is of the form PropertyDefinition : PropertyName : AssignmentExpression
  7635. if (propertyId == Js::PropertyIds::__proto__ && memberNode->nop != knopMemberShort && (exprNode->nop != knopFncDecl || !exprNode->AsParseNodeFnc()->IsMethod()))
  7636. {
  7637. byteCodeGenerator->Writer()->Property(Js::OpCode::InitProto, exprNode->location, objectLocation,
  7638. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  7639. }
  7640. else
  7641. {
  7642. uint cacheId = funcInfo->FindOrAddInlineCacheId(objectLocation, propertyId, false, true);
  7643. Js::OpCode patchablePropertyOpCode;
  7644. if (useStore)
  7645. {
  7646. patchablePropertyOpCode = stFldOpCode;
  7647. }
  7648. else if (isClassMember)
  7649. {
  7650. patchablePropertyOpCode = Js::OpCode::InitClassMember;
  7651. }
  7652. else
  7653. {
  7654. patchablePropertyOpCode = Js::OpCode::InitFld;
  7655. }
  7656. byteCodeGenerator->Writer()->PatchableProperty(patchablePropertyOpCode, exprNode->location, objectLocation, cacheId);
  7657. }
  7658. }
  7659. else
  7660. {
  7661. AssertOrFailFast(memberNode->nop == knopGetMember || memberNode->nop == knopSetMember);
  7662. Js::OpCode setOp = memberNode->nop == knopGetMember ?
  7663. (isClassMember ? Js::OpCode::InitClassMemberGet : Js::OpCode::InitGetFld) :
  7664. (isClassMember ? Js::OpCode::InitClassMemberSet : Js::OpCode::InitSetFld);
  7665. byteCodeGenerator->Writer()->Property(setOp, exprNode->location, objectLocation, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  7666. }
  7667. funcInfo->ReleaseLoc(exprNode);
  7668. if (propertyId == Js::PropertyIds::valueOf)
  7669. {
  7670. byteCodeGenerator->GetScriptContext()->optimizationOverrides.SetSideEffects(Js::SideEffects_ValueOf);
  7671. }
  7672. else if (propertyId == Js::PropertyIds::toString)
  7673. {
  7674. byteCodeGenerator->GetScriptContext()->optimizationOverrides.SetSideEffects(Js::SideEffects_ToString);
  7675. }
  7676. }
  7677. void EmitObjectSpreadNode(ParseNode *spreadNode, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7678. {
  7679. Js::RegSlot fromObjectLocation;
  7680. ParseNode *exprNode = spreadNode->AsParseNodeUni()->pnode1;
  7681. Emit(exprNode, byteCodeGenerator, funcInfo, false);
  7682. fromObjectLocation = exprNode->location;
  7683. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SpreadObjectLiteral, fromObjectLocation, objectLocation);
  7684. funcInfo->ReleaseLoc(exprNode);
  7685. }
  7686. void EmitClassInitializers(ParseNode *memberList, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, ParseNode* parentNode, bool isObjectEmpty)
  7687. {
  7688. if (memberList != nullptr)
  7689. {
  7690. while (memberList->nop == knopList)
  7691. {
  7692. ParseNode *memberNode = memberList->AsParseNodeBin()->pnode1;
  7693. EmitMemberNode(memberNode, objectLocation, byteCodeGenerator, funcInfo, parentNode, /*useStore*/ false, &isObjectEmpty);
  7694. memberList = memberList->AsParseNodeBin()->pnode2;
  7695. }
  7696. EmitMemberNode(memberList, objectLocation, byteCodeGenerator, funcInfo, parentNode, /*useStore*/ false, &isObjectEmpty);
  7697. }
  7698. }
  7699. void EmitObjectInitializers(ParseNode *memberList, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7700. {
  7701. ParseNode *pmemberList = memberList;
  7702. unsigned int argCount = 0;
  7703. uint32 value;
  7704. Js::PropertyId propertyId;
  7705. //
  7706. // 1. Add all non-int property ids to a dictionary propertyIds with value true
  7707. // 2. Get the count of propertyIds
  7708. // 3. Create a propertyId array of size count
  7709. // 4. Put the propIds in the auxiliary area
  7710. // 5. Get the objectLiteralCacheId
  7711. // 6. Generate propId inits with values
  7712. //
  7713. // Handle propertyId collision
  7714. typedef JsUtil::BaseHashSet<Js::PropertyId, ArenaAllocator, PowerOf2SizePolicy> PropertyIdSet;
  7715. PropertyIdSet* propertyIds = Anew(byteCodeGenerator->GetAllocator(), PropertyIdSet, byteCodeGenerator->GetAllocator(), 17);
  7716. bool hasComputedNameOrSpread = false;
  7717. if (memberList != nullptr)
  7718. {
  7719. while (memberList->nop == knopList)
  7720. {
  7721. if (memberList->AsParseNodeBin()->pnode1->nop == knopEllipsis || memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->nop == knopComputedName)
  7722. {
  7723. hasComputedNameOrSpread = true;
  7724. break;
  7725. }
  7726. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7727. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value))
  7728. {
  7729. propertyIds->Item(propertyId);
  7730. }
  7731. memberList = memberList->AsParseNodeBin()->pnode2;
  7732. }
  7733. if (memberList->nop != knopEllipsis && memberList->AsParseNodeBin()->pnode1->nop != knopComputedName && !hasComputedNameOrSpread)
  7734. {
  7735. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7736. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value))
  7737. {
  7738. propertyIds->Item(propertyId);
  7739. }
  7740. }
  7741. }
  7742. argCount = propertyIds->Count();
  7743. memberList = pmemberList;
  7744. if ((memberList == nullptr) || (argCount == 0))
  7745. {
  7746. // Empty literal or numeric property only object literal
  7747. byteCodeGenerator->Writer()->Reg1(Js::OpCode::NewScObjectSimple, objectLocation);
  7748. }
  7749. else
  7750. {
  7751. uint32 allocSize = UInt32Math::Mul(argCount, sizeof(Js::PropertyId));
  7752. Js::PropertyIdArray *propIds = AnewPlus(byteCodeGenerator->GetAllocator(), allocSize, Js::PropertyIdArray, argCount, 0);
  7753. if (propertyIds->ContainsKey(Js::PropertyIds::__proto__))
  7754. {
  7755. // Always record whether the initializer contains __proto__ no matter if current environment has it enabled
  7756. // or not, in case the bytecode is later run with __proto__ enabled.
  7757. propIds->has__proto__ = true;
  7758. }
  7759. unsigned int argIndex = 0;
  7760. while (memberList->nop == knopList)
  7761. {
  7762. if (memberList->AsParseNodeBin()->pnode1->nop == knopEllipsis || memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->nop == knopComputedName)
  7763. {
  7764. break;
  7765. }
  7766. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7767. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value) && propertyIds->Remove(propertyId))
  7768. {
  7769. propIds->elements[argIndex] = propertyId;
  7770. argIndex++;
  7771. }
  7772. memberList = memberList->AsParseNodeBin()->pnode2;
  7773. }
  7774. if (memberList->nop != knopEllipsis && memberList->AsParseNodeBin()->pnode1->nop != knopComputedName && !hasComputedNameOrSpread)
  7775. {
  7776. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7777. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value) && propertyIds->Remove(propertyId))
  7778. {
  7779. propIds->elements[argIndex] = propertyId;
  7780. argIndex++;
  7781. }
  7782. }
  7783. uint32 literalObjectId = funcInfo->GetParsedFunctionBody()->NewObjectLiteral();
  7784. // Generate the opcode with propIds and cacheId
  7785. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::NewScObjectLiteral, objectLocation, propIds, UInt32Math::Add(sizeof(Js::PropertyIdArray), allocSize), literalObjectId);
  7786. Adelete(byteCodeGenerator->GetAllocator(), propertyIds);
  7787. AdeletePlus(byteCodeGenerator->GetAllocator(), allocSize, propIds);
  7788. }
  7789. memberList = pmemberList;
  7790. bool useStore = false;
  7791. // Generate the actual assignment to those properties
  7792. if (memberList != nullptr)
  7793. {
  7794. while (memberList->nop == knopList)
  7795. {
  7796. ParseNode *memberNode = memberList->AsParseNodeBin()->pnode1;
  7797. if (memberNode->nop == knopEllipsis)
  7798. {
  7799. byteCodeGenerator->StartSubexpression(memberNode);
  7800. EmitObjectSpreadNode(memberNode, objectLocation, byteCodeGenerator, funcInfo);
  7801. byteCodeGenerator->EndSubexpression(memberNode);
  7802. }
  7803. else
  7804. {
  7805. if (memberNode->AsParseNodeBin()->pnode1->nop == knopComputedName)
  7806. {
  7807. useStore = true;
  7808. }
  7809. byteCodeGenerator->StartSubexpression(memberNode);
  7810. EmitMemberNode(memberNode, objectLocation, byteCodeGenerator, funcInfo, nullptr, useStore);
  7811. byteCodeGenerator->EndSubexpression(memberNode);
  7812. }
  7813. memberList = memberList->AsParseNodeBin()->pnode2;
  7814. }
  7815. byteCodeGenerator->StartSubexpression(memberList);
  7816. if (memberList->nop == knopEllipsis)
  7817. {
  7818. EmitObjectSpreadNode(memberList, objectLocation, byteCodeGenerator, funcInfo);
  7819. }
  7820. else
  7821. {
  7822. EmitMemberNode(memberList, objectLocation, byteCodeGenerator, funcInfo, nullptr, useStore);
  7823. }
  7824. byteCodeGenerator->EndSubexpression(memberList);
  7825. }
  7826. }
  7827. void EmitStringTemplate(ParseNodeStrTemplate *pnodeStrTemplate, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7828. {
  7829. Assert(pnodeStrTemplate->pnodeStringLiterals);
  7830. // For a tagged string template, we will create the callsite constant object as part of the FunctionBody constants table.
  7831. // We only need to emit code for non-tagged string templates here.
  7832. if (!pnodeStrTemplate->isTaggedTemplate)
  7833. {
  7834. // If we have no substitutions and this is not a tagged template, we can emit just the single cooked string.
  7835. if (pnodeStrTemplate->pnodeSubstitutionExpressions == nullptr)
  7836. {
  7837. Assert(pnodeStrTemplate->pnodeStringLiterals->nop != knopList);
  7838. funcInfo->AcquireLoc(pnodeStrTemplate);
  7839. Emit(pnodeStrTemplate->pnodeStringLiterals, byteCodeGenerator, funcInfo, false);
  7840. Assert(pnodeStrTemplate->location != pnodeStrTemplate->pnodeStringLiterals->location);
  7841. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnodeStrTemplate->location, pnodeStrTemplate->pnodeStringLiterals->location);
  7842. funcInfo->ReleaseLoc(pnodeStrTemplate->pnodeStringLiterals);
  7843. }
  7844. else
  7845. {
  7846. // If we have substitutions but no tag function, we can skip the callSite object construction (and also ignore raw strings).
  7847. funcInfo->AcquireLoc(pnodeStrTemplate);
  7848. // First string must be a list node since we have substitutions.
  7849. AssertMsg(pnodeStrTemplate->pnodeStringLiterals->nop == knopList, "First string in the list must be a knopList node.");
  7850. ParseNode* stringNodeList = pnodeStrTemplate->pnodeStringLiterals;
  7851. // Emit the first string and load that into the pnode location.
  7852. // skip loading the string if it is empty
  7853. ParseNode* firstString = stringNodeList->AsParseNodeBin()->pnode1;
  7854. bool skippedFirst = false;
  7855. if (firstString->AsParseNodeStr()->pid->Cch() == 0)
  7856. {
  7857. skippedFirst = true;
  7858. }
  7859. else
  7860. {
  7861. Emit(stringNodeList->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  7862. Assert(pnodeStrTemplate->location != stringNodeList->AsParseNodeBin()->pnode1->location);
  7863. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnodeStrTemplate->location, stringNodeList->AsParseNodeBin()->pnode1->location);
  7864. funcInfo->ReleaseLoc(stringNodeList->AsParseNodeBin()->pnode1);
  7865. }
  7866. ParseNode* expressionNodeList = pnodeStrTemplate->pnodeSubstitutionExpressions;
  7867. ParseNode* stringNode;
  7868. ParseNode* expressionNode;
  7869. // Now append the substitution expressions and remaining string constants via normal add operator
  7870. // We will always have one more string constant than substitution expression
  7871. // `strcon1 ${expr1} strcon2 ${expr2} strcon3` = strcon1 + expr1 + strcon2 + expr2 + strcon3
  7872. //
  7873. // strcon1 --- step 1 (above)
  7874. // expr1 \__ step 2
  7875. // strcon2 /
  7876. // expr2 \__ step 3
  7877. // strcon3 /
  7878. while (stringNodeList->nop == knopList)
  7879. {
  7880. // If the current head of the expression list is a list, fetch the node and walk the list.
  7881. if (expressionNodeList->nop == knopList)
  7882. {
  7883. expressionNode = expressionNodeList->AsParseNodeBin()->pnode1;
  7884. expressionNodeList = expressionNodeList->AsParseNodeBin()->pnode2;
  7885. }
  7886. else
  7887. {
  7888. // This is the last element of the expression list.
  7889. expressionNode = expressionNodeList;
  7890. }
  7891. // Emit the expression and append it to the string we're building.
  7892. Emit(expressionNode, byteCodeGenerator, funcInfo, false);
  7893. // if this is the first expression AND the initial string was empty write directly to the pnodeStrTemplate location
  7894. if (skippedFirst == true)
  7895. {
  7896. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Str, pnodeStrTemplate->location, expressionNode->location);
  7897. skippedFirst = false;
  7898. }
  7899. else
  7900. {
  7901. Js::RegSlot toStringLocation = funcInfo->AcquireTmpRegister();
  7902. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Str, toStringLocation, expressionNode->location);
  7903. byteCodeGenerator->Writer()->Reg3(Js::OpCode::Add_A, pnodeStrTemplate->location, pnodeStrTemplate->location, toStringLocation);
  7904. funcInfo->ReleaseTmpRegister(toStringLocation);
  7905. }
  7906. funcInfo->ReleaseLoc(expressionNode);
  7907. // Move to the next string in the list - we already got ahead of the expressions in the first string literal above.
  7908. stringNodeList = stringNodeList->AsParseNodeBin()->pnode2;
  7909. // If the current head of the string literal list is also a list node, need to fetch the actual string literal node.
  7910. if (stringNodeList->nop == knopList)
  7911. {
  7912. stringNode = stringNodeList->AsParseNodeBin()->pnode1;
  7913. }
  7914. else
  7915. {
  7916. // This is the last element of the string literal list.
  7917. stringNode = stringNodeList;
  7918. }
  7919. // Emit the string node following the previous expression and append it to the string.
  7920. // This is either just some string in the list or it is the last string.
  7921. if (stringNode->AsParseNodeStr()->pid->Cch() != 0)
  7922. {
  7923. Emit(stringNode, byteCodeGenerator, funcInfo, false);
  7924. byteCodeGenerator->Writer()->Reg3(Js::OpCode::Add_A, pnodeStrTemplate->location, pnodeStrTemplate->location, stringNode->location);
  7925. funcInfo->ReleaseLoc(stringNode);
  7926. }
  7927. }
  7928. }
  7929. }
  7930. }
  7931. void SetNewArrayElements(ParseNode *pnode, Js::RegSlot arrayLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7932. {
  7933. ParseNode *args = pnode->AsParseNodeUni()->pnode1;
  7934. uint argCount = pnode->AsParseNodeArrLit()->count;
  7935. uint spreadCount = pnode->AsParseNodeArrLit()->spreadCount;
  7936. bool nativeArrays = CreateNativeArrays(byteCodeGenerator, funcInfo);
  7937. bool arrayIntOpt = nativeArrays && pnode->AsParseNodeArrLit()->arrayOfInts;
  7938. if (arrayIntOpt)
  7939. {
  7940. int extraAlloc = 0, auxSize = 0;
  7941. if (Int32Math::Mul(argCount, sizeof(int32), &extraAlloc)
  7942. || Int32Math::Add(sizeof(Js::AuxArray<int>), extraAlloc, &auxSize))
  7943. {
  7944. ::Math::DefaultOverflowPolicy();
  7945. }
  7946. Js::AuxArray<int> *ints = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<int32>, argCount);
  7947. EmitConstantArgsToIntArray(byteCodeGenerator, ints->elements, args, argCount);
  7948. Assert(!pnode->AsParseNodeArrLit()->hasMissingValues);
  7949. byteCodeGenerator->Writer()->Auxiliary(
  7950. Js::OpCode::NewScIntArray,
  7951. pnode->location,
  7952. ints,
  7953. auxSize,
  7954. argCount);
  7955. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, ints);
  7956. return;
  7957. }
  7958. bool arrayNumOpt = nativeArrays && pnode->AsParseNodeArrLit()->arrayOfNumbers;
  7959. if (arrayNumOpt)
  7960. {
  7961. int extraAlloc = 0, auxSize = 0;
  7962. if (Int32Math::Mul(argCount, sizeof(double), &extraAlloc)
  7963. || Int32Math::Add(sizeof(Js::AuxArray<double>), extraAlloc, &auxSize))
  7964. {
  7965. ::Math::DefaultOverflowPolicy();
  7966. }
  7967. Js::AuxArray<double> *doubles = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<double>, argCount);
  7968. EmitConstantArgsToFltArray(byteCodeGenerator, doubles->elements, args, argCount);
  7969. Assert(!pnode->AsParseNodeArrLit()->hasMissingValues);
  7970. byteCodeGenerator->Writer()->Auxiliary(
  7971. Js::OpCode::NewScFltArray,
  7972. pnode->location,
  7973. doubles,
  7974. auxSize,
  7975. argCount);
  7976. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, doubles);
  7977. return;
  7978. }
  7979. bool arrayLitOpt = pnode->AsParseNodeArrLit()->arrayOfTaggedInts && pnode->AsParseNodeArrLit()->count > 1;
  7980. Assert(!arrayLitOpt || !nativeArrays);
  7981. Js::RegSlot spreadArrLoc = arrayLocation;
  7982. Js::AuxArray<uint32> *spreadIndices = nullptr;
  7983. const uint extraAlloc = UInt32Math::Mul(spreadCount, sizeof(uint32));
  7984. if (pnode->AsParseNodeArrLit()->spreadCount > 0)
  7985. {
  7986. arrayLocation = funcInfo->AcquireTmpRegister();
  7987. spreadIndices = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<uint32>, spreadCount);
  7988. }
  7989. byteCodeGenerator->Writer()->Reg1Unsigned1(
  7990. pnode->AsParseNodeArrLit()->hasMissingValues ? Js::OpCode::NewScArrayWithMissingValues : Js::OpCode::NewScArray,
  7991. arrayLocation,
  7992. argCount);
  7993. if (args != nullptr)
  7994. {
  7995. Js::OpCode opcode;
  7996. Js::RegSlot arrLoc;
  7997. if (argCount == 1 && !byteCodeGenerator->Writer()->DoProfileNewScArrayOp(Js::OpCode::NewScArray))
  7998. {
  7999. opcode = Js::OpCode::StArrItemC_CI4;
  8000. arrLoc = arrayLocation;
  8001. }
  8002. else if (arrayLitOpt)
  8003. {
  8004. opcode = Js::OpCode::StArrSegItem_A;
  8005. arrLoc = funcInfo->AcquireTmpRegister();
  8006. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdArrHead, arrLoc, arrayLocation);
  8007. }
  8008. else if (Js::JavascriptArray::HasInlineHeadSegment(argCount))
  8009. {
  8010. // The head segment will be allocated inline as an interior pointer. To keep the array alive, the set operation
  8011. // should be done relative to the array header to keep it alive (instead of the array segment).
  8012. opcode = Js::OpCode::StArrInlineItem_CI4;
  8013. arrLoc = arrayLocation;
  8014. }
  8015. else if (argCount <= Js::JavascriptArray::MaxInitialDenseLength)
  8016. {
  8017. opcode = Js::OpCode::StArrSegItem_CI4;
  8018. arrLoc = funcInfo->AcquireTmpRegister();
  8019. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdArrHead, arrLoc, arrayLocation);
  8020. }
  8021. else
  8022. {
  8023. opcode = Js::OpCode::StArrItemI_CI4;
  8024. arrLoc = arrayLocation;
  8025. }
  8026. if (arrayLitOpt)
  8027. {
  8028. uint32 allocSize = UInt32Math::Mul(argCount, sizeof(Js::Var));
  8029. Js::VarArray *vars = AnewPlus(byteCodeGenerator->GetAllocator(), allocSize, Js::VarArray, argCount);
  8030. EmitConstantArgsToVarArray(byteCodeGenerator, vars->elements, args, argCount);
  8031. // Generate the opcode with vars
  8032. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::StArrSegItem_A, arrLoc, vars, UInt32Math::Add(sizeof(Js::VarArray), allocSize), argCount);
  8033. AdeletePlus(byteCodeGenerator->GetAllocator(), allocSize, vars);
  8034. }
  8035. else
  8036. {
  8037. uint i = 0;
  8038. unsigned spreadIndex = 0;
  8039. Js::RegSlot rhsLocation;
  8040. while (args->nop == knopList)
  8041. {
  8042. if (args->AsParseNodeBin()->pnode1->nop != knopEmpty)
  8043. {
  8044. Emit(args->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  8045. rhsLocation = args->AsParseNodeBin()->pnode1->location;
  8046. Js::RegSlot regVal = rhsLocation;
  8047. if (args->AsParseNodeBin()->pnode1->nop == knopEllipsis)
  8048. {
  8049. AnalysisAssert(spreadIndices);
  8050. regVal = funcInfo->AcquireTmpRegister();
  8051. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, rhsLocation);
  8052. spreadIndices->elements[spreadIndex++] = i;
  8053. }
  8054. byteCodeGenerator->Writer()->ElementUnsigned1(opcode, regVal, arrLoc, i);
  8055. if (args->AsParseNodeBin()->pnode1->nop == knopEllipsis)
  8056. {
  8057. funcInfo->ReleaseTmpRegister(regVal);
  8058. }
  8059. funcInfo->ReleaseLoc(args->AsParseNodeBin()->pnode1);
  8060. }
  8061. args = args->AsParseNodeBin()->pnode2;
  8062. i++;
  8063. }
  8064. if (args->nop != knopEmpty)
  8065. {
  8066. Emit(args, byteCodeGenerator, funcInfo, false);
  8067. rhsLocation = args->location;
  8068. Js::RegSlot regVal = rhsLocation;
  8069. if (args->nop == knopEllipsis)
  8070. {
  8071. regVal = funcInfo->AcquireTmpRegister();
  8072. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, rhsLocation);
  8073. AnalysisAssert(spreadIndices);
  8074. spreadIndices->elements[spreadIndex] = i;
  8075. }
  8076. byteCodeGenerator->Writer()->ElementUnsigned1(opcode, regVal, arrLoc, i);
  8077. if (args->nop == knopEllipsis)
  8078. {
  8079. funcInfo->ReleaseTmpRegister(regVal);
  8080. }
  8081. funcInfo->ReleaseLoc(args);
  8082. i++;
  8083. }
  8084. Assert(i <= argCount);
  8085. }
  8086. if (arrLoc != arrayLocation)
  8087. {
  8088. funcInfo->ReleaseTmpRegister(arrLoc);
  8089. }
  8090. }
  8091. if (pnode->AsParseNodeArrLit()->spreadCount > 0)
  8092. {
  8093. byteCodeGenerator->Writer()->Reg2Aux(Js::OpCode::SpreadArrayLiteral, spreadArrLoc, arrayLocation, spreadIndices, UInt32Math::Add(sizeof(Js::AuxArray<uint32>), extraAlloc), extraAlloc);
  8094. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, spreadIndices);
  8095. funcInfo->ReleaseTmpRegister(arrayLocation);
  8096. }
  8097. }
  8098. // FIX: TODO: mixed-mode expressions (arithmetic expressions mixed with boolean expressions); current solution
  8099. // will not short-circuit in some cases and is not complete (for example: var i=(x==y))
  8100. // This uses Aho and Ullman style double-branch generation (p. 494 ASU); we will need to peephole optimize or replace
  8101. // with special case for single-branch style.
  8102. void EmitBooleanExpression(
  8103. _In_ ParseNode* expr,
  8104. Js::ByteCodeLabel trueLabel,
  8105. Js::ByteCodeLabel falseLabel,
  8106. _In_ ByteCodeGenerator* byteCodeGenerator,
  8107. _In_ FuncInfo* funcInfo,
  8108. bool trueFallthrough,
  8109. bool falseFallthrough)
  8110. {
  8111. Assert(!trueFallthrough || !falseFallthrough);
  8112. byteCodeGenerator->StartStatement(expr);
  8113. switch (expr->nop)
  8114. {
  8115. case knopLogOr:
  8116. {
  8117. Js::ByteCodeLabel leftFalse = byteCodeGenerator->Writer()->DefineLabel();
  8118. EmitBooleanExpression(expr->AsParseNodeBin()->pnode1, trueLabel, leftFalse, byteCodeGenerator, funcInfo, false, true);
  8119. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  8120. byteCodeGenerator->Writer()->MarkLabel(leftFalse);
  8121. EmitBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, falseLabel, byteCodeGenerator, funcInfo, trueFallthrough, falseFallthrough);
  8122. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  8123. break;
  8124. }
  8125. case knopLogAnd:
  8126. {
  8127. Js::ByteCodeLabel leftTrue = byteCodeGenerator->Writer()->DefineLabel();
  8128. EmitBooleanExpression(expr->AsParseNodeBin()->pnode1, leftTrue, falseLabel, byteCodeGenerator, funcInfo, true, false);
  8129. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  8130. byteCodeGenerator->Writer()->MarkLabel(leftTrue);
  8131. EmitBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, falseLabel, byteCodeGenerator, funcInfo, trueFallthrough, falseFallthrough);
  8132. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  8133. break;
  8134. }
  8135. case knopLogNot:
  8136. EmitBooleanExpression(expr->AsParseNodeUni()->pnode1, falseLabel, trueLabel, byteCodeGenerator, funcInfo, falseFallthrough, trueFallthrough);
  8137. funcInfo->ReleaseLoc(expr->AsParseNodeUni()->pnode1);
  8138. break;
  8139. case knopEq:
  8140. case knopEqv:
  8141. case knopNEqv:
  8142. case knopNe:
  8143. case knopLt:
  8144. case knopLe:
  8145. case knopGe:
  8146. case knopGt:
  8147. EmitBinaryOpnds(expr->AsParseNodeBin()->pnode1, expr->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  8148. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  8149. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  8150. byteCodeGenerator->Writer()->BrReg2(nopToOp[expr->nop], trueLabel, expr->AsParseNodeBin()->pnode1->location,
  8151. expr->AsParseNodeBin()->pnode2->location);
  8152. if (!falseFallthrough)
  8153. {
  8154. byteCodeGenerator->Writer()->Br(falseLabel);
  8155. }
  8156. break;
  8157. case knopTrue:
  8158. if (!trueFallthrough)
  8159. {
  8160. byteCodeGenerator->Writer()->Br(trueLabel);
  8161. }
  8162. break;
  8163. case knopFalse:
  8164. if (!falseFallthrough)
  8165. {
  8166. byteCodeGenerator->Writer()->Br(falseLabel);
  8167. }
  8168. break;
  8169. default:
  8170. // Note: we usually release the temp assigned to a node after we Emit it.
  8171. // But in this case, EmitBooleanExpression is just a wrapper around a normal Emit call,
  8172. // and the caller of EmitBooleanExpression expects to be able to release this register.
  8173. Emit(expr, byteCodeGenerator, funcInfo, false);
  8174. if (trueFallthrough)
  8175. {
  8176. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  8177. }
  8178. else
  8179. {
  8180. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  8181. if (!falseFallthrough)
  8182. {
  8183. byteCodeGenerator->Writer()->Br(falseLabel);
  8184. }
  8185. }
  8186. break;
  8187. }
  8188. byteCodeGenerator->EndStatement(expr);
  8189. }
  8190. void EmitGeneratingBooleanExpression(ParseNode *expr, Js::ByteCodeLabel trueLabel, bool truefallthrough, Js::ByteCodeLabel falseLabel, bool falsefallthrough, Js::RegSlot writeto,
  8191. bool reuseLoc, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8192. {
  8193. switch (expr->nop)
  8194. {
  8195. case knopLogOr:
  8196. {
  8197. byteCodeGenerator->StartStatement(expr);
  8198. Js::ByteCodeLabel leftFalse = byteCodeGenerator->Writer()->DefineLabel();
  8199. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode1, trueLabel, false, leftFalse, true, writeto, reuseLoc, byteCodeGenerator, funcInfo);
  8200. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  8201. byteCodeGenerator->Writer()->MarkLabel(leftFalse);
  8202. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, truefallthrough, falseLabel, falsefallthrough, writeto, true, byteCodeGenerator, funcInfo);
  8203. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  8204. byteCodeGenerator->EndStatement(expr);
  8205. break;
  8206. }
  8207. case knopLogAnd:
  8208. {
  8209. byteCodeGenerator->StartStatement(expr);
  8210. Js::ByteCodeLabel leftTrue = byteCodeGenerator->Writer()->DefineLabel();
  8211. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode1, leftTrue, true, falseLabel, false, writeto, reuseLoc, byteCodeGenerator, funcInfo);
  8212. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  8213. byteCodeGenerator->Writer()->MarkLabel(leftTrue);
  8214. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, truefallthrough, falseLabel, falsefallthrough, writeto, true, byteCodeGenerator, funcInfo);
  8215. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  8216. byteCodeGenerator->EndStatement(expr);
  8217. break;
  8218. }
  8219. case knopLogNot:
  8220. {
  8221. byteCodeGenerator->StartStatement(expr);
  8222. // this time we want a boolean expression, since Logical Not is nice and only returns true or false
  8223. Js::ByteCodeLabel emitTrue = byteCodeGenerator->Writer()->DefineLabel();
  8224. Js::ByteCodeLabel emitFalse = byteCodeGenerator->Writer()->DefineLabel();
  8225. EmitBooleanExpression(expr->AsParseNodeUni()->pnode1, emitFalse, emitTrue, byteCodeGenerator, funcInfo, false, true);
  8226. byteCodeGenerator->Writer()->MarkLabel(emitTrue);
  8227. byteCodeGenerator->Writer()->Reg1(reuseLoc ? Js::OpCode::LdTrue_ReuseLoc : Js::OpCode::LdTrue, writeto);
  8228. byteCodeGenerator->Writer()->Br(trueLabel);
  8229. byteCodeGenerator->Writer()->MarkLabel(emitFalse);
  8230. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse_ReuseLoc, writeto);
  8231. if (!falsefallthrough)
  8232. {
  8233. byteCodeGenerator->Writer()->Br(falseLabel);
  8234. }
  8235. funcInfo->ReleaseLoc(expr->AsParseNodeUni()->pnode1);
  8236. byteCodeGenerator->EndStatement(expr);
  8237. break;
  8238. }
  8239. case knopEq:
  8240. case knopEqv:
  8241. case knopNEqv:
  8242. case knopNe:
  8243. case knopLt:
  8244. case knopLe:
  8245. case knopGe:
  8246. case knopGt:
  8247. byteCodeGenerator->StartStatement(expr);
  8248. EmitBinaryOpnds(expr->AsParseNodeBin()->pnode1, expr->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  8249. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  8250. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  8251. funcInfo->AcquireLoc(expr);
  8252. byteCodeGenerator->Writer()->Reg3(nopToCMOp[expr->nop], expr->location, expr->AsParseNodeBin()->pnode1->location,
  8253. expr->AsParseNodeBin()->pnode2->location);
  8254. byteCodeGenerator->Writer()->Reg2(reuseLoc ? Js::OpCode::Ld_A_ReuseLoc : Js::OpCode::Ld_A, writeto, expr->location);
  8255. // The inliner likes small bytecode
  8256. if (!(truefallthrough || falsefallthrough))
  8257. {
  8258. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  8259. byteCodeGenerator->Writer()->Br(falseLabel);
  8260. }
  8261. else if (truefallthrough && !falsefallthrough) {
  8262. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  8263. }
  8264. else if (falsefallthrough && !truefallthrough) {
  8265. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  8266. }
  8267. byteCodeGenerator->EndStatement(expr);
  8268. break;
  8269. case knopTrue:
  8270. byteCodeGenerator->StartStatement(expr);
  8271. byteCodeGenerator->Writer()->Reg1(reuseLoc ? Js::OpCode::LdTrue_ReuseLoc : Js::OpCode::LdTrue, writeto);
  8272. if (!truefallthrough)
  8273. {
  8274. byteCodeGenerator->Writer()->Br(trueLabel);
  8275. }
  8276. byteCodeGenerator->EndStatement(expr);
  8277. break;
  8278. case knopFalse:
  8279. byteCodeGenerator->StartStatement(expr);
  8280. byteCodeGenerator->Writer()->Reg1(reuseLoc ? Js::OpCode::LdFalse_ReuseLoc : Js::OpCode::LdFalse, writeto);
  8281. if (!falsefallthrough)
  8282. {
  8283. byteCodeGenerator->Writer()->Br(falseLabel);
  8284. }
  8285. byteCodeGenerator->EndStatement(expr);
  8286. break;
  8287. default:
  8288. // Note: we usually release the temp assigned to a node after we Emit it.
  8289. // But in this case, EmitBooleanExpression is just a wrapper around a normal Emit call,
  8290. // and the caller of EmitBooleanExpression expects to be able to release this register.
  8291. // For diagnostics purposes, register the name and dot to the statement list.
  8292. if (expr->nop == knopName || expr->nop == knopDot)
  8293. {
  8294. byteCodeGenerator->StartStatement(expr);
  8295. Emit(expr, byteCodeGenerator, funcInfo, false);
  8296. byteCodeGenerator->Writer()->Reg2(reuseLoc ? Js::OpCode::Ld_A_ReuseLoc : Js::OpCode::Ld_A, writeto, expr->location);
  8297. // The inliner likes small bytecode
  8298. if (!(truefallthrough || falsefallthrough))
  8299. {
  8300. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  8301. byteCodeGenerator->Writer()->Br(falseLabel);
  8302. }
  8303. else if (truefallthrough && !falsefallthrough) {
  8304. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  8305. }
  8306. else if (falsefallthrough && !truefallthrough) {
  8307. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  8308. }
  8309. byteCodeGenerator->EndStatement(expr);
  8310. }
  8311. else
  8312. {
  8313. Emit(expr, byteCodeGenerator, funcInfo, false);
  8314. byteCodeGenerator->Writer()->Reg2(reuseLoc ? Js::OpCode::Ld_A_ReuseLoc : Js::OpCode::Ld_A, writeto, expr->location);
  8315. // The inliner likes small bytecode
  8316. if (!(truefallthrough || falsefallthrough))
  8317. {
  8318. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  8319. byteCodeGenerator->Writer()->Br(falseLabel);
  8320. }
  8321. else if (truefallthrough && !falsefallthrough) {
  8322. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  8323. }
  8324. else if (falsefallthrough && !truefallthrough) {
  8325. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  8326. }
  8327. }
  8328. break;
  8329. }
  8330. }
  8331. // used by while and for loops
  8332. void EmitLoop(
  8333. ParseNodeStmt *loopNode,
  8334. ParseNode *cond,
  8335. ParseNode *body,
  8336. ParseNode *incr,
  8337. ByteCodeGenerator *byteCodeGenerator,
  8338. FuncInfo *funcInfo,
  8339. BOOL fReturnValue,
  8340. BOOL doWhile = FALSE,
  8341. ParseNodeBlock *forLoopBlock = nullptr)
  8342. {
  8343. // Need to increment loop count whether we are going to profile or not for HasLoop()
  8344. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  8345. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  8346. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8347. byteCodeGenerator->PushJumpCleanupForLoop(loopNode, loopId);
  8348. if (doWhile)
  8349. {
  8350. Emit(body, byteCodeGenerator, funcInfo, fReturnValue);
  8351. funcInfo->ReleaseLoc(body);
  8352. if (loopNode->emitLabels)
  8353. {
  8354. byteCodeGenerator->Writer()->MarkLabel(loopNode->continueLabel);
  8355. }
  8356. if (!ByteCodeGenerator::IsFalse(cond) ||
  8357. byteCodeGenerator->IsInDebugMode())
  8358. {
  8359. EmitBooleanExpression(cond, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, false, false);
  8360. }
  8361. funcInfo->ReleaseLoc(cond);
  8362. }
  8363. else
  8364. {
  8365. if (cond)
  8366. {
  8367. if (!(cond->nop == knopInt &&
  8368. cond->AsParseNodeInt()->lw != 0))
  8369. {
  8370. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  8371. EmitBooleanExpression(cond, trueLabel, continuePastLoop, byteCodeGenerator, funcInfo, true, false);
  8372. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  8373. }
  8374. funcInfo->ReleaseLoc(cond);
  8375. }
  8376. Emit(body, byteCodeGenerator, funcInfo, fReturnValue);
  8377. funcInfo->ReleaseLoc(body);
  8378. if (forLoopBlock != nullptr)
  8379. {
  8380. CloneEmitBlock(forLoopBlock, byteCodeGenerator, funcInfo);
  8381. }
  8382. if (loopNode->emitLabels)
  8383. {
  8384. byteCodeGenerator->Writer()->MarkLabel(loopNode->continueLabel);
  8385. }
  8386. if (incr != nullptr)
  8387. {
  8388. Emit(incr, byteCodeGenerator, funcInfo, false);
  8389. funcInfo->ReleaseLoc(incr);
  8390. }
  8391. byteCodeGenerator->Writer()->Br(loopEntrance);
  8392. }
  8393. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  8394. if (loopNode->emitLabels)
  8395. {
  8396. byteCodeGenerator->Writer()->MarkLabel(loopNode->breakLabel);
  8397. }
  8398. byteCodeGenerator->PopJumpCleanup();
  8399. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8400. }
  8401. void ByteCodeGenerator::EmitInvertedLoop(ParseNodeStmt* outerLoop, ParseNodeFor* invertedLoop, FuncInfo* funcInfo)
  8402. {
  8403. Js::ByteCodeLabel invertedLoopLabel = this->m_writer.DefineLabel();
  8404. Js::ByteCodeLabel afterInvertedLoop = this->m_writer.DefineLabel();
  8405. // emit branch around original
  8406. Emit(outerLoop->AsParseNodeFor()->pnodeInit, this, funcInfo, false);
  8407. funcInfo->ReleaseLoc(outerLoop->AsParseNodeFor()->pnodeInit);
  8408. this->m_writer.BrS(Js::OpCode::BrNotHasSideEffects, invertedLoopLabel, Js::SideEffects_Any);
  8409. // emit original
  8410. EmitLoop(outerLoop, outerLoop->AsParseNodeFor()->pnodeCond, outerLoop->AsParseNodeFor()->pnodeBody,
  8411. outerLoop->AsParseNodeFor()->pnodeIncr, this, funcInfo, false);
  8412. // clear temporary registers since inverted loop may share nodes with
  8413. // emitted original loop
  8414. VisitClearTmpRegs(outerLoop, this, funcInfo);
  8415. // emit branch around inverted
  8416. this->m_writer.Br(afterInvertedLoop);
  8417. this->m_writer.MarkLabel(invertedLoopLabel);
  8418. // Emit a zero trip test for the original outer-loop if the outer-loop
  8419. // has a condition
  8420. if (outerLoop->AsParseNodeFor()->pnodeCond)
  8421. {
  8422. Js::ByteCodeLabel zeroTrip = this->m_writer.DefineLabel();
  8423. ParseNode* testNode = this->GetParser()->CopyPnode(outerLoop->AsParseNodeFor()->pnodeCond);
  8424. EmitBooleanExpression(testNode, zeroTrip, afterInvertedLoop, this, funcInfo, true, false);
  8425. this->m_writer.MarkLabel(zeroTrip);
  8426. funcInfo->ReleaseLoc(testNode);
  8427. }
  8428. // emit inverted
  8429. Emit(invertedLoop->pnodeInit, this, funcInfo, false);
  8430. funcInfo->ReleaseLoc(invertedLoop->pnodeInit);
  8431. EmitLoop(invertedLoop, invertedLoop->pnodeCond, invertedLoop->pnodeBody,
  8432. invertedLoop->pnodeIncr, this, funcInfo, false);
  8433. this->m_writer.MarkLabel(afterInvertedLoop);
  8434. }
  8435. void EmitGetIterator(
  8436. Js::RegSlot iteratorReg,
  8437. Js::RegSlot iterableReg,
  8438. ByteCodeGenerator* byteCodeGenerator,
  8439. FuncInfo* funcInfo)
  8440. {
  8441. EmitGetObjectMethod(
  8442. iteratorReg,
  8443. iterableReg,
  8444. Js::PropertyIds::_symbolIterator,
  8445. byteCodeGenerator,
  8446. funcInfo);
  8447. EmitFunctionCall(iteratorReg, iteratorReg, iterableReg, byteCodeGenerator, funcInfo);
  8448. EmitThrowOnNotObject(iteratorReg, byteCodeGenerator);
  8449. }
  8450. void EmitGetAsyncIterator(
  8451. Js::RegSlot resultReg,
  8452. Js::RegSlot iterableReg,
  8453. ByteCodeGenerator* byteCodeGenerator,
  8454. FuncInfo* funcInfo)
  8455. {
  8456. auto* writer = byteCodeGenerator->Writer();
  8457. Js::ByteCodeLabel noAsyncIterator = writer->DefineLabel();
  8458. EmitGetOptionalObjectMethod(
  8459. resultReg,
  8460. iterableReg,
  8461. Js::PropertyIds::_symbolAsyncIterator,
  8462. noAsyncIterator,
  8463. byteCodeGenerator,
  8464. funcInfo);
  8465. EmitFunctionCall(resultReg, resultReg, iterableReg, byteCodeGenerator, funcInfo);
  8466. EmitThrowOnNotObject(resultReg, byteCodeGenerator);
  8467. Js::ByteCodeLabel finished = writer->DefineLabel();
  8468. writer->Br(finished);
  8469. // Iterable does not have a Symbol.asyncIterator method: attempt to get a sync
  8470. // iterable and wrap it with an AsyncFromSyncIterator
  8471. writer->MarkLabel(noAsyncIterator);
  8472. Js::RegSlot iteratorReg = funcInfo->AcquireTmpRegister();
  8473. EmitGetIterator(iteratorReg, iterableReg, byteCodeGenerator, funcInfo);
  8474. writer->Reg2(Js::OpCode::NewAsyncFromSyncIterator, iteratorReg, iteratorReg);
  8475. writer->Reg2(Js::OpCode::Ld_A_ReuseLoc, resultReg, iteratorReg);
  8476. funcInfo->ReleaseTmpRegister(iteratorReg);
  8477. byteCodeGenerator->Writer()->MarkLabel(finished);
  8478. }
  8479. // Generating
  8480. // if (hasReturnFunction) {
  8481. // value = Call Retrun;
  8482. // if (value != Object)
  8483. // throw TypeError;
  8484. // }
  8485. void EmitIteratorClose(
  8486. Js::RegSlot iteratorLocation,
  8487. ByteCodeGenerator* byteCodeGenerator,
  8488. FuncInfo* funcInfo,
  8489. bool isAsync)
  8490. {
  8491. Js::RegSlot returnReg = funcInfo->AcquireTmpRegister();
  8492. Js::ByteCodeLabel noReturn = byteCodeGenerator->Writer()->DefineLabel();
  8493. EmitGetOptionalObjectMethod(
  8494. returnReg,
  8495. iteratorLocation,
  8496. Js::PropertyIds::return_,
  8497. noReturn,
  8498. byteCodeGenerator,
  8499. funcInfo);
  8500. EmitFunctionCall(returnReg, returnReg, iteratorLocation, byteCodeGenerator, funcInfo);
  8501. // In for-await or async yield* use await on the returned value
  8502. if (isAsync)
  8503. EmitAwait(returnReg, returnReg, byteCodeGenerator, funcInfo);
  8504. EmitThrowOnNotObject(returnReg, byteCodeGenerator);
  8505. funcInfo->ReleaseTmpRegister(returnReg);
  8506. byteCodeGenerator->Writer()->MarkLabel(noReturn);
  8507. }
  8508. void EmitForInOfLoopBody(ParseNodeForInOrForOf *loopNode,
  8509. Js::ByteCodeLabel loopEntrance,
  8510. Js::ByteCodeLabel continuePastLoop,
  8511. ByteCodeGenerator *byteCodeGenerator,
  8512. FuncInfo *funcInfo,
  8513. BOOL fReturnValue)
  8514. {
  8515. if (loopNode->pnodeLval->nop != knopVarDecl &&
  8516. loopNode->pnodeLval->nop != knopLetDecl &&
  8517. loopNode->pnodeLval->nop != knopConstDecl)
  8518. {
  8519. EmitReference(loopNode->pnodeLval, byteCodeGenerator, funcInfo);
  8520. }
  8521. else
  8522. {
  8523. Symbol * sym = loopNode->pnodeLval->AsParseNodeVar()->sym;
  8524. sym->SetNeedDeclaration(false);
  8525. }
  8526. BeginEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8527. EmitAssignment(nullptr, loopNode->pnodeLval, loopNode->itemLocation, byteCodeGenerator, funcInfo);
  8528. // The StartStatement is already done in the caller of this function.
  8529. byteCodeGenerator->EndStatement(loopNode->pnodeLval);
  8530. funcInfo->ReleaseReference(loopNode->pnodeLval);
  8531. Emit(loopNode->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  8532. funcInfo->ReleaseLoc(loopNode->pnodeBody);
  8533. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8534. funcInfo->ReleaseTmpRegister(loopNode->itemLocation);
  8535. if (loopNode->emitLabels)
  8536. {
  8537. byteCodeGenerator->Writer()->MarkLabel(loopNode->continueLabel);
  8538. }
  8539. byteCodeGenerator->Writer()->Br(loopEntrance);
  8540. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  8541. if (loopNode->emitLabels)
  8542. {
  8543. byteCodeGenerator->Writer()->MarkLabel(loopNode->breakLabel);
  8544. }
  8545. }
  8546. void EmitForIn(ParseNodeForInOrForOf *loopNode,
  8547. Js::ByteCodeLabel loopEntrance,
  8548. Js::ByteCodeLabel continuePastLoop,
  8549. ByteCodeGenerator *byteCodeGenerator,
  8550. FuncInfo *funcInfo,
  8551. BOOL fReturnValue)
  8552. {
  8553. Assert(loopNode->nop == knopForIn);
  8554. Assert(loopNode->location == Js::Constants::NoRegister);
  8555. // Grab registers for the enumerator and for the current enumerated item.
  8556. // The enumerator register will be released after this call returns.
  8557. loopNode->itemLocation = funcInfo->AcquireTmpRegister();
  8558. uint forInLoopLevel = funcInfo->AcquireForInLoopLevel();
  8559. // get enumerator from the collection
  8560. byteCodeGenerator->Writer()->Reg1Unsigned1(Js::OpCode::InitForInEnumerator, loopNode->pnodeObj->location, forInLoopLevel);
  8561. // The StartStatement is already done in the caller of the current function, which is EmitForInOrForOf
  8562. byteCodeGenerator->EndStatement(loopNode);
  8563. // Need to increment loop count whether we are going into profile or not for HasLoop()
  8564. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8565. byteCodeGenerator->PushJumpCleanupForLoop(loopNode, loopId);
  8566. // The EndStatement will happen in the EmitForInOfLoopBody function
  8567. byteCodeGenerator->StartStatement(loopNode->pnodeLval);
  8568. // branch past loop when MoveAndGetNext returns nullptr
  8569. byteCodeGenerator->Writer()->BrReg1Unsigned1(Js::OpCode::BrOnEmpty, continuePastLoop, loopNode->itemLocation, forInLoopLevel);
  8570. EmitForInOfLoopBody(loopNode, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, fReturnValue);
  8571. byteCodeGenerator->PopJumpCleanup();
  8572. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8573. funcInfo->ReleaseForInLoopLevel(forInLoopLevel);
  8574. }
  8575. void EmitForInOrForOf(ParseNodeForInOrForOf *loopNode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue)
  8576. {
  8577. bool isForIn = (loopNode->nop == knopForIn);
  8578. bool isForAwaitOf = (loopNode->nop == knopForAwaitOf);
  8579. Assert(isForAwaitOf || isForIn || loopNode->nop == knopForOf);
  8580. BeginEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8581. byteCodeGenerator->StartStatement(loopNode);
  8582. if (!isForIn)
  8583. {
  8584. funcInfo->AcquireLoc(loopNode);
  8585. }
  8586. // Record the branch bytecode offset.
  8587. // This is used for "ignore exception" and "set next stmt" scenarios. See ProbeContainer::GetNextUserStatementOffsetForAdvance:
  8588. // If there is a branch recorded between current offset and next stmt offset, we'll use offset of the branch recorded,
  8589. // otherwise use offset of next stmt.
  8590. // The idea here is that when we bail out after ignore exception, we need to bail out to the beginning of the ForIn,
  8591. // but currently ForIn stmt starts at the condition part, which is needed for correct handling of break point on ForIn
  8592. // (break every time on the loop back edge) and correct display of current statement under debugger.
  8593. // See WinBlue 231880 for details.
  8594. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_All);
  8595. if (loopNode->pnodeBlock->HasBlockScopedContent())
  8596. {
  8597. byteCodeGenerator->Writer()->RecordForInOrOfCollectionScope();
  8598. }
  8599. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  8600. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  8601. if (loopNode->pnodeLval->nop == knopVarDecl)
  8602. {
  8603. EmitReference(loopNode->pnodeLval, byteCodeGenerator, funcInfo);
  8604. }
  8605. Emit(loopNode->pnodeObj, byteCodeGenerator, funcInfo, false); // evaluate collection expression
  8606. funcInfo->ReleaseLoc(loopNode->pnodeObj);
  8607. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8608. if (loopNode->pnodeBlock->scope != nullptr)
  8609. {
  8610. loopNode->pnodeBlock->scope->ForEachSymbol([](Symbol *sym) {
  8611. sym->SetIsTrackedForDebugger(false);
  8612. });
  8613. }
  8614. if (isForIn)
  8615. {
  8616. EmitForIn(loopNode, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, fReturnValue);
  8617. return;
  8618. }
  8619. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  8620. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrNeq_A, skipThrow, loopNode->pnodeObj->location, funcInfo->undefinedConstantRegister);
  8621. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ObjectCoercible));
  8622. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  8623. Js::RegSlot regException = Js::Constants::NoRegister;
  8624. Js::RegSlot regOffset = Js::Constants::NoRegister;
  8625. // These two temp variables track whether the return method of the source iterator should
  8626. // be called. One variable is used for catch block and one is used for finally block.
  8627. // Non-temps are used so that when jitting loop bodies, writes to these variables are not
  8628. // mistaken for dead stores.
  8629. Js::RegSlot shouldCallReturnFunctionLocation = loopNode->shouldCallReturnFunctionLocation;
  8630. Js::RegSlot shouldCallReturnFunctionLocationFinally = loopNode->shouldCallReturnFunctionLocationFinally;
  8631. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  8632. if (isCoroutine)
  8633. {
  8634. regException = funcInfo->AcquireTmpRegister();
  8635. regOffset = funcInfo->AcquireTmpRegister();
  8636. }
  8637. // Grab registers for the enumerator and for the current enumerated item.
  8638. // The enumerator register will be released after this call returns.
  8639. Js::RegSlot nextMethodReg = funcInfo->AcquireTmpRegister();
  8640. loopNode->itemLocation = funcInfo->AcquireTmpRegister();
  8641. // We want call profile information on the @@iterator call, so instead of adding a GetForOfIterator bytecode op
  8642. // to do all the following work in a helper do it explicitly in bytecode so that the @@iterator call is exposed
  8643. // to the profiler and JIT.
  8644. byteCodeGenerator->SetHasFinally(true);
  8645. byteCodeGenerator->SetHasTry(true);
  8646. byteCodeGenerator->TopFuncInfo()->byteCodeFunction->SetDontInline(true);
  8647. // do a ToObject on the collection
  8648. Js::RegSlot tmpObj = funcInfo->AcquireTmpRegister();
  8649. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Obj, tmpObj, loopNode->pnodeObj->location);
  8650. if (isForAwaitOf)
  8651. EmitGetAsyncIterator(loopNode->location, tmpObj, byteCodeGenerator, funcInfo);
  8652. else
  8653. EmitGetIterator(loopNode->location, tmpObj, byteCodeGenerator, funcInfo);
  8654. funcInfo->ReleaseTmpRegister(tmpObj);
  8655. EmitGetObjectMethod(
  8656. nextMethodReg,
  8657. loopNode->location,
  8658. Js::PropertyIds::next,
  8659. byteCodeGenerator,
  8660. funcInfo);
  8661. // The whole loop is surrounded with try..catch..finally - in order to capture the abrupt completion.
  8662. Js::ByteCodeLabel finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  8663. Js::ByteCodeLabel catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  8664. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  8665. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  8666. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  8667. if (isCoroutine)
  8668. {
  8669. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  8670. byteCodeGenerator->PushJumpCleanupForTry(
  8671. Js::OpCode::TryFinallyWithYield,
  8672. finallyLabel,
  8673. regException,
  8674. regOffset);
  8675. }
  8676. else
  8677. {
  8678. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  8679. byteCodeGenerator->PushJumpCleanupForTry(Js::OpCode::TryFinally, finallyLabel);
  8680. }
  8681. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  8682. byteCodeGenerator->PushJumpCleanupForTry(Js::OpCode::TryCatch, catchLabel);
  8683. byteCodeGenerator->EndStatement(loopNode);
  8684. // Need to increment loop count whether we are going into profile or not for HasLoop()
  8685. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8686. byteCodeGenerator->PushJumpCleanupForLoop(loopNode, loopId);
  8687. byteCodeGenerator->StartStatement(loopNode->pnodeLval);
  8688. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  8689. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  8690. // Call next on the iterator
  8691. EmitFunctionCall(
  8692. loopNode->itemLocation,
  8693. nextMethodReg,
  8694. loopNode->location,
  8695. byteCodeGenerator,
  8696. funcInfo);
  8697. // If this is a for-await-of then await the iterator next result
  8698. if (isForAwaitOf)
  8699. EmitAwait(loopNode->itemLocation, loopNode->itemLocation, byteCodeGenerator, funcInfo);
  8700. EmitThrowOnNotObject(loopNode->itemLocation, byteCodeGenerator);
  8701. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  8702. EmitGetObjectProperty(
  8703. doneLocation,
  8704. loopNode->itemLocation,
  8705. Js::PropertyIds::done,
  8706. byteCodeGenerator,
  8707. funcInfo);
  8708. // Branch past loop if the result's done property is truthy
  8709. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, continuePastLoop, doneLocation);
  8710. funcInfo->ReleaseTmpRegister(doneLocation);
  8711. // Otherwise put result's value property in itemLocation
  8712. EmitGetObjectProperty(
  8713. loopNode->itemLocation,
  8714. loopNode->itemLocation,
  8715. Js::PropertyIds::value,
  8716. byteCodeGenerator,
  8717. funcInfo);
  8718. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  8719. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  8720. EmitForInOfLoopBody(loopNode, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, fReturnValue);
  8721. byteCodeGenerator->PopJumpCleanup();
  8722. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8723. funcInfo->ReleaseTmpRegister(nextMethodReg);
  8724. EmitIteratorCatchAndFinally(catchLabel,
  8725. finallyLabel,
  8726. loopNode->location,
  8727. shouldCallReturnFunctionLocation,
  8728. shouldCallReturnFunctionLocationFinally,
  8729. regException,
  8730. regOffset,
  8731. byteCodeGenerator,
  8732. funcInfo,
  8733. isForAwaitOf);
  8734. }
  8735. void EmitArrayLiteral(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8736. {
  8737. funcInfo->AcquireLoc(pnode);
  8738. ParseNode *args = pnode->AsParseNodeUni()->pnode1;
  8739. if (args == nullptr)
  8740. {
  8741. byteCodeGenerator->Writer()->Reg1Unsigned1(
  8742. pnode->AsParseNodeArrLit()->hasMissingValues ? Js::OpCode::NewScArrayWithMissingValues : Js::OpCode::NewScArray,
  8743. pnode->location,
  8744. ByteCodeGenerator::DefaultArraySize);
  8745. }
  8746. else
  8747. {
  8748. SetNewArrayElements(pnode, pnode->location, byteCodeGenerator, funcInfo);
  8749. }
  8750. }
  8751. void ByteCodeGenerator::EmitJumpCleanup(ParseNode* target, FuncInfo* funcInfo)
  8752. {
  8753. for (JumpCleanupList::Iterator iter(this->jumpCleanupList); iter.Next();)
  8754. {
  8755. const JumpCleanupInfo& info = iter.Data();
  8756. if (info.loopNode)
  8757. {
  8758. if (info.loopNode == target)
  8759. break;
  8760. #if ENABLE_PROFILE_INFO
  8761. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(funcInfo->GetParsedFunctionBody()))
  8762. this->Writer()->Unsigned1(Js::OpCode::ProfiledLoopEnd, info.loopId);
  8763. #endif
  8764. }
  8765. else
  8766. {
  8767. Assert(
  8768. info.tryOp == Js::OpCode::TryCatch ||
  8769. info.tryOp == Js::OpCode::TryFinally ||
  8770. info.tryOp == Js::OpCode::TryFinallyWithYield ||
  8771. info.tryOp == Js::OpCode::ResumeCatch ||
  8772. info.tryOp == Js::OpCode::ResumeFinally);
  8773. // We insert OpCode::Leave when there is a 'return' inside try/catch/finally.
  8774. // This is for flow control and does not participate in identifying boundaries
  8775. // of try/catch blocks, thus we shouldn't call RecordCrossFrameEntryExitRecord
  8776. // here.
  8777. this->Writer()->Empty(Js::OpCode::Leave);
  8778. }
  8779. }
  8780. }
  8781. void EmitBinaryOpnds(ParseNode* pnode1, ParseNode* pnode2, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot computedPropertyLocation)
  8782. {
  8783. // If opnd2 can overwrite opnd1, make sure the value of opnd1 is stashed away.
  8784. if (MayHaveSideEffectOnNode(pnode1, pnode2, byteCodeGenerator))
  8785. {
  8786. SaveOpndValue(pnode1, funcInfo);
  8787. }
  8788. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  8789. if (pnode1->nop == knopComputedName && computedPropertyLocation != Js::Constants::NoRegister)
  8790. {
  8791. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Prop, computedPropertyLocation, pnode1->location);
  8792. }
  8793. Emit(pnode2, byteCodeGenerator, funcInfo, false, false, computedPropertyLocation);
  8794. }
  8795. void EmitBinaryReference(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fLoadLhs)
  8796. {
  8797. // Make sure that the RHS of an assignment doesn't kill the opnd's of the expression on the LHS.
  8798. switch (pnode1->nop)
  8799. {
  8800. case knopName:
  8801. if (fLoadLhs && MayHaveSideEffectOnNode(pnode1, pnode2, byteCodeGenerator))
  8802. {
  8803. // Given x op y, y may kill x, so stash x.
  8804. // Note that this only matters if we're loading x prior to the op.
  8805. SaveOpndValue(pnode1, funcInfo);
  8806. }
  8807. break;
  8808. case knopDot:
  8809. if (fLoadLhs)
  8810. {
  8811. // We're loading the value of the LHS before the RHS, so make sure the LHS gets a register first.
  8812. funcInfo->AcquireLoc(pnode1);
  8813. }
  8814. if (MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode1, pnode2, byteCodeGenerator))
  8815. {
  8816. // Given x.y op z, z may kill x, so stash x away.
  8817. SaveOpndValue(pnode1->AsParseNodeBin()->pnode1, funcInfo);
  8818. }
  8819. break;
  8820. case knopIndex:
  8821. if (fLoadLhs)
  8822. {
  8823. // We're loading the value of the LHS before the RHS, so make sure the LHS gets a register first.
  8824. funcInfo->AcquireLoc(pnode1);
  8825. }
  8826. if (MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode1, pnode2, byteCodeGenerator) ||
  8827. MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode1, pnode1->AsParseNodeBin()->pnode2, byteCodeGenerator))
  8828. {
  8829. // Given x[y] op z, y or z may kill x, so stash x away.
  8830. SaveOpndValue(pnode1->AsParseNodeBin()->pnode1, funcInfo);
  8831. }
  8832. if (MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode2, pnode2, byteCodeGenerator))
  8833. {
  8834. // Given x[y] op z, z may kill y, so stash y away.
  8835. // But make sure that x gets a register before y.
  8836. funcInfo->AcquireLoc(pnode1->AsParseNodeBin()->pnode1);
  8837. SaveOpndValue(pnode1->AsParseNodeBin()->pnode2, funcInfo);
  8838. }
  8839. break;
  8840. }
  8841. if (fLoadLhs)
  8842. {
  8843. // Emit code to load the value of the LHS.
  8844. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  8845. }
  8846. else
  8847. {
  8848. // Emit code to evaluate the LHS opnds, but don't load the LHS's value.
  8849. EmitReference(pnode1, byteCodeGenerator, funcInfo);
  8850. }
  8851. // Evaluate the RHS.
  8852. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  8853. }
  8854. void EmitUseBeforeDeclarationRuntimeError(ByteCodeGenerator * byteCodeGenerator, Js::RegSlot location)
  8855. {
  8856. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_UseBeforeDeclaration));
  8857. if (location != Js::Constants::NoRegister)
  8858. {
  8859. // Optionally load something into register in order to do not confuse IRBuilder. This value will never be used.
  8860. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, location);
  8861. }
  8862. }
  8863. void EmitUseBeforeDeclaration(Symbol *sym, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8864. {
  8865. // Don't emit static use-before-declaration error in a closure or dynamic scope case. We detect such cases with dynamic checks,
  8866. // if necessary.
  8867. if (sym != nullptr &&
  8868. !sym->GetIsModuleExportStorage() &&
  8869. sym->GetNeedDeclaration() &&
  8870. byteCodeGenerator->GetCurrentScope()->HasStaticPathToAncestor(sym->GetScope()) &&
  8871. sym->GetScope()->GetFunc() == funcInfo)
  8872. {
  8873. EmitUseBeforeDeclarationRuntimeError(byteCodeGenerator, Js::Constants::NoRegister);
  8874. }
  8875. }
  8876. void EmitBinary(Js::OpCode opcode, ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8877. {
  8878. byteCodeGenerator->StartStatement(pnode);
  8879. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  8880. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  8881. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  8882. funcInfo->AcquireLoc(pnode);
  8883. byteCodeGenerator->Writer()->Reg3(opcode,
  8884. pnode->location,
  8885. pnode->AsParseNodeBin()->pnode1->location,
  8886. pnode->AsParseNodeBin()->pnode2->location);
  8887. byteCodeGenerator->EndStatement(pnode);
  8888. }
  8889. bool CollectConcat(ParseNode *pnodeAdd, DListCounted<ParseNode *, ArenaAllocator>& concatOpnds, ArenaAllocator *arenaAllocator
  8890. #ifdef ENABLE_TEST_HOOKS
  8891. , bool Force32BitByteCode = false
  8892. #endif
  8893. )
  8894. {
  8895. Assert(pnodeAdd->nop == knopAdd);
  8896. Assert(pnodeAdd->CanFlattenConcatExpr());
  8897. bool doConcatString = false;
  8898. DList<ParseNode*, ArenaAllocator> pnodeStack(arenaAllocator);
  8899. pnodeStack.Prepend(pnodeAdd->AsParseNodeBin()->pnode2);
  8900. ParseNode * pnode = pnodeAdd->AsParseNodeBin()->pnode1;
  8901. while (true)
  8902. {
  8903. if (!pnode->CanFlattenConcatExpr())
  8904. {
  8905. concatOpnds.Append(pnode);
  8906. }
  8907. else if (pnode->nop == knopStr)
  8908. {
  8909. concatOpnds.Append(pnode);
  8910. // Detect if there are any string larger then the append size limit.
  8911. // If there are, we can do concat; otherwise, still use add so we will not lose the AddLeftDead opportunities.
  8912. #ifdef ENABLE_TEST_HOOKS
  8913. if (Force32BitByteCode)
  8914. {
  8915. doConcatString = doConcatString || (pnode->AsParseNodeStr()->pid->Cch() > 4);
  8916. }
  8917. else
  8918. {
  8919. doConcatString = doConcatString || !Js::CompoundString::ShouldAppendChars(pnode->AsParseNodeStr()->pid->Cch());
  8920. }
  8921. #else
  8922. doConcatString = doConcatString || !Js::CompoundString::ShouldAppendChars(pnode->AsParseNodeStr()->pid->Cch());
  8923. #endif
  8924. }
  8925. else
  8926. {
  8927. Assert(pnode->nop == knopAdd);
  8928. pnodeStack.Prepend(pnode->AsParseNodeBin()->pnode2);
  8929. pnode = pnode->AsParseNodeBin()->pnode1;
  8930. continue;
  8931. }
  8932. if (pnodeStack.Empty())
  8933. {
  8934. break;
  8935. }
  8936. pnode = pnodeStack.Head();
  8937. pnodeStack.RemoveHead();
  8938. }
  8939. return doConcatString;
  8940. }
  8941. void EmitConcat3(ParseNode *pnode, ParseNode *pnode1, ParseNode *pnode2, ParseNode *pnode3, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8942. {
  8943. byteCodeGenerator->StartStatement(pnode);
  8944. if (MayHaveSideEffectOnNode(pnode1, pnode2, byteCodeGenerator) || MayHaveSideEffectOnNode(pnode1, pnode3, byteCodeGenerator))
  8945. {
  8946. SaveOpndValue(pnode1, funcInfo);
  8947. }
  8948. if (MayHaveSideEffectOnNode(pnode2, pnode3, byteCodeGenerator))
  8949. {
  8950. SaveOpndValue(pnode2, funcInfo);
  8951. }
  8952. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  8953. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  8954. Emit(pnode3, byteCodeGenerator, funcInfo, false);
  8955. funcInfo->ReleaseLoc(pnode3);
  8956. funcInfo->ReleaseLoc(pnode2);
  8957. funcInfo->ReleaseLoc(pnode1);
  8958. funcInfo->AcquireLoc(pnode);
  8959. byteCodeGenerator->Writer()->Reg4(Js::OpCode::Concat3,
  8960. pnode->location,
  8961. pnode1->location,
  8962. pnode2->location,
  8963. pnode3->location);
  8964. byteCodeGenerator->EndStatement(pnode);
  8965. }
  8966. void EmitNewConcatStrMulti(ParseNode *pnode, uint8 count, ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8967. {
  8968. EmitBinaryOpnds(pnode1, pnode2, byteCodeGenerator, funcInfo);
  8969. funcInfo->ReleaseLoc(pnode2);
  8970. funcInfo->ReleaseLoc(pnode1);
  8971. funcInfo->AcquireLoc(pnode);
  8972. byteCodeGenerator->Writer()->Reg3B1(Js::OpCode::NewConcatStrMulti,
  8973. pnode->location,
  8974. pnode1->location,
  8975. pnode2->location,
  8976. count);
  8977. }
  8978. void EmitAdd(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8979. {
  8980. Assert(pnode->nop == knopAdd);
  8981. if (pnode->CanFlattenConcatExpr())
  8982. {
  8983. // We should only have a string concat if the feature is on.
  8984. Assert(!PHASE_OFF1(Js::ByteCodeConcatExprOptPhase));
  8985. DListCounted<ParseNode*, ArenaAllocator> concatOpnds(byteCodeGenerator->GetAllocator());
  8986. #ifdef ENABLE_TEST_HOOKS
  8987. bool doConcatString = CollectConcat(pnode, concatOpnds, byteCodeGenerator->GetAllocator(),
  8988. byteCodeGenerator->GetScriptContext()->GetConfig()->Force32BitByteCode());
  8989. #else
  8990. bool doConcatString = CollectConcat(pnode, concatOpnds, byteCodeGenerator->GetAllocator());
  8991. #endif
  8992. if (doConcatString)
  8993. {
  8994. uint concatCount = concatOpnds.Count();
  8995. Assert(concatCount >= 2);
  8996. // Don't do concatN if the number is too high
  8997. // CONSIDER: although we could have done multiple ConcatNs
  8998. if (concatCount > 2 && concatCount <= UINT8_MAX)
  8999. {
  9000. #if DBG
  9001. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  9002. #endif
  9003. ParseNode * pnode1 = concatOpnds.Head();
  9004. concatOpnds.RemoveHead();
  9005. ParseNode * pnode2 = concatOpnds.Head();
  9006. concatOpnds.RemoveHead();
  9007. if (concatCount == 3)
  9008. {
  9009. OUTPUT_TRACE_DEBUGONLY(Js::ByteCodeConcatExprOptPhase, _u("%s(%s) offset:#%d : Concat3\n"),
  9010. funcInfo->GetParsedFunctionBody()->GetDisplayName(),
  9011. funcInfo->GetParsedFunctionBody()->GetDebugNumberSet(debugStringBuffer),
  9012. byteCodeGenerator->Writer()->ByteCodeDataSize());
  9013. EmitConcat3(pnode, pnode1, pnode2, concatOpnds.Head(), byteCodeGenerator, funcInfo);
  9014. return;
  9015. }
  9016. OUTPUT_TRACE_DEBUGONLY(Js::ByteCodeConcatExprOptPhase, _u("%s(%s) offset:#%d: ConcatMulti %d\n"),
  9017. funcInfo->GetParsedFunctionBody()->GetDisplayName(),
  9018. funcInfo->GetParsedFunctionBody()->GetDebugNumberSet(debugStringBuffer),
  9019. byteCodeGenerator->Writer()->ByteCodeDataSize(), concatCount);
  9020. byteCodeGenerator->StartStatement(pnode);
  9021. funcInfo->AcquireLoc(pnode);
  9022. // CONSIDER: this may cause the backend not able CSE repeating pattern within the concat.
  9023. EmitNewConcatStrMulti(pnode, (uint8)concatCount, pnode1, pnode2, byteCodeGenerator, funcInfo);
  9024. uint i = 2;
  9025. do
  9026. {
  9027. ParseNode * currNode = concatOpnds.Head();
  9028. concatOpnds.RemoveHead();
  9029. ParseNode * currNode2 = concatOpnds.Head();
  9030. concatOpnds.RemoveHead();
  9031. EmitBinaryOpnds(currNode, currNode2, byteCodeGenerator, funcInfo);
  9032. funcInfo->ReleaseLoc(currNode2);
  9033. funcInfo->ReleaseLoc(currNode);
  9034. byteCodeGenerator->Writer()->Reg3B1(
  9035. Js::OpCode::SetConcatStrMultiItem2, pnode->location, currNode->location, currNode2->location, (uint8)i);
  9036. i += 2;
  9037. } while (concatOpnds.Count() > 1);
  9038. if (!concatOpnds.Empty())
  9039. {
  9040. ParseNode * currNode = concatOpnds.Head();
  9041. Emit(currNode, byteCodeGenerator, funcInfo, false);
  9042. funcInfo->ReleaseLoc(currNode);
  9043. byteCodeGenerator->Writer()->Reg2B1(
  9044. Js::OpCode::SetConcatStrMultiItem, pnode->location, currNode->location, (uint8)i);
  9045. i++;
  9046. }
  9047. Assert(concatCount == i);
  9048. byteCodeGenerator->EndStatement(pnode);
  9049. return;
  9050. }
  9051. }
  9052. // Since we collected all the node already, let's just emit them instead of doing it recursively.
  9053. byteCodeGenerator->StartStatement(pnode);
  9054. ParseNode * currNode = concatOpnds.Head();
  9055. concatOpnds.RemoveHead();
  9056. ParseNode * currNode2 = concatOpnds.Head();
  9057. concatOpnds.RemoveHead();
  9058. EmitBinaryOpnds(currNode, currNode2, byteCodeGenerator, funcInfo);
  9059. funcInfo->ReleaseLoc(currNode2);
  9060. funcInfo->ReleaseLoc(currNode);
  9061. Js::RegSlot dstReg = funcInfo->AcquireLoc(pnode);
  9062. byteCodeGenerator->Writer()->Reg3(
  9063. Js::OpCode::Add_A, dstReg, currNode->location, currNode2->location);
  9064. while (!concatOpnds.Empty())
  9065. {
  9066. currNode = concatOpnds.Head();
  9067. concatOpnds.RemoveHead();
  9068. Emit(currNode, byteCodeGenerator, funcInfo, false);
  9069. funcInfo->ReleaseLoc(currNode);
  9070. byteCodeGenerator->Writer()->Reg3(
  9071. Js::OpCode::Add_A, dstReg, dstReg, currNode->location);
  9072. }
  9073. byteCodeGenerator->EndStatement(pnode);
  9074. }
  9075. else
  9076. {
  9077. EmitBinary(Js::OpCode::Add_A, pnode, byteCodeGenerator, funcInfo);
  9078. }
  9079. }
  9080. void ByteCodeGenerator::EmitLeaveOpCodesBeforeYield()
  9081. {
  9082. for (JumpCleanupList::Iterator iter(this->jumpCleanupList); iter.Next();)
  9083. {
  9084. const JumpCleanupInfo& info = iter.Data();
  9085. switch (info.tryOp)
  9086. {
  9087. case Js::OpCode::TryFinallyWithYield:
  9088. this->Writer()->Empty(Js::OpCode::LeaveNull);
  9089. break;
  9090. case Js::OpCode::TryCatch:
  9091. case Js::OpCode::ResumeFinally:
  9092. case Js::OpCode::ResumeCatch:
  9093. this->Writer()->Empty(Js::OpCode::Leave);
  9094. break;
  9095. case Js::OpCode::Nop:
  9096. break;
  9097. default:
  9098. AssertMsg(false, "Unexpected OpCode in jumpCleanupList");
  9099. break;
  9100. }
  9101. }
  9102. }
  9103. void ByteCodeGenerator::EmitTryBlockHeadersAfterYield()
  9104. {
  9105. for (JumpCleanupList::Iterator iter(this->jumpCleanupList); iter.Prev();)
  9106. {
  9107. const JumpCleanupInfo& info = iter.Data();
  9108. switch (info.tryOp)
  9109. {
  9110. case Js::OpCode::TryCatch:
  9111. this->Writer()->Br(info.tryOp, info.label);
  9112. break;
  9113. case Js::OpCode::TryFinallyWithYield:
  9114. case Js::OpCode::ResumeFinally:
  9115. this->Writer()->BrReg2(info.tryOp, info.label, info.regSlot1, info.regSlot2);
  9116. break;
  9117. case Js::OpCode::ResumeCatch:
  9118. this->Writer()->Empty(info.tryOp);
  9119. break;
  9120. case Js::OpCode::Nop:
  9121. break;
  9122. default:
  9123. AssertMsg(false, "Unexpected OpCode in jumpCleanupList");
  9124. break;
  9125. }
  9126. }
  9127. }
  9128. void EmitYieldAndResume(
  9129. Js::RegSlot resumeValueReg,
  9130. Js::RegSlot inputReg,
  9131. Js::ByteCodeLabel resumeNormalLabel,
  9132. Js::ByteCodeLabel resumeThrowLabel,
  9133. ByteCodeGenerator* byteCodeGenerator,
  9134. FuncInfo* funcInfo)
  9135. {
  9136. // If `resultThrowLabel` is a valid label, then the instruction
  9137. // sequence following this call must handle the return yield resume
  9138. // case. Otherwise, the instruction sequence following this call
  9139. // must handle both the throw and return cases.
  9140. auto* writer = byteCodeGenerator->Writer();
  9141. // If in a loop mark it as containing Yield and hence not eligible for Jit loop body
  9142. writer->SetCurrentLoopHasYield();
  9143. if (inputReg != funcInfo->yieldRegister)
  9144. writer->Reg2(Js::OpCode::Ld_A, funcInfo->yieldRegister, inputReg);
  9145. // Yield the result. On resume, the resume yield object will be in yieldRegister
  9146. byteCodeGenerator->EmitLeaveOpCodesBeforeYield();
  9147. writer->Reg2(Js::OpCode::Yield, funcInfo->yieldRegister, funcInfo->yieldRegister);
  9148. byteCodeGenerator->EmitTryBlockHeadersAfterYield();
  9149. Js::RegSlot resumeKindReg = funcInfo->AcquireTmpRegister();
  9150. // Get the "kind" property of the resume object
  9151. EmitGetObjectProperty(
  9152. resumeKindReg,
  9153. funcInfo->yieldRegister,
  9154. Js::PropertyIds::kind,
  9155. byteCodeGenerator,
  9156. funcInfo);
  9157. // Get the "value" property of the resume object
  9158. EmitGetObjectProperty(
  9159. resumeValueReg,
  9160. funcInfo->yieldRegister,
  9161. Js::PropertyIds::value,
  9162. byteCodeGenerator,
  9163. funcInfo);
  9164. Js::RegSlot normalConst = funcInfo->constantToRegister.Lookup(
  9165. (uint)Js::ResumeYieldKind::Normal,
  9166. Js::Constants::NoRegister);
  9167. Assert(normalConst != Js::Constants::NoRegister);
  9168. // Branch to normal resume if kind is Normal
  9169. writer->BrReg2(Js::OpCode::BrSrEq_A, resumeNormalLabel, resumeKindReg, normalConst);
  9170. if (resumeThrowLabel != Js::Constants::NoByteCodeLabel)
  9171. {
  9172. Js::RegSlot throwConst = funcInfo->constantToRegister.Lookup(
  9173. (uint)Js::ResumeYieldKind::Throw,
  9174. Js::Constants::NoRegister);
  9175. Assert(throwConst != Js::Constants::NoRegister);
  9176. // Branch to throw if kind is Throw
  9177. writer->BrReg2(Js::OpCode::BrSrEq_A, resumeThrowLabel, resumeKindReg, throwConst);
  9178. }
  9179. funcInfo->ReleaseTmpRegister(resumeKindReg);
  9180. }
  9181. void EmitReturnFromYield(
  9182. Js::RegSlot resultReg,
  9183. ByteCodeGenerator* byteCodeGenerator,
  9184. FuncInfo* funcInfo)
  9185. {
  9186. auto* writer = byteCodeGenerator->Writer();
  9187. writer->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, resultReg);
  9188. byteCodeGenerator->EmitJumpCleanup(nullptr, funcInfo);
  9189. writer->Br(funcInfo->singleExit);
  9190. }
  9191. void EmitStartupYield(ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  9192. {
  9193. // Generators are "paused" after evaluating the parameter list. A synthetic
  9194. // yield is inserted at the beginning of the function for this purpose. It
  9195. // has the following special properties: it can only be resumed with a "normal"
  9196. // completion (the other types are handled in the generator logic), the
  9197. // resume value is not observable to user code, and it cannot be contained
  9198. // within a try scope.
  9199. Assert(!byteCodeGenerator->HasJumpCleanup());
  9200. auto* writer = byteCodeGenerator->Writer();
  9201. writer->Reg1(Js::OpCode::LdUndef, funcInfo->yieldRegister);
  9202. writer->Reg2(Js::OpCode::Yield, funcInfo->yieldRegister, funcInfo->yieldRegister);
  9203. }
  9204. void EmitAwait(
  9205. Js::RegSlot resultReg,
  9206. Js::RegSlot inputReg,
  9207. ByteCodeGenerator* byteCodeGenerator,
  9208. FuncInfo* funcInfo)
  9209. {
  9210. auto writer = byteCodeGenerator->Writer();
  9211. writer->PatchableProperty(
  9212. Js::OpCode::StFld,
  9213. inputReg,
  9214. funcInfo->awaitRegister,
  9215. funcInfo->FindOrAddInlineCacheId(funcInfo->awaitRegister, Js::PropertyIds::value, false, true));
  9216. Js::ByteCodeLabel resumeNormal = writer->DefineLabel();
  9217. EmitYieldAndResume(
  9218. resultReg,
  9219. funcInfo->awaitRegister,
  9220. resumeNormal,
  9221. Js::Constants::NoByteCodeLabel,
  9222. byteCodeGenerator,
  9223. funcInfo);
  9224. // Throw case: throw the resume value
  9225. writer->Reg1(Js::OpCode::Throw, resultReg);
  9226. // Normal case: continue (value is already in result register)
  9227. writer->MarkLabel(resumeNormal);
  9228. }
  9229. void EmitCreateYieldResult(
  9230. Js::RegSlot resultReg,
  9231. Js::RegSlot inputReg,
  9232. ByteCodeGenerator* byteCodeGenerator,
  9233. FuncInfo* funcInfo)
  9234. {
  9235. Assert(resultReg != inputReg);
  9236. byteCodeGenerator->Writer()->Reg1(Js::OpCode::NewScObjectSimple, resultReg);
  9237. byteCodeGenerator->Writer()->PatchableProperty(
  9238. Js::OpCode::StFld,
  9239. inputReg,
  9240. resultReg,
  9241. funcInfo->FindOrAddInlineCacheId(resultReg, Js::PropertyIds::value, false, true));
  9242. byteCodeGenerator->Writer()->PatchableProperty(
  9243. Js::OpCode::StFld,
  9244. funcInfo->falseConstantRegister,
  9245. resultReg,
  9246. funcInfo->FindOrAddInlineCacheId(resultReg, Js::PropertyIds::done, false, true));
  9247. }
  9248. void EmitYield(
  9249. Js::RegSlot resultReg,
  9250. Js::RegSlot inputReg,
  9251. ByteCodeGenerator* byteCodeGenerator,
  9252. FuncInfo* funcInfo)
  9253. {
  9254. auto* writer = byteCodeGenerator->Writer();
  9255. Js::RegSlot yieldReg = funcInfo->yieldRegister;
  9256. EmitCreateYieldResult(yieldReg, inputReg, byteCodeGenerator, funcInfo);
  9257. Js::ByteCodeLabel resumeNormal = writer->DefineLabel();
  9258. Js::ByteCodeLabel resumeThrow = writer->DefineLabel();
  9259. EmitYieldAndResume(
  9260. resultReg,
  9261. yieldReg,
  9262. resumeNormal,
  9263. resumeThrow,
  9264. byteCodeGenerator,
  9265. funcInfo);
  9266. // Return case: set the return register value and branch to function exit
  9267. EmitReturnFromYield(resultReg, byteCodeGenerator, funcInfo);
  9268. // Throw case: throw the resume value
  9269. writer->MarkLabel(resumeThrow);
  9270. writer->Reg1(Js::OpCode::Throw, resultReg);
  9271. // Normal case: continue (value is already in result register)
  9272. writer->MarkLabel(resumeNormal);
  9273. }
  9274. void EmitYieldStar(
  9275. ParseNodeUni* yieldStarNode,
  9276. ByteCodeGenerator* byteCodeGenerator,
  9277. FuncInfo* funcInfo)
  9278. {
  9279. bool isAsync = funcInfo->IsAsyncGenerator();
  9280. auto* writer = byteCodeGenerator->Writer();
  9281. Js::ByteCodeLabel loopEntrance = writer->DefineLabel();
  9282. Js::ByteCodeLabel continueLoop = writer->DefineLabel();
  9283. Js::ByteCodeLabel continuePastLoop = writer->DefineLabel();
  9284. Js::ByteCodeLabel finishReturn = writer->DefineLabel();
  9285. Js::ByteCodeLabel finishNormal = writer->DefineLabel();
  9286. Js::RegSlot yieldStarReg = yieldStarNode->location;
  9287. // Initialize shouldReturn to false; this flag is used to indicate
  9288. // whether we should return or continue after the loop is complete
  9289. Js::RegSlot shouldReturnReg = funcInfo->AcquireTmpRegister();
  9290. writer->Reg1(Js::OpCode::LdFalse, shouldReturnReg);
  9291. // Evaluate operand and get the inner iterator
  9292. Js::RegSlot iteratorReg = funcInfo->AcquireTmpRegister();
  9293. ParseNode* operand = yieldStarNode->pnode1;
  9294. Emit(operand, byteCodeGenerator, funcInfo, false);
  9295. if (isAsync)
  9296. EmitGetAsyncIterator(iteratorReg, operand->location, byteCodeGenerator, funcInfo);
  9297. else
  9298. EmitGetIterator(iteratorReg, operand->location, byteCodeGenerator, funcInfo);
  9299. funcInfo->ReleaseLoc(operand);
  9300. // Load next method
  9301. Js::RegSlot nextMethodReg = funcInfo->AcquireTmpRegister();
  9302. EmitGetObjectMethod(
  9303. nextMethodReg,
  9304. iteratorReg,
  9305. Js::PropertyIds::next,
  9306. byteCodeGenerator,
  9307. funcInfo);
  9308. // Call the next method of iterator to obtain the first result
  9309. EmitFunctionCall(
  9310. yieldStarReg,
  9311. nextMethodReg,
  9312. iteratorReg,
  9313. funcInfo->undefinedConstantRegister,
  9314. byteCodeGenerator,
  9315. funcInfo);
  9316. // Begin loop
  9317. uint loopId = writer->EnterLoop(loopEntrance);
  9318. // If this is an async generator await the yielded value
  9319. if (isAsync)
  9320. EmitAwait(yieldStarReg, yieldStarReg, byteCodeGenerator, funcInfo);
  9321. EmitThrowOnNotObject(yieldStarReg, byteCodeGenerator);
  9322. // Get the iterator result's done property
  9323. Js::RegSlot doneReg = funcInfo->AcquireTmpRegister();
  9324. EmitGetObjectProperty(
  9325. doneReg,
  9326. yieldStarReg,
  9327. Js::PropertyIds::done,
  9328. byteCodeGenerator,
  9329. funcInfo);
  9330. // Break out of loop if the done property is truthy
  9331. writer->BrReg1(Js::OpCode::BrTrue_A, continuePastLoop, doneReg);
  9332. funcInfo->ReleaseTmpRegister(doneReg);
  9333. // Reset shouldReturn to false
  9334. writer->Reg1(Js::OpCode::LdFalse_ReuseLoc, shouldReturnReg);
  9335. Js::ByteCodeLabel resumeNormal = writer->DefineLabel();
  9336. Js::ByteCodeLabel resumeThrow = writer->DefineLabel();
  9337. Js::RegSlot resumeValueReg = funcInfo->AcquireTmpRegister();
  9338. if (isAsync)
  9339. {
  9340. // For async generators, extract the value property and wrap it in a
  9341. // new result object, so that exceptions thrown when getting the value
  9342. // property are handled appropriately
  9343. Js::RegSlot valueReg = funcInfo->AcquireTmpRegister();
  9344. EmitGetObjectProperty(
  9345. valueReg,
  9346. yieldStarReg,
  9347. Js::PropertyIds::value,
  9348. byteCodeGenerator,
  9349. funcInfo);
  9350. EmitCreateYieldResult(yieldStarReg, valueReg, byteCodeGenerator, funcInfo);
  9351. funcInfo->ReleaseTmpRegister(valueReg);
  9352. }
  9353. // Yield the next result to the caller
  9354. EmitYieldAndResume(
  9355. resumeValueReg,
  9356. yieldStarReg,
  9357. resumeNormal,
  9358. resumeThrow,
  9359. byteCodeGenerator,
  9360. funcInfo);
  9361. // Return case: set shouldReturn to true and attempt to call return
  9362. writer->Reg1(Js::OpCode::LdTrue_ReuseLoc, shouldReturnReg);
  9363. Js::RegSlot returnMethodReg = funcInfo->AcquireTmpRegister();
  9364. // Load return method
  9365. Js::ByteCodeLabel noReturnMethod = writer->DefineLabel();
  9366. EmitGetOptionalObjectMethod(
  9367. returnMethodReg,
  9368. iteratorReg,
  9369. Js::PropertyIds::return_,
  9370. noReturnMethod,
  9371. byteCodeGenerator,
  9372. funcInfo);
  9373. // The iterator has a return method: call method and loop
  9374. EmitFunctionCall(
  9375. yieldStarReg,
  9376. returnMethodReg,
  9377. iteratorReg,
  9378. resumeValueReg,
  9379. byteCodeGenerator,
  9380. funcInfo);
  9381. funcInfo->ReleaseTmpRegister(returnMethodReg);
  9382. writer->Br(continueLoop);
  9383. // The iterator does not have a return method: exit loop
  9384. writer->MarkLabel(noReturnMethod);
  9385. if (isAsync)
  9386. {
  9387. Js::RegSlot awaitValue = funcInfo->AcquireTmpRegister();
  9388. writer->Reg2(Js::OpCode::Ld_A, awaitValue, resumeValueReg);
  9389. EmitAwait(awaitValue, awaitValue, byteCodeGenerator, funcInfo);
  9390. writer->Reg2(Js::OpCode::Ld_A_ReuseLoc, yieldStarReg, awaitValue);
  9391. funcInfo->ReleaseTmpRegister(awaitValue);
  9392. }
  9393. else
  9394. writer->Reg2(Js::OpCode::Ld_A_ReuseLoc, yieldStarReg, resumeValueReg);
  9395. writer->Br(finishReturn);
  9396. // Throw case: attempt to call throw
  9397. writer->MarkLabel(resumeThrow);
  9398. Js::RegSlot throwMethodReg = funcInfo->AcquireTmpRegister();
  9399. Js::ByteCodeLabel noThrowMethod = writer->DefineLabel();
  9400. // Load throw method
  9401. EmitGetOptionalObjectMethod(
  9402. throwMethodReg,
  9403. iteratorReg,
  9404. Js::PropertyIds::throw_,
  9405. noThrowMethod,
  9406. byteCodeGenerator,
  9407. funcInfo);
  9408. // Iterator has throw method: call method and loop
  9409. EmitFunctionCall(
  9410. yieldStarReg,
  9411. throwMethodReg,
  9412. iteratorReg,
  9413. resumeValueReg,
  9414. byteCodeGenerator,
  9415. funcInfo);
  9416. funcInfo->ReleaseTmpRegister(throwMethodReg);
  9417. writer->Br(continueLoop);
  9418. // Iterator does not have a throw method; close the iterator and throw a TypeError
  9419. writer->MarkLabel(noThrowMethod);
  9420. EmitIteratorClose(iteratorReg, byteCodeGenerator, funcInfo, isAsync);
  9421. byteCodeGenerator->Writer()->W1(
  9422. Js::OpCode::RuntimeTypeError,
  9423. SCODE_CODE(JSERR_YieldStarThrowMissing));
  9424. // Normal case: call next method of iterator
  9425. writer->MarkLabel(resumeNormal);
  9426. EmitFunctionCall(
  9427. yieldStarReg,
  9428. nextMethodReg,
  9429. iteratorReg,
  9430. resumeValueReg,
  9431. byteCodeGenerator,
  9432. funcInfo);
  9433. funcInfo->ReleaseTmpRegister(resumeValueReg);
  9434. funcInfo->ReleaseTmpRegister(nextMethodReg);
  9435. funcInfo->ReleaseTmpRegister(iteratorReg);
  9436. // Loop end
  9437. writer->MarkLabel(continueLoop);
  9438. writer->Br(loopEntrance);
  9439. writer->MarkLabel(continuePastLoop);
  9440. writer->ExitLoop(loopId);
  9441. // Load the iterator result value into place
  9442. EmitGetObjectProperty(
  9443. yieldStarReg,
  9444. yieldStarReg,
  9445. Js::PropertyIds::value,
  9446. byteCodeGenerator,
  9447. funcInfo);
  9448. writer->BrReg1(Js::OpCode::BrFalse_A, finishNormal, shouldReturnReg);
  9449. funcInfo->ReleaseTmpRegister(shouldReturnReg);
  9450. // Return case: return the value from the generator
  9451. writer->MarkLabel(finishReturn);
  9452. EmitReturnFromYield(yieldStarReg, byteCodeGenerator, funcInfo);
  9453. // Normal case
  9454. writer->MarkLabel(finishNormal);
  9455. }
  9456. void EmitClass(ParseNodeClass * pnodeClass, ByteCodeGenerator * byteCodeGenerator, FuncInfo * funcInfo)
  9457. {
  9458. funcInfo->AcquireLoc(pnodeClass);
  9459. Assert(pnodeClass->pnodeConstructor);
  9460. pnodeClass->pnodeConstructor->location = pnodeClass->location;
  9461. Js::RegSlot protoLoc = funcInfo->AcquireTmpRegister();
  9462. BeginEmitBlock(pnodeClass->pnodeBlock, byteCodeGenerator, funcInfo);
  9463. Js::RegSlot frameDisplayLoc = funcInfo->frameDisplayRegister != Js::Constants::NoRegister ? funcInfo->frameDisplayRegister : funcInfo->GetEnvRegister();
  9464. Js::RegSlot tmpFrameDisplayLoc = funcInfo->AcquireTmpRegister();
  9465. frameDisplayLoc = byteCodeGenerator->PrependLocalScopes(frameDisplayLoc, tmpFrameDisplayLoc, funcInfo);
  9466. if (frameDisplayLoc != tmpFrameDisplayLoc)
  9467. {
  9468. funcInfo->ReleaseTmpRegister(tmpFrameDisplayLoc);
  9469. }
  9470. // Extends
  9471. if (pnodeClass->pnodeExtends)
  9472. {
  9473. Emit(pnodeClass->pnodeExtends, byteCodeGenerator, funcInfo, false);
  9474. byteCodeGenerator->StartStatement(pnodeClass->pnodeExtends);
  9475. Js::RegSlot ctorParentLoc = funcInfo->IsTmpReg(pnodeClass->pnodeExtends->location) ? pnodeClass->pnodeExtends->location : funcInfo->AcquireTmpRegister();
  9476. Js::RegSlot protoParentLoc = funcInfo->AcquireTmpRegister();
  9477. if (pnodeClass->pnodeExtends->location != ctorParentLoc)
  9478. {
  9479. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A_ReuseLoc, ctorParentLoc, pnodeClass->pnodeExtends->location);
  9480. }
  9481. Js::ByteCodeLabel needProto = byteCodeGenerator->Writer()->DefineLabel();
  9482. Js::ByteCodeLabel haveConstructor = byteCodeGenerator->Writer()->DefineLabel();
  9483. Js::ByteCodeLabel labelParentsFound = byteCodeGenerator->Writer()->DefineLabel();
  9484. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnNotNullObj_A, needProto, ctorParentLoc);
  9485. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdC_A_Null, protoParentLoc);
  9486. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdBaseFncProto, ctorParentLoc);
  9487. byteCodeGenerator->Writer()->Br(labelParentsFound);
  9488. byteCodeGenerator->Writer()->MarkLabel(needProto);
  9489. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnConstructor_A, haveConstructor, ctorParentLoc);
  9490. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ErrorOnNew));
  9491. byteCodeGenerator->Writer()->MarkLabel(haveConstructor);
  9492. uint cacheId = funcInfo->FindOrAddInlineCacheId(ctorParentLoc, Js::PropertyIds::prototype, false, false);
  9493. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld_ReuseLoc, protoParentLoc, ctorParentLoc, cacheId);
  9494. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObjectOrNull_A, labelParentsFound, protoParentLoc);
  9495. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_InvalidPrototype));
  9496. byteCodeGenerator->Writer()->MarkLabel(labelParentsFound);
  9497. if (frameDisplayLoc == funcInfo->frameDisplayRegister || frameDisplayLoc == funcInfo->GetEnvRegister())
  9498. {
  9499. byteCodeGenerator->Writer()->Reg4U(Js::OpCode::InitClass, pnodeClass->location, protoLoc, ctorParentLoc, protoParentLoc, pnodeClass->pnodeConstructor->nestedIndex);
  9500. }
  9501. else
  9502. {
  9503. byteCodeGenerator->Writer()->Reg5U(Js::OpCode::InitInnerClass, pnodeClass->location, protoLoc, ctorParentLoc, protoParentLoc, frameDisplayLoc, pnodeClass->pnodeConstructor->nestedIndex);
  9504. }
  9505. funcInfo->ReleaseTmpRegister(protoParentLoc);
  9506. funcInfo->ReleaseTmpRegister(ctorParentLoc);
  9507. byteCodeGenerator->EndStatement(pnodeClass->pnodeExtends);
  9508. }
  9509. else
  9510. {
  9511. if (frameDisplayLoc == funcInfo->frameDisplayRegister || frameDisplayLoc == funcInfo->GetEnvRegister())
  9512. {
  9513. byteCodeGenerator->Writer()->Reg2U(Js::OpCode::InitBaseClass, pnodeClass->location, protoLoc, pnodeClass->pnodeConstructor->nestedIndex);
  9514. }
  9515. else
  9516. {
  9517. byteCodeGenerator->Writer()->Reg3U(Js::OpCode::InitInnerBaseClass, pnodeClass->location, protoLoc, frameDisplayLoc, pnodeClass->pnodeConstructor->nestedIndex);
  9518. }
  9519. }
  9520. funcInfo->ReleaseTmpRegister(frameDisplayLoc);
  9521. // Methods
  9522. bool isObjectEmpty = true;
  9523. ParseNode * pnodeMembers = pnodeClass->pnodeMembers;
  9524. ParseNode * pnodeMember;
  9525. ParseNodeFnc * pnodeMemberFnc;
  9526. if (pnodeMembers != nullptr)
  9527. {
  9528. while (pnodeMembers->nop == knopList)
  9529. {
  9530. pnodeMember = pnodeMembers->AsParseNodeBin()->pnode1;
  9531. pnodeMemberFnc = pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc();
  9532. EmitMemberNode(pnodeMember, pnodeMemberFnc->IsStaticMember() ? pnodeClass->location : protoLoc, byteCodeGenerator, funcInfo, pnodeClass, /*useStore*/ false, &isObjectEmpty);
  9533. pnodeMembers = pnodeMembers->AsParseNodeBin()->pnode2;
  9534. }
  9535. pnodeMemberFnc = pnodeMembers->AsParseNodeBin()->pnode2->AsParseNodeFnc();
  9536. EmitMemberNode(pnodeMembers, pnodeMemberFnc->IsStaticMember() ? pnodeClass->location : protoLoc, byteCodeGenerator, funcInfo, pnodeClass, /*useStore*/ false, &isObjectEmpty);
  9537. }
  9538. funcInfo->ReleaseTmpRegister(protoLoc);
  9539. // Emit name binding.
  9540. if (pnodeClass->pnodeName)
  9541. {
  9542. Symbol * sym = pnodeClass->pnodeName->sym;
  9543. sym->SetNeedDeclaration(false);
  9544. byteCodeGenerator->EmitPropStore(pnodeClass->location, sym, nullptr, funcInfo, false, true);
  9545. }
  9546. EndEmitBlock(pnodeClass->pnodeBlock, byteCodeGenerator, funcInfo);
  9547. if (pnodeClass->pnodeDeclName)
  9548. {
  9549. Symbol * sym = pnodeClass->pnodeDeclName->sym;
  9550. sym->SetNeedDeclaration(false);
  9551. byteCodeGenerator->EmitPropStore(pnodeClass->location, sym, nullptr, funcInfo, true, false);
  9552. }
  9553. if (pnodeClass->IsDefaultModuleExport())
  9554. {
  9555. byteCodeGenerator->EmitAssignmentToDefaultModuleExport(pnodeClass, funcInfo);
  9556. }
  9557. }
  9558. void TrackIntConstantsOnGlobalUserObject(ByteCodeGenerator *byteCodeGenerator, bool isSymGlobalAndSingleAssignment, Js::PropertyId propertyId)
  9559. {
  9560. if (isSymGlobalAndSingleAssignment)
  9561. {
  9562. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalUserObject(propertyId);
  9563. }
  9564. }
  9565. void TrackIntConstantsOnGlobalObject(ByteCodeGenerator *byteCodeGenerator, bool isSymGlobalAndSingleAssignment, Js::PropertyId propertyId)
  9566. {
  9567. if (isSymGlobalAndSingleAssignment)
  9568. {
  9569. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalObject(propertyId);
  9570. }
  9571. }
  9572. void TrackIntConstantsOnGlobalObject(ByteCodeGenerator *byteCodeGenerator, Symbol *sym)
  9573. {
  9574. if (sym && sym->GetIsGlobal() && sym->IsAssignedOnce())
  9575. {
  9576. Js::PropertyId propertyId = sym->EnsurePosition(byteCodeGenerator);
  9577. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalObject(propertyId);
  9578. }
  9579. }
  9580. void TrackMemberNodesInObjectForIntConstants(ByteCodeGenerator *byteCodeGenerator, ParseNodePtr objNode)
  9581. {
  9582. Assert(objNode->nop == knopObject);
  9583. ParseNodePtr memberList = objNode->AsParseNodeUni()->pnode1;
  9584. while (memberList != nullptr)
  9585. {
  9586. ParseNodePtr memberNode = memberList->nop == knopList ? memberList->AsParseNodeBin()->pnode1 : memberList;
  9587. if (memberNode->nop != knopEllipsis)
  9588. {
  9589. ParseNodePtr memberNameNode = memberNode->AsParseNodeBin()->pnode1;
  9590. ParseNodePtr memberValNode = memberNode->AsParseNodeBin()->pnode2;
  9591. if (memberNameNode->nop != knopComputedName && memberValNode->nop == knopInt)
  9592. {
  9593. Js::PropertyId propertyId = memberNameNode->AsParseNodeStr()->pid->GetPropertyId();
  9594. TrackIntConstantsOnGlobalUserObject(byteCodeGenerator, true, propertyId);
  9595. }
  9596. }
  9597. memberList = memberList->nop == knopList ? memberList->AsParseNodeBin()->pnode2 : nullptr;
  9598. }
  9599. }
  9600. void TrackGlobalIntAssignmentsForknopDotProps(ParseNodePtr knopDotNode, ByteCodeGenerator * byteCodeGenerator)
  9601. {
  9602. Assert(knopDotNode->nop == knopDot);
  9603. ParseNodePtr objectNode = knopDotNode->AsParseNodeBin()->pnode1;
  9604. ParseNodeName * propertyNode = knopDotNode->AsParseNodeBin()->pnode2->AsParseNodeName();
  9605. bool isSymGlobalAndSingleAssignment = false;
  9606. if (objectNode->nop == knopName)
  9607. {
  9608. if (ByteCodeGenerator::IsThis(objectNode))
  9609. {
  9610. // Assume 'this' always refer to GlobalObject
  9611. // Cases like "this.a = "
  9612. isSymGlobalAndSingleAssignment = propertyNode->pid->IsSingleAssignment();
  9613. Js::PropertyId propertyId = propertyNode->PropertyIdFromNameNode();
  9614. TrackIntConstantsOnGlobalObject(byteCodeGenerator, isSymGlobalAndSingleAssignment, propertyId);
  9615. }
  9616. else
  9617. {
  9618. Symbol * sym = objectNode->AsParseNodeName()->sym;
  9619. isSymGlobalAndSingleAssignment = sym && sym->GetIsGlobal() && sym->IsAssignedOnce() && propertyNode->pid->IsSingleAssignment();
  9620. Js::PropertyId propertyId = propertyNode->PropertyIdFromNameNode();
  9621. TrackIntConstantsOnGlobalUserObject(byteCodeGenerator, isSymGlobalAndSingleAssignment, propertyId);
  9622. }
  9623. }
  9624. }
  9625. void TrackGlobalIntAssignments(ParseNodePtr pnode, ByteCodeGenerator * byteCodeGenerator)
  9626. {
  9627. // Track the Global Int Constant properties' assignments here.
  9628. uint nodeType = ParseNode::Grfnop(pnode->nop);
  9629. if (nodeType & fnopAsg)
  9630. {
  9631. if (nodeType & fnopBin)
  9632. {
  9633. ParseNodePtr lhs = pnode->AsParseNodeBin()->pnode1;
  9634. ParseNodePtr rhs = pnode->AsParseNodeBin()->pnode2;
  9635. Assert(lhs && rhs);
  9636. // Don't track other than integers and objects with member nodes.
  9637. if (rhs->nop == knopObject)
  9638. {
  9639. TrackMemberNodesInObjectForIntConstants(byteCodeGenerator, rhs);
  9640. }
  9641. else if (rhs->nop != knopInt &&
  9642. ((rhs->nop != knopLsh && rhs->nop != knopRsh) || (rhs->AsParseNodeBin()->pnode1->nop != knopInt || rhs->AsParseNodeBin()->pnode2->nop != knopInt)))
  9643. {
  9644. return;
  9645. }
  9646. if (lhs->nop == knopName)
  9647. {
  9648. // Handle "a = <Integer>" cases here
  9649. Symbol * sym = lhs->AsParseNodeName()->sym;
  9650. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  9651. }
  9652. else if (lhs->nop == knopDot && lhs->AsParseNodeBin()->pnode2->nop == knopName)
  9653. {
  9654. // Cases like "obj.a = <Integer>"
  9655. TrackGlobalIntAssignmentsForknopDotProps(lhs, byteCodeGenerator);
  9656. }
  9657. }
  9658. else if (nodeType & fnopUni)
  9659. {
  9660. ParseNodePtr lhs = pnode->AsParseNodeUni()->pnode1;
  9661. if (lhs->nop == knopName)
  9662. {
  9663. // Cases like "a++"
  9664. Symbol * sym = lhs->AsParseNodeName()->sym;
  9665. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  9666. }
  9667. else if (lhs->nop == knopDot && lhs->AsParseNodeBin()->pnode2->nop == knopName)
  9668. {
  9669. // Cases like "obj.a++"
  9670. TrackGlobalIntAssignmentsForknopDotProps(lhs, byteCodeGenerator);
  9671. }
  9672. }
  9673. }
  9674. }
  9675. void Emit(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue, bool isConstructorCall, bool isTopLevel)
  9676. {
  9677. if (pnode == nullptr)
  9678. {
  9679. return;
  9680. }
  9681. ThreadContext::ProbeCurrentStackNoDispose(Js::Constants::MinStackByteCodeVisitor, byteCodeGenerator->GetScriptContext());
  9682. TrackGlobalIntAssignments(pnode, byteCodeGenerator);
  9683. // printNop(pnode->nop);
  9684. switch (pnode->nop)
  9685. {
  9686. case knopList:
  9687. EmitList(pnode, byteCodeGenerator, funcInfo);
  9688. break;
  9689. case knopInt:
  9690. // currently, these are loaded at the top
  9691. break;
  9692. // PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  9693. case knopFlt:
  9694. // currently, these are loaded at the top
  9695. break;
  9696. // PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  9697. case knopStr:
  9698. // TODO: protocol for combining string constants
  9699. break;
  9700. // PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  9701. case knopBigInt:
  9702. // PTNODE(knopBigInt , "bigint const" ,None ,Pid ,fnopLeaf|fnopConst)
  9703. break;
  9704. case knopRegExp:
  9705. funcInfo->GetParsedFunctionBody()->SetLiteralRegex(pnode->AsParseNodeRegExp()->regexPatternIndex, pnode->AsParseNodeRegExp()->regexPattern);
  9706. byteCodeGenerator->Writer()->Reg1Unsigned1(Js::OpCode::NewRegEx, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeRegExp()->regexPatternIndex);
  9707. break;
  9708. // PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  9709. case knopNull:
  9710. // enregistered
  9711. break;
  9712. // PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  9713. case knopFalse:
  9714. // enregistered
  9715. break;
  9716. // PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  9717. case knopTrue:
  9718. // enregistered
  9719. break;
  9720. // PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  9721. case knopEmpty:
  9722. break;
  9723. // Unary operators.
  9724. // PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  9725. case knopNot:
  9726. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9727. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9728. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9729. byteCodeGenerator->Writer()->Reg2(
  9730. Js::OpCode::Not_A, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeUni()->pnode1->location);
  9731. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9732. break;
  9733. // PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  9734. case knopNeg:
  9735. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9736. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9737. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9738. funcInfo->AcquireLoc(pnode);
  9739. byteCodeGenerator->Writer()->Reg2(
  9740. Js::OpCode::Neg_A, pnode->location, pnode->AsParseNodeUni()->pnode1->location);
  9741. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9742. break;
  9743. // PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  9744. case knopPos:
  9745. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9746. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9747. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9748. byteCodeGenerator->Writer()->Reg2(
  9749. Js::OpCode::Conv_Num, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeUni()->pnode1->location);
  9750. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9751. break;
  9752. // PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  9753. case knopLogNot:
  9754. {
  9755. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9756. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  9757. // For boolean expressions that compute a result, we have to burn a register for the result
  9758. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  9759. // full-on renaming in the back end.
  9760. funcInfo->AcquireLoc(pnode);
  9761. if (pnode->AsParseNodeUni()->pnode1->nop == knopInt)
  9762. {
  9763. int32 value = pnode->AsParseNodeUni()->pnode1->AsParseNodeInt()->lw;
  9764. Js::OpCode op = value ? Js::OpCode::LdFalse : Js::OpCode::LdTrue;
  9765. byteCodeGenerator->Writer()->Reg1(op, pnode->location);
  9766. }
  9767. else
  9768. {
  9769. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9770. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, pnode->location);
  9771. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, doneLabel, pnode->AsParseNodeUni()->pnode1->location);
  9772. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue_ReuseLoc, pnode->location);
  9773. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  9774. }
  9775. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9776. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9777. break;
  9778. }
  9779. // PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  9780. case knopEllipsis:
  9781. {
  9782. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9783. // Transparently pass the location of the object or array.
  9784. pnode->location = pnode->AsParseNodeUni()->pnode1->location;
  9785. break;
  9786. }
  9787. // PTNODE(knopIncPost , "post++" ,Inc ,Uni ,fnopUni|fnopAsg)
  9788. case knopIncPost:
  9789. case knopDecPost:
  9790. // FALL THROUGH to the faster pre-inc/dec case if the result of the expression is not needed.
  9791. if (pnode->isUsed || fReturnValue)
  9792. {
  9793. byteCodeGenerator->StartStatement(pnode);
  9794. bool isESBigIntEnabled = byteCodeGenerator->GetScriptContext()->GetConfig()->IsESBigIntEnabled();
  9795. Js::OpCode op1;
  9796. if (isESBigIntEnabled)
  9797. {
  9798. op1 = (pnode->nop == knopDecPost) ? Js::OpCode::Decr_Num_A : Js::OpCode::Incr_Num_A;
  9799. }
  9800. else
  9801. {
  9802. op1 = (pnode->nop == knopDecPost) ? Js::OpCode::Sub_A : Js::OpCode::Add_A;
  9803. }
  9804. ParseNode* pnode1 = pnode->AsParseNodeUni()->pnode1;
  9805. // Grab a register for the expression result.
  9806. funcInfo->AcquireLoc(pnode);
  9807. // Load the initial value, convert it (this is the expression result), and increment it.
  9808. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  9809. const Js::OpCode op2 = isESBigIntEnabled ? Js::OpCode::Conv_Numeric : Js::OpCode::Conv_Num;
  9810. byteCodeGenerator->Writer()->Reg2(op2, pnode->location, pnode1->location);
  9811. // Use temporary register if lhs cannot be assigned
  9812. Js::RegSlot incDecResult = pnode1->location;
  9813. if (funcInfo->RegIsConst(incDecResult) ||
  9814. (pnode1->nop == knopName && pnode1->AsParseNodeName()->sym && pnode1->AsParseNodeName()->sym->GetIsFuncExpr()))
  9815. {
  9816. incDecResult = funcInfo->AcquireTmpRegister();
  9817. }
  9818. if (isESBigIntEnabled)
  9819. {
  9820. byteCodeGenerator->Writer()->Reg2(op1, incDecResult, pnode->location);
  9821. }
  9822. else
  9823. {
  9824. Js::RegSlot oneReg = funcInfo->constantToRegister.LookupWithKey(1, Js::Constants::NoRegister);
  9825. Assert(oneReg != Js::Constants::NoRegister);
  9826. byteCodeGenerator->Writer()->Reg3(op1, incDecResult, pnode->location, oneReg);
  9827. }
  9828. // Store the incremented value.
  9829. EmitAssignment(nullptr, pnode1, incDecResult, byteCodeGenerator, funcInfo);
  9830. // Release the incremented value and the l-value.
  9831. if (incDecResult != pnode1->location)
  9832. {
  9833. funcInfo->ReleaseTmpRegister(incDecResult);
  9834. }
  9835. funcInfo->ReleaseLoad(pnode1);
  9836. byteCodeGenerator->EndStatement(pnode);
  9837. break;
  9838. }
  9839. else
  9840. {
  9841. pnode->nop = (pnode->nop == knopIncPost) ? knopIncPre : knopDecPre;
  9842. }
  9843. // FALL THROUGH to the fast pre-inc/dec case if the result of the expression is not needed.
  9844. // PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  9845. case knopIncPre:
  9846. case knopDecPre:
  9847. {
  9848. byteCodeGenerator->StartStatement(pnode);
  9849. const Js::OpCode op = (pnode->nop == knopDecPre) ? Js::OpCode::Decr_A : Js::OpCode::Incr_A;
  9850. ParseNode* pnode1 = pnode->AsParseNodeUni()->pnode1;
  9851. // Assign a register for the result only if the result is used or the LHS can't be assigned to
  9852. // (i.e., is a constant).
  9853. const bool need_result_location =
  9854. pnode->isUsed
  9855. || fReturnValue
  9856. || funcInfo->RegIsConst(pnode1->location)
  9857. || (pnode1->nop == knopName && pnode1->AsParseNodeName()->sym && pnode1->AsParseNodeName()->sym->GetIsFuncExpr());
  9858. if (need_result_location)
  9859. {
  9860. const Js::RegSlot result_location = funcInfo->AcquireLoc(pnode);
  9861. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  9862. byteCodeGenerator->Writer()->Reg2(op, result_location, pnode1->location);
  9863. // Store the incremented value and release the l-value.
  9864. EmitAssignment(nullptr, pnode1, result_location, byteCodeGenerator, funcInfo);
  9865. }
  9866. else
  9867. {
  9868. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  9869. byteCodeGenerator->Writer()->Reg2(op, pnode1->location, pnode1->location);
  9870. // Store the incremented value and release the l-value.
  9871. EmitAssignment(nullptr, pnode1, pnode1->location, byteCodeGenerator, funcInfo);
  9872. }
  9873. funcInfo->ReleaseLoad(pnode1);
  9874. byteCodeGenerator->EndStatement(pnode);
  9875. break;
  9876. }
  9877. // PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  9878. case knopTypeof:
  9879. {
  9880. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9881. ParseNode* pnodeOpnd = pnode->AsParseNodeUni()->pnode1;
  9882. switch (pnodeOpnd->nop)
  9883. {
  9884. case knopDot:
  9885. {
  9886. Emit(pnodeOpnd->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  9887. Js::PropertyId propertyId = pnodeOpnd->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  9888. Assert(pnodeOpnd->AsParseNodeBin()->pnode2->nop == knopName);
  9889. funcInfo->ReleaseLoc(pnodeOpnd->AsParseNodeBin()->pnode1);
  9890. funcInfo->AcquireLoc(pnode);
  9891. byteCodeGenerator->EmitTypeOfFld(funcInfo, propertyId, pnode->location, pnodeOpnd->AsParseNodeBin()->pnode1->location, Js::OpCode::LdFldForTypeOf);
  9892. break;
  9893. }
  9894. case knopIndex:
  9895. {
  9896. EmitBinaryOpnds(pnodeOpnd->AsParseNodeBin()->pnode1, pnodeOpnd->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9897. funcInfo->ReleaseLoc(pnodeOpnd->AsParseNodeBin()->pnode2);
  9898. funcInfo->ReleaseLoc(pnodeOpnd->AsParseNodeBin()->pnode1);
  9899. funcInfo->AcquireLoc(pnode);
  9900. byteCodeGenerator->Writer()->Element(Js::OpCode::TypeofElem, pnode->location, pnodeOpnd->AsParseNodeBin()->pnode1->location, pnodeOpnd->AsParseNodeBin()->pnode2->location);
  9901. break;
  9902. }
  9903. case knopName:
  9904. {
  9905. ParseNodeName * pnodeNameOpnd = pnodeOpnd->AsParseNodeName();
  9906. if (pnodeNameOpnd->IsUserIdentifier())
  9907. {
  9908. funcInfo->AcquireLoc(pnode);
  9909. byteCodeGenerator->EmitPropTypeof(pnode->location, pnodeNameOpnd->sym, pnodeNameOpnd->pid, funcInfo);
  9910. break;
  9911. }
  9912. // Special names should fallthrough to default case
  9913. }
  9914. default:
  9915. Emit(pnodeOpnd, byteCodeGenerator, funcInfo, false);
  9916. funcInfo->ReleaseLoc(pnodeOpnd);
  9917. byteCodeGenerator->Writer()->Reg2(
  9918. Js::OpCode::Typeof, funcInfo->AcquireLoc(pnode), pnodeOpnd->location);
  9919. break;
  9920. }
  9921. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9922. break;
  9923. }
  9924. // PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  9925. case knopVoid:
  9926. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9927. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9928. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, funcInfo->AcquireLoc(pnode));
  9929. break;
  9930. // PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  9931. case knopArray:
  9932. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9933. EmitArrayLiteral(pnode, byteCodeGenerator, funcInfo);
  9934. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9935. break;
  9936. // PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  9937. case knopObject:
  9938. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9939. funcInfo->AcquireLoc(pnode);
  9940. EmitObjectInitializers(pnode->AsParseNodeUni()->pnode1, pnode->location, byteCodeGenerator, funcInfo);
  9941. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9942. break;
  9943. // PTNODE(knopComputedName, "[name]" ,None ,Uni ,fnopUni)
  9944. case knopComputedName:
  9945. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9946. if (pnode->location == Js::Constants::NoRegister)
  9947. {
  9948. // The name is some expression with no home location. We can just re-use the register.
  9949. pnode->location = pnode->AsParseNodeUni()->pnode1->location;
  9950. }
  9951. else if (pnode->location != pnode->AsParseNodeUni()->pnode1->location)
  9952. {
  9953. // The name had to be protected from side-effects of the RHS.
  9954. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeUni()->pnode1->location);
  9955. }
  9956. break;
  9957. // Binary and Ternary Operators
  9958. case knopAdd:
  9959. EmitAdd(pnode, byteCodeGenerator, funcInfo);
  9960. break;
  9961. case knopSub:
  9962. case knopMul:
  9963. case knopExpo:
  9964. case knopDiv:
  9965. case knopMod:
  9966. case knopOr:
  9967. case knopXor:
  9968. case knopAnd:
  9969. case knopLsh:
  9970. case knopRsh:
  9971. case knopRs2:
  9972. case knopIn:
  9973. EmitBinary(nopToOp[pnode->nop], pnode, byteCodeGenerator, funcInfo);
  9974. break;
  9975. case knopInstOf:
  9976. {
  9977. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9978. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9979. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  9980. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  9981. funcInfo->AcquireLoc(pnode);
  9982. uint cacheId = funcInfo->NewIsInstInlineCache();
  9983. byteCodeGenerator->Writer()->Reg3C(nopToOp[pnode->nop], pnode->location, pnode->AsParseNodeBin()->pnode1->location,
  9984. pnode->AsParseNodeBin()->pnode2->location, cacheId);
  9985. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9986. }
  9987. break;
  9988. case knopEq:
  9989. case knopEqv:
  9990. case knopNEqv:
  9991. case knopNe:
  9992. case knopLt:
  9993. case knopLe:
  9994. case knopGe:
  9995. case knopGt:
  9996. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9997. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9998. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  9999. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  10000. funcInfo->AcquireLoc(pnode);
  10001. byteCodeGenerator->Writer()->Reg3(nopToCMOp[pnode->nop], pnode->location, pnode->AsParseNodeBin()->pnode1->location,
  10002. pnode->AsParseNodeBin()->pnode2->location);
  10003. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10004. break;
  10005. case knopNew:
  10006. {
  10007. EmitNew(pnode, byteCodeGenerator, funcInfo);
  10008. byteCodeGenerator->EndStatement(pnode);
  10009. break;
  10010. }
  10011. case knopDelete:
  10012. {
  10013. ParseNode *pexpr = pnode->AsParseNodeUni()->pnode1;
  10014. byteCodeGenerator->StartStatement(pnode);
  10015. switch (pexpr->nop)
  10016. {
  10017. case knopName:
  10018. {
  10019. ParseNodeName * pnodeName = pexpr->AsParseNodeName();
  10020. if (pnodeName->IsSpecialName())
  10021. {
  10022. funcInfo->AcquireLoc(pnode);
  10023. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, pnode->location);
  10024. }
  10025. else
  10026. {
  10027. funcInfo->AcquireLoc(pnode);
  10028. byteCodeGenerator->EmitPropDelete(pnode->location, pnodeName->sym, pnodeName->pid, funcInfo);
  10029. }
  10030. break;
  10031. }
  10032. case knopDot:
  10033. {
  10034. if (ByteCodeGenerator::IsSuper(pexpr->AsParseNodeBin()->pnode1))
  10035. {
  10036. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_DeletePropertyWithSuper));
  10037. funcInfo->AcquireLoc(pnode);
  10038. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, pnode->location);
  10039. }
  10040. else
  10041. {
  10042. Emit(pexpr->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  10043. funcInfo->ReleaseLoc(pexpr->AsParseNodeBin()->pnode1);
  10044. Js::PropertyId propertyId = pexpr->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  10045. funcInfo->AcquireLoc(pnode);
  10046. byteCodeGenerator->Writer()->Property(Js::OpCode::DeleteFld, pnode->location, pexpr->AsParseNodeBin()->pnode1->location,
  10047. funcInfo->FindOrAddReferencedPropertyId(propertyId), byteCodeGenerator->forceStrictModeForClassComputedPropertyName);
  10048. }
  10049. break;
  10050. }
  10051. case knopIndex:
  10052. {
  10053. EmitBinaryOpnds(pexpr->AsParseNodeBin()->pnode1, pexpr->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  10054. funcInfo->ReleaseLoc(pexpr->AsParseNodeBin()->pnode2);
  10055. funcInfo->ReleaseLoc(pexpr->AsParseNodeBin()->pnode1);
  10056. funcInfo->AcquireLoc(pnode);
  10057. byteCodeGenerator->Writer()->Element(Js::OpCode::DeleteElemI_A, pnode->location, pexpr->AsParseNodeBin()->pnode1->location, pexpr->AsParseNodeBin()->pnode2->location);
  10058. break;
  10059. }
  10060. default:
  10061. {
  10062. Emit(pexpr, byteCodeGenerator, funcInfo, false);
  10063. funcInfo->ReleaseLoc(pexpr);
  10064. byteCodeGenerator->Writer()->Reg2(
  10065. Js::OpCode::Delete_A, funcInfo->AcquireLoc(pnode), pexpr->location);
  10066. break;
  10067. }
  10068. }
  10069. byteCodeGenerator->EndStatement(pnode);
  10070. break;
  10071. }
  10072. case knopCall:
  10073. {
  10074. ParseNodeCall * pnodeCall = pnode->AsParseNodeCall();
  10075. byteCodeGenerator->StartStatement(pnodeCall);
  10076. if (pnodeCall->isSuperCall)
  10077. {
  10078. byteCodeGenerator->EmitSuperCall(funcInfo, pnodeCall->AsParseNodeSuperCall(), fReturnValue, /*fEvaluateComponents=*/ true);
  10079. }
  10080. else if (pnodeCall->pnodeTarget->nop == knopImport)
  10081. {
  10082. ParseNodePtr args = pnodeCall->pnodeArgs;
  10083. Assert(CountArguments(args) == 2); // import() takes one argument
  10084. Emit(args, byteCodeGenerator, funcInfo, false);
  10085. funcInfo->ReleaseLoc(args);
  10086. funcInfo->AcquireLoc(pnodeCall);
  10087. byteCodeGenerator->Writer()->Reg2(Js::OpCode::ImportCall, pnodeCall->location, args->location);
  10088. }
  10089. else
  10090. {
  10091. if (pnodeCall->isApplyCall && funcInfo->GetApplyEnclosesArgs())
  10092. {
  10093. // TODO[ianhall]: Can we remove the ApplyCall bytecode gen time optimization?
  10094. EmitApplyCall(pnodeCall, byteCodeGenerator, funcInfo, fReturnValue);
  10095. }
  10096. else
  10097. {
  10098. EmitCall(pnodeCall, byteCodeGenerator, funcInfo, fReturnValue, /*fEvaluateComponents*/ true);
  10099. }
  10100. }
  10101. byteCodeGenerator->EndStatement(pnode);
  10102. break;
  10103. }
  10104. case knopIndex:
  10105. {
  10106. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10107. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  10108. Js::RegSlot callObjLocation = pnode->AsParseNodeBin()->pnode1->location;
  10109. Js::RegSlot protoLocation = callObjLocation;
  10110. if (ByteCodeGenerator::IsSuper(pnode->AsParseNodeBin()->pnode1))
  10111. {
  10112. Emit(pnode->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  10113. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, callObjLocation, funcInfo);
  10114. funcInfo->ReleaseLoc(pnode->AsParseNodeSuperReference()->pnodeThis);
  10115. }
  10116. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  10117. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  10118. funcInfo->AcquireLoc(pnode);
  10119. byteCodeGenerator->Writer()->Element(
  10120. Js::OpCode::LdElemI_A, pnode->location, protoLocation, pnode->AsParseNodeBin()->pnode2->location);
  10121. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10122. break;
  10123. }
  10124. // this is MemberExpression as rvalue
  10125. case knopDot:
  10126. {
  10127. Emit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  10128. Js::RegSlot callObjLocation = pnode->AsParseNodeBin()->pnode1->location;
  10129. Js::RegSlot protoLocation = callObjLocation;
  10130. if (ByteCodeGenerator::IsSuper(pnode->AsParseNodeBin()->pnode1))
  10131. {
  10132. Emit(pnode->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  10133. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, callObjLocation, funcInfo);
  10134. funcInfo->ReleaseLoc(pnode->AsParseNodeSuperReference()->pnodeThis);
  10135. }
  10136. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  10137. funcInfo->AcquireLoc(pnode);
  10138. Js::PropertyId propertyId = pnode->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  10139. uint cacheId = funcInfo->FindOrAddInlineCacheId(protoLocation, propertyId, false, false);
  10140. if (propertyId == Js::PropertyIds::length)
  10141. {
  10142. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdLen_A, pnode->location, protoLocation, cacheId);
  10143. }
  10144. else if (pnode->IsCallApplyTargetLoad())
  10145. {
  10146. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFldForCallApplyTarget, pnode->location, protoLocation, cacheId);
  10147. }
  10148. else if (ByteCodeGenerator::IsSuper(pnode->AsParseNodeBin()->pnode1))
  10149. {
  10150. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(Js::OpCode::LdSuperFld, pnode->location, protoLocation, pnode->AsParseNodeSuperReference()->pnodeThis->location, cacheId, isConstructorCall);
  10151. }
  10152. else
  10153. {
  10154. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, pnode->location, callObjLocation, cacheId, isConstructorCall);
  10155. }
  10156. break;
  10157. }
  10158. // PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  10159. case knopAsg:
  10160. {
  10161. ParseNode *lhs = pnode->AsParseNodeBin()->pnode1;
  10162. ParseNode *rhs = pnode->AsParseNodeBin()->pnode2;
  10163. byteCodeGenerator->StartStatement(pnode);
  10164. if (pnode->isUsed || fReturnValue)
  10165. {
  10166. // If the assignment result is used, grab a register to hold it and pass it to EmitAssignment,
  10167. // which will copy the assigned value there.
  10168. funcInfo->AcquireLoc(pnode);
  10169. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, false);
  10170. EmitAssignment(pnode, lhs, rhs->location, byteCodeGenerator, funcInfo);
  10171. }
  10172. else
  10173. {
  10174. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, false);
  10175. EmitAssignment(nullptr, lhs, rhs->location, byteCodeGenerator, funcInfo);
  10176. }
  10177. funcInfo->ReleaseLoc(rhs);
  10178. if (!lhs->IsPattern())
  10179. {
  10180. funcInfo->ReleaseReference(lhs);
  10181. }
  10182. byteCodeGenerator->EndStatement(pnode);
  10183. break;
  10184. }
  10185. case knopName:
  10186. funcInfo->AcquireLoc(pnode);
  10187. if (ByteCodeGenerator::IsThis(pnode))
  10188. {
  10189. byteCodeGenerator->EmitPropLoadThis(pnode->location, pnode->AsParseNodeSpecialName(), funcInfo, true);
  10190. }
  10191. else
  10192. {
  10193. byteCodeGenerator->EmitPropLoad(pnode->location, pnode->AsParseNodeName()->sym, pnode->AsParseNodeName()->pid, funcInfo);
  10194. }
  10195. break;
  10196. case knopComma:
  10197. {
  10198. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10199. // The parser marks binary opnd pnodes as used, but value of the first opnd of a comma is not used.
  10200. // Easier to correct this here than to check every binary op in the parser.
  10201. ParseNode *pnode1 = pnode->AsParseNodeBin()->pnode1;
  10202. pnode1->isUsed = false;
  10203. if (pnode1->nop == knopComma)
  10204. {
  10205. // Spot fix for giant comma expressions that send us into OOS if we use a simple recursive
  10206. // algorithm. Instead of recursing on comma LHS's, iterate over them, pushing the RHS's onto
  10207. // a stack. (This suggests a model for removing recursion from Emit altogether...)
  10208. ArenaAllocator *alloc = byteCodeGenerator->GetAllocator();
  10209. SList<ParseNode *> rhsStack(alloc);
  10210. do
  10211. {
  10212. rhsStack.Push(pnode1->AsParseNodeBin()->pnode2);
  10213. pnode1 = pnode1->AsParseNodeBin()->pnode1;
  10214. pnode1->isUsed = false;
  10215. } while (pnode1->nop == knopComma);
  10216. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  10217. while (!rhsStack.Empty())
  10218. {
  10219. ParseNode *pnodeRhs = rhsStack.Pop();
  10220. pnodeRhs->isUsed = false;
  10221. Emit(pnodeRhs, byteCodeGenerator, funcInfo, false);
  10222. funcInfo->ReleaseLoc(pnodeRhs);
  10223. }
  10224. }
  10225. else
  10226. {
  10227. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  10228. }
  10229. funcInfo->ReleaseLoc(pnode1);
  10230. pnode->AsParseNodeBin()->pnode2->isUsed = pnode->isUsed || fReturnValue;
  10231. Emit(pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo, false);
  10232. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  10233. funcInfo->AcquireLoc(pnode);
  10234. if (pnode->AsParseNodeBin()->pnode2->isUsed && pnode->location != pnode->AsParseNodeBin()->pnode2->location)
  10235. {
  10236. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeBin()->pnode2->location);
  10237. }
  10238. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10239. }
  10240. break;
  10241. // The binary logical ops && and || resolve to the value of the left-hand expression if its
  10242. // boolean value short-circuits the operation, and to the value of the right-hand expression
  10243. // otherwise. (In other words, the "truth" of the right-hand expression is never tested.)
  10244. // PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  10245. case knopLogOr:
  10246. {
  10247. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10248. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  10249. // We use a single dest here for the whole generating boolean expr, because we were poorly
  10250. // optimizing the previous version where we had a dest for each level
  10251. funcInfo->AcquireLoc(pnode);
  10252. EmitGeneratingBooleanExpression(pnode, doneLabel, true, doneLabel, true, pnode->location, false, byteCodeGenerator, funcInfo);
  10253. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  10254. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10255. break;
  10256. }
  10257. // PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  10258. case knopLogAnd:
  10259. {
  10260. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10261. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  10262. // We use a single dest here for the whole generating boolean expr, because we were poorly
  10263. // optimizing the previous version where we had a dest for each level
  10264. funcInfo->AcquireLoc(pnode);
  10265. EmitGeneratingBooleanExpression(pnode, doneLabel, true, doneLabel, true, pnode->location, false, byteCodeGenerator, funcInfo);
  10266. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  10267. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10268. break;
  10269. }
  10270. // The Coalescing operator resolves to the left hand side if it is not null or undefined
  10271. // In that case the right hand side is not evaluated
  10272. // If the left hand side is null or undefined it resolves to the right hand side
  10273. // PTNODE(knopCoalesce , "??" ,None ,Bin ,fnopBin)
  10274. case knopCoalesce:
  10275. {
  10276. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10277. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  10278. funcInfo->AcquireLoc(pnode);
  10279. // LHS
  10280. Emit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  10281. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeBin()->pnode1->location);
  10282. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  10283. // check for null/undefined with != null
  10284. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrNeq_A, doneLabel, pnode->location, funcInfo->nullConstantRegister);
  10285. // RHS
  10286. Emit(pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo, false);
  10287. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A_ReuseLoc, pnode->location, pnode->AsParseNodeBin()->pnode2->location);
  10288. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  10289. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  10290. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10291. break;
  10292. }
  10293. // PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  10294. case knopQmark:
  10295. {
  10296. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  10297. Js::ByteCodeLabel falseLabel = byteCodeGenerator->Writer()->DefineLabel();
  10298. Js::ByteCodeLabel skipLabel = byteCodeGenerator->Writer()->DefineLabel();
  10299. EmitBooleanExpression(pnode->AsParseNodeTri()->pnode1, trueLabel, falseLabel, byteCodeGenerator, funcInfo, true, false);
  10300. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  10301. funcInfo->ReleaseLoc(pnode->AsParseNodeTri()->pnode1);
  10302. // For boolean expressions that compute a result, we have to burn a register for the result
  10303. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  10304. // full-on renaming in the back end.
  10305. funcInfo->AcquireLoc(pnode);
  10306. Emit(pnode->AsParseNodeTri()->pnode2, byteCodeGenerator, funcInfo, false);
  10307. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeTri()->pnode2->location);
  10308. funcInfo->ReleaseLoc(pnode->AsParseNodeTri()->pnode2);
  10309. // Record the branch bytecode offset
  10310. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_FromCurrentToNext);
  10311. byteCodeGenerator->Writer()->Br(skipLabel);
  10312. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  10313. Emit(pnode->AsParseNodeTri()->pnode3, byteCodeGenerator, funcInfo, false);
  10314. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A_ReuseLoc, pnode->location, pnode->AsParseNodeTri()->pnode3->location);
  10315. funcInfo->ReleaseLoc(pnode->AsParseNodeTri()->pnode3);
  10316. byteCodeGenerator->Writer()->MarkLabel(skipLabel);
  10317. break;
  10318. }
  10319. case knopAsgAdd:
  10320. case knopAsgSub:
  10321. case knopAsgMul:
  10322. case knopAsgDiv:
  10323. case knopAsgExpo:
  10324. case knopAsgMod:
  10325. case knopAsgAnd:
  10326. case knopAsgXor:
  10327. case knopAsgOr:
  10328. case knopAsgLsh:
  10329. case knopAsgRsh:
  10330. case knopAsgRs2:
  10331. {
  10332. byteCodeGenerator->StartStatement(pnode);
  10333. ParseNode *lhs = pnode->AsParseNodeBin()->pnode1;
  10334. ParseNode *rhs = pnode->AsParseNodeBin()->pnode2;
  10335. // Assign a register for the result only if the result is used or the LHS can't be assigned to
  10336. // (i.e., is a constant).
  10337. const bool need_result_location =
  10338. pnode->isUsed
  10339. || fReturnValue
  10340. || funcInfo->RegIsConst(lhs->location)
  10341. || (lhs->nop == knopName && lhs->AsParseNodeName()->sym && lhs->AsParseNodeName()->sym->GetIsFuncExpr());
  10342. if (need_result_location)
  10343. {
  10344. const Js::RegSlot result_location = funcInfo->AcquireLoc(pnode);
  10345. // Grab a register for the initial value and load it.
  10346. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, true);
  10347. funcInfo->ReleaseLoc(rhs);
  10348. // Do the arithmetic, store the result, and release the l-value.
  10349. byteCodeGenerator->Writer()->Reg3(nopToOp[pnode->nop], result_location, lhs->location, rhs->location);
  10350. EmitAssignment(pnode, lhs, result_location, byteCodeGenerator, funcInfo);
  10351. }
  10352. else
  10353. {
  10354. // Grab a register for the initial value and load it. Might modify lhs->location.
  10355. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, true);
  10356. funcInfo->ReleaseLoc(rhs);
  10357. // Do the arithmetic, store the result, and release the l-value.
  10358. byteCodeGenerator->Writer()->Reg3(nopToOp[pnode->nop], lhs->location, lhs->location, rhs->location);
  10359. EmitAssignment(nullptr, lhs, lhs->location, byteCodeGenerator, funcInfo);
  10360. }
  10361. funcInfo->ReleaseLoad(lhs);
  10362. byteCodeGenerator->EndStatement(pnode);
  10363. break;
  10364. }
  10365. // General nodes.
  10366. // PTNODE(knopTempRef , "temp ref" ,None ,Uni ,fnopUni)
  10367. case knopTempRef:
  10368. // TODO: check whether mov is necessary
  10369. funcInfo->AcquireLoc(pnode);
  10370. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeUni()->pnode1->location);
  10371. break;
  10372. // PTNODE(knopTemp , "temp" ,None ,None ,fnopLeaf)
  10373. case knopTemp:
  10374. // Emit initialization code
  10375. if (pnode->AsParseNodeVar()->pnodeInit != nullptr)
  10376. {
  10377. byteCodeGenerator->StartStatement(pnode);
  10378. Emit(pnode->AsParseNodeVar()->pnodeInit, byteCodeGenerator, funcInfo, false);
  10379. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeVar()->pnodeInit->location);
  10380. funcInfo->ReleaseLoc(pnode->AsParseNodeVar()->pnodeInit);
  10381. byteCodeGenerator->EndStatement(pnode);
  10382. }
  10383. break;
  10384. // PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  10385. case knopVarDecl:
  10386. case knopConstDecl:
  10387. case knopLetDecl:
  10388. {
  10389. // Emit initialization code
  10390. ParseNodePtr initNode = pnode->AsParseNodeVar()->pnodeInit;
  10391. AssertMsg(pnode->nop != knopConstDecl || initNode != nullptr, "knopConstDecl expected to have an initializer");
  10392. if (initNode != nullptr || pnode->nop == knopLetDecl)
  10393. {
  10394. Symbol *sym = pnode->AsParseNodeVar()->sym;
  10395. Js::RegSlot rhsLocation;
  10396. byteCodeGenerator->StartStatement(pnode);
  10397. if (initNode != nullptr)
  10398. {
  10399. Emit(initNode, byteCodeGenerator, funcInfo, false);
  10400. rhsLocation = initNode->location;
  10401. if (initNode->nop == knopObject)
  10402. {
  10403. TrackMemberNodesInObjectForIntConstants(byteCodeGenerator, initNode);
  10404. }
  10405. else if (initNode->nop == knopInt)
  10406. {
  10407. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  10408. }
  10409. }
  10410. else
  10411. {
  10412. Assert(pnode->nop == knopLetDecl);
  10413. rhsLocation = funcInfo->AcquireTmpRegister();
  10414. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, rhsLocation);
  10415. }
  10416. if (pnode->nop != knopVarDecl)
  10417. {
  10418. Assert(sym->GetDecl() == pnode || (sym->IsArguments() && !funcInfo->GetHasArguments()));
  10419. sym->SetNeedDeclaration(false);
  10420. }
  10421. EmitAssignment(nullptr, pnode, rhsLocation, byteCodeGenerator, funcInfo);
  10422. funcInfo->ReleaseTmpRegister(rhsLocation);
  10423. byteCodeGenerator->EndStatement(pnode);
  10424. }
  10425. break;
  10426. }
  10427. // PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  10428. case knopFncDecl:
  10429. // The "function declarations" were emitted in DefineFunctions()
  10430. if (!pnode->AsParseNodeFnc()->IsDeclaration())
  10431. {
  10432. byteCodeGenerator->DefineOneFunction(pnode->AsParseNodeFnc(), funcInfo, false);
  10433. }
  10434. break;
  10435. // PTNODE(knopClassDecl, "class" ,None ,None ,fnopLeaf)
  10436. case knopClassDecl:
  10437. EmitClass(pnode->AsParseNodeClass(), byteCodeGenerator, funcInfo);
  10438. break;
  10439. case knopStrTemplate:
  10440. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10441. EmitStringTemplate(pnode->AsParseNodeStrTemplate(), byteCodeGenerator, funcInfo);
  10442. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  10443. break;
  10444. case knopEndCode:
  10445. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_All);
  10446. // load undefined for the fallthrough case:
  10447. if (!funcInfo->IsGlobalFunction())
  10448. {
  10449. if (funcInfo->IsClassConstructor())
  10450. {
  10451. // For class constructors, we need to explicitly load 'this' into the return register.
  10452. byteCodeGenerator->EmitClassConstructorEndCode(funcInfo);
  10453. }
  10454. else
  10455. {
  10456. // In the global function, implicit return values are copied to the return register, and if
  10457. // necessary the return register is initialized at the top. Don't clobber the value here.
  10458. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, ByteCodeGenerator::ReturnRegister);
  10459. }
  10460. }
  10461. // Label for non-fall-through return
  10462. byteCodeGenerator->Writer()->MarkLabel(funcInfo->singleExit);
  10463. if (funcInfo->GetHasCachedScope())
  10464. {
  10465. byteCodeGenerator->Writer()->Empty(Js::OpCode::CommitScope);
  10466. }
  10467. byteCodeGenerator->StartStatement(pnode);
  10468. byteCodeGenerator->Writer()->Empty(Js::OpCode::Ret);
  10469. byteCodeGenerator->EndStatement(pnode);
  10470. break;
  10471. // PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  10472. case knopDebugger:
  10473. byteCodeGenerator->StartStatement(pnode);
  10474. byteCodeGenerator->Writer()->Empty(Js::OpCode::Break);
  10475. byteCodeGenerator->EndStatement(pnode);
  10476. break;
  10477. // PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  10478. case knopFor:
  10479. {
  10480. ParseNodeFor * pnodeFor = pnode->AsParseNodeFor();
  10481. if (pnodeFor->pnodeInverted != nullptr)
  10482. {
  10483. byteCodeGenerator->EmitInvertedLoop(pnodeFor, pnodeFor->pnodeInverted, funcInfo);
  10484. }
  10485. else
  10486. {
  10487. BeginEmitBlock(pnodeFor->pnodeBlock, byteCodeGenerator, funcInfo);
  10488. Emit(pnodeFor->pnodeInit, byteCodeGenerator, funcInfo, false);
  10489. funcInfo->ReleaseLoc(pnodeFor->pnodeInit);
  10490. CloneEmitBlock(pnodeFor->pnodeBlock, byteCodeGenerator, funcInfo);
  10491. EmitLoop(pnodeFor,
  10492. pnodeFor->pnodeCond,
  10493. pnodeFor->pnodeBody,
  10494. pnodeFor->pnodeIncr,
  10495. byteCodeGenerator,
  10496. funcInfo,
  10497. fReturnValue,
  10498. FALSE,
  10499. pnodeFor->pnodeBlock);
  10500. EndEmitBlock(pnodeFor->pnodeBlock, byteCodeGenerator, funcInfo);
  10501. }
  10502. break;
  10503. }
  10504. // PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  10505. case knopIf:
  10506. {
  10507. ParseNodeIf * pnodeIf = pnode->AsParseNodeIf();
  10508. byteCodeGenerator->StartStatement(pnodeIf);
  10509. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  10510. Js::ByteCodeLabel falseLabel = byteCodeGenerator->Writer()->DefineLabel();
  10511. EmitBooleanExpression(pnodeIf->pnodeCond, trueLabel, falseLabel, byteCodeGenerator, funcInfo, true, false);
  10512. funcInfo->ReleaseLoc(pnodeIf->pnodeCond);
  10513. byteCodeGenerator->EndStatement(pnodeIf);
  10514. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  10515. Emit(pnodeIf->pnodeTrue, byteCodeGenerator, funcInfo, fReturnValue);
  10516. funcInfo->ReleaseLoc(pnodeIf->pnodeTrue);
  10517. if (pnodeIf->pnodeFalse != nullptr)
  10518. {
  10519. // has else clause
  10520. Js::ByteCodeLabel skipLabel = byteCodeGenerator->Writer()->DefineLabel();
  10521. // Record the branch bytecode offset
  10522. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_FromCurrentToNext);
  10523. // then clause skips else clause
  10524. byteCodeGenerator->Writer()->Br(skipLabel);
  10525. // generate code for else clause
  10526. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  10527. Emit(pnodeIf->pnodeFalse, byteCodeGenerator, funcInfo, fReturnValue);
  10528. funcInfo->ReleaseLoc(pnodeIf->pnodeFalse);
  10529. byteCodeGenerator->Writer()->MarkLabel(skipLabel);
  10530. }
  10531. else
  10532. {
  10533. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  10534. }
  10535. if (pnodeIf->emitLabels)
  10536. {
  10537. byteCodeGenerator->Writer()->MarkLabel(pnodeIf->breakLabel);
  10538. }
  10539. break;
  10540. }
  10541. case knopWhile:
  10542. {
  10543. ParseNodeWhile * pnodeWhile = pnode->AsParseNodeWhile();
  10544. EmitLoop(pnodeWhile,
  10545. pnodeWhile->pnodeCond,
  10546. pnodeWhile->pnodeBody,
  10547. nullptr,
  10548. byteCodeGenerator,
  10549. funcInfo,
  10550. fReturnValue);
  10551. break;
  10552. }
  10553. // PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  10554. case knopDoWhile:
  10555. {
  10556. ParseNodeWhile * pnodeWhile = pnode->AsParseNodeWhile();
  10557. EmitLoop(pnodeWhile,
  10558. pnodeWhile->pnodeCond,
  10559. pnodeWhile->pnodeBody,
  10560. nullptr,
  10561. byteCodeGenerator,
  10562. funcInfo,
  10563. fReturnValue,
  10564. true);
  10565. break;
  10566. }
  10567. // PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  10568. case knopForIn:
  10569. EmitForInOrForOf(pnode->AsParseNodeForInOrForOf(), byteCodeGenerator, funcInfo, fReturnValue);
  10570. break;
  10571. case knopForAwaitOf:
  10572. case knopForOf:
  10573. EmitForInOrForOf(pnode->AsParseNodeForInOrForOf(), byteCodeGenerator, funcInfo, fReturnValue);
  10574. break;
  10575. // PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  10576. case knopReturn:
  10577. {
  10578. ParseNodeReturn * pnodeReturn = pnode->AsParseNodeReturn();
  10579. byteCodeGenerator->StartStatement(pnodeReturn);
  10580. if (pnodeReturn->pnodeExpr != nullptr)
  10581. {
  10582. if (pnodeReturn->pnodeExpr->location == Js::Constants::NoRegister)
  10583. {
  10584. // No need to burn a register for the return value. If we need a temp, use R0 directly.
  10585. pnodeReturn->pnodeExpr->location = ByteCodeGenerator::ReturnRegister;
  10586. }
  10587. Emit(pnodeReturn->pnodeExpr, byteCodeGenerator, funcInfo, fReturnValue);
  10588. if (funcInfo->IsAsyncGenerator())
  10589. {
  10590. EmitAwait(
  10591. ByteCodeGenerator::ReturnRegister,
  10592. pnodeReturn->pnodeExpr->location,
  10593. byteCodeGenerator,
  10594. funcInfo);
  10595. }
  10596. else if (pnodeReturn->pnodeExpr->location != ByteCodeGenerator::ReturnRegister)
  10597. {
  10598. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, pnodeReturn->pnodeExpr->location);
  10599. }
  10600. funcInfo->GetParsedFunctionBody()->SetHasNoExplicitReturnValue(false);
  10601. }
  10602. else
  10603. {
  10604. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, ByteCodeGenerator::ReturnRegister);
  10605. }
  10606. if (funcInfo->IsClassConstructor())
  10607. {
  10608. // return expr; // becomes like below:
  10609. //
  10610. // if (IsObject(expr)) {
  10611. // return expr;
  10612. // } else if (IsBaseClassConstructor) {
  10613. // return this;
  10614. // } else if (!IsUndefined(expr)) {
  10615. // throw TypeError;
  10616. // }
  10617. Js::ByteCodeLabel returnExprLabel = byteCodeGenerator->Writer()->DefineLabel();
  10618. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, returnExprLabel, ByteCodeGenerator::ReturnRegister);
  10619. if (funcInfo->IsBaseClassConstructor())
  10620. {
  10621. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, funcInfo->GetThisSymbol()->GetLocation());
  10622. }
  10623. else
  10624. {
  10625. Js::ByteCodeLabel returnThisLabel = byteCodeGenerator->Writer()->DefineLabel();
  10626. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, returnThisLabel, ByteCodeGenerator::ReturnRegister, funcInfo->undefinedConstantRegister);
  10627. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ClassDerivedConstructorInvalidReturnType));
  10628. byteCodeGenerator->Writer()->MarkLabel(returnThisLabel);
  10629. byteCodeGenerator->EmitClassConstructorEndCode(funcInfo);
  10630. }
  10631. byteCodeGenerator->Writer()->MarkLabel(returnExprLabel);
  10632. }
  10633. if (pnodeReturn->grfnop & fnopCleanup)
  10634. {
  10635. byteCodeGenerator->EmitJumpCleanup(nullptr, funcInfo);
  10636. }
  10637. byteCodeGenerator->Writer()->Br(funcInfo->singleExit);
  10638. byteCodeGenerator->EndStatement(pnodeReturn);
  10639. break;
  10640. }
  10641. // PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  10642. case knopBlock:
  10643. {
  10644. ParseNodeBlock * pnodeBlock = pnode->AsParseNodeBlock();
  10645. if (pnodeBlock->pnodeStmt != nullptr)
  10646. {
  10647. EmitBlock(pnodeBlock, byteCodeGenerator, funcInfo, fReturnValue);
  10648. if (pnodeBlock->emitLabels)
  10649. {
  10650. byteCodeGenerator->Writer()->MarkLabel(pnodeBlock->breakLabel);
  10651. }
  10652. }
  10653. break;
  10654. }
  10655. // PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  10656. case knopWith:
  10657. {
  10658. ParseNodeWith * pnodeWith = pnode->AsParseNodeWith();
  10659. Assert(pnodeWith->pnodeObj != nullptr);
  10660. byteCodeGenerator->StartStatement(pnodeWith);
  10661. // Copy the with object to a temp register (the location assigned to pnode) so that if the with object
  10662. // is overwritten in the body, the lookups are not affected.
  10663. funcInfo->AcquireLoc(pnodeWith);
  10664. Emit(pnodeWith->pnodeObj, byteCodeGenerator, funcInfo, false);
  10665. Js::RegSlot regVal = funcInfo->AcquireTmpRegister();
  10666. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Obj, regVal, pnodeWith->pnodeObj->location);
  10667. byteCodeGenerator->Writer()->Reg2(Js::OpCode::NewUnscopablesWrapperObject, pnodeWith->location, regVal);
  10668. byteCodeGenerator->EndStatement(pnodeWith);
  10669. #ifdef PERF_HINT
  10670. if (PHASE_TRACE1(Js::PerfHintPhase))
  10671. {
  10672. WritePerfHint(PerfHints::HasWithBlock, funcInfo->byteCodeFunction->GetFunctionBody(), byteCodeGenerator->Writer()->GetCurrentOffset() - 1);
  10673. }
  10674. #endif
  10675. if (pnodeWith->pnodeBody != nullptr)
  10676. {
  10677. Scope *scope = pnodeWith->scope;
  10678. scope->SetLocation(pnodeWith->location);
  10679. byteCodeGenerator->PushScope(scope);
  10680. Js::DebuggerScope *debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeWith, Js::DiagExtraScopesType::DiagWithScope, regVal);
  10681. if (byteCodeGenerator->ShouldTrackDebuggerMetadata())
  10682. {
  10683. byteCodeGenerator->Writer()->AddPropertyToDebuggerScope(debuggerScope, regVal, Js::Constants::NoProperty, /*shouldConsumeRegister*/ true, Js::DebuggerScopePropertyFlags_WithObject);
  10684. }
  10685. Emit(pnodeWith->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10686. funcInfo->ReleaseLoc(pnodeWith->pnodeBody);
  10687. byteCodeGenerator->PopScope();
  10688. byteCodeGenerator->RecordEndScopeObject(pnodeWith);
  10689. }
  10690. if (pnodeWith->emitLabels)
  10691. {
  10692. byteCodeGenerator->Writer()->MarkLabel(pnodeWith->breakLabel);
  10693. }
  10694. funcInfo->ReleaseTmpRegister(regVal);
  10695. funcInfo->ReleaseLoc(pnodeWith->pnodeObj);
  10696. break;
  10697. }
  10698. // PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  10699. case knopBreak:
  10700. {
  10701. ParseNodeJump * pnodeJump = pnode->AsParseNodeJump();
  10702. Assert(pnodeJump->pnodeTarget->emitLabels);
  10703. byteCodeGenerator->StartStatement(pnodeJump);
  10704. if (pnodeJump->grfnop & fnopCleanup)
  10705. {
  10706. byteCodeGenerator->EmitJumpCleanup(pnodeJump->pnodeTarget, funcInfo);
  10707. }
  10708. byteCodeGenerator->Writer()->Br(pnodeJump->pnodeTarget->breakLabel);
  10709. if (pnodeJump->emitLabels)
  10710. {
  10711. byteCodeGenerator->Writer()->MarkLabel(pnodeJump->breakLabel);
  10712. }
  10713. byteCodeGenerator->EndStatement(pnodeJump);
  10714. break;
  10715. }
  10716. case knopContinue:
  10717. {
  10718. ParseNodeJump * pnodeJump = pnode->AsParseNodeJump();
  10719. Assert(pnodeJump->pnodeTarget->emitLabels);
  10720. byteCodeGenerator->StartStatement(pnodeJump);
  10721. if (pnodeJump->grfnop & fnopCleanup)
  10722. {
  10723. byteCodeGenerator->EmitJumpCleanup(pnodeJump->pnodeTarget, funcInfo);
  10724. }
  10725. byteCodeGenerator->Writer()->Br(pnodeJump->pnodeTarget->continueLabel);
  10726. byteCodeGenerator->EndStatement(pnodeJump);
  10727. break;
  10728. }
  10729. // PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  10730. case knopSwitch:
  10731. {
  10732. ParseNodeSwitch * pnodeSwitch = pnode->AsParseNodeSwitch();
  10733. BOOL fHasDefault = false;
  10734. Assert(pnodeSwitch->pnodeVal != nullptr);
  10735. byteCodeGenerator->StartStatement(pnodeSwitch);
  10736. Emit(pnodeSwitch->pnodeVal, byteCodeGenerator, funcInfo, false);
  10737. Js::RegSlot regVal = funcInfo->AcquireTmpRegister();
  10738. byteCodeGenerator->Writer()->Reg2(Js::OpCode::BeginSwitch, regVal, pnodeSwitch->pnodeVal->location);
  10739. BeginEmitBlock(pnodeSwitch->pnodeBlock, byteCodeGenerator, funcInfo);
  10740. byteCodeGenerator->EndStatement(pnodeSwitch);
  10741. // TODO: if all cases are compile-time constants, emit a switch statement in the byte
  10742. // code so the BE can optimize it.
  10743. ParseNodeCase *pnodeCase;
  10744. for (pnodeCase = pnodeSwitch->pnodeCases; pnodeCase; pnodeCase = pnodeCase->pnodeNext)
  10745. {
  10746. // Jump to the first case body if this one doesn't match. Make sure any side-effects of the case
  10747. // expression take place regardless.
  10748. pnodeCase->labelCase = byteCodeGenerator->Writer()->DefineLabel();
  10749. if (pnodeCase == pnodeSwitch->pnodeDefault)
  10750. {
  10751. fHasDefault = true;
  10752. continue;
  10753. }
  10754. Emit(pnodeCase->pnodeExpr, byteCodeGenerator, funcInfo, false);
  10755. byteCodeGenerator->Writer()->BrReg2(
  10756. Js::OpCode::Case, pnodeCase->labelCase, regVal, pnodeCase->pnodeExpr->location);
  10757. funcInfo->ReleaseLoc(pnodeCase->pnodeExpr);
  10758. }
  10759. // No explicit case value matches. Jump to the default arm (if any) or break out altogether.
  10760. if (fHasDefault)
  10761. {
  10762. byteCodeGenerator->Writer()->Br(Js::OpCode::EndSwitch, pnodeSwitch->pnodeDefault->labelCase);
  10763. }
  10764. else
  10765. {
  10766. if (!pnodeSwitch->emitLabels)
  10767. {
  10768. pnodeSwitch->breakLabel = byteCodeGenerator->Writer()->DefineLabel();
  10769. }
  10770. byteCodeGenerator->Writer()->Br(Js::OpCode::EndSwitch, pnodeSwitch->breakLabel);
  10771. }
  10772. // Now emit the case arms to which we jump on matching a case value.
  10773. for (pnodeCase = pnodeSwitch->pnodeCases; pnodeCase; pnodeCase = pnodeCase->pnodeNext)
  10774. {
  10775. byteCodeGenerator->Writer()->MarkLabel(pnodeCase->labelCase);
  10776. Emit(pnodeCase->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10777. funcInfo->ReleaseLoc(pnodeCase->pnodeBody);
  10778. }
  10779. EndEmitBlock(pnodeSwitch->pnodeBlock, byteCodeGenerator, funcInfo);
  10780. funcInfo->ReleaseTmpRegister(regVal);
  10781. funcInfo->ReleaseLoc(pnodeSwitch->pnodeVal);
  10782. if (!fHasDefault || pnodeSwitch->emitLabels)
  10783. {
  10784. byteCodeGenerator->Writer()->MarkLabel(pnodeSwitch->breakLabel);
  10785. }
  10786. break;
  10787. }
  10788. case knopTryCatch:
  10789. {
  10790. Js::ByteCodeLabel catchLabel = (Js::ByteCodeLabel) - 1;
  10791. ParseNodeTryCatch * pnodeTryCatch = pnode->AsParseNodeTryCatch();
  10792. ParseNodeTry *pnodeTry = pnodeTryCatch->pnodeTry;
  10793. Assert(pnodeTry);
  10794. ParseNodeCatch *pnodeCatch = pnodeTryCatch->pnodeCatch;
  10795. Assert(pnodeCatch);
  10796. catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  10797. // Note: try uses OpCode::Leave which causes a return to parent interpreter thunk,
  10798. // same for catch block. Thus record cross interpreter frame entry/exit records for them.
  10799. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  10800. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  10801. byteCodeGenerator->PushJumpCleanupForTry(Js::OpCode::TryCatch, catchLabel);
  10802. Emit(pnodeTry->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10803. byteCodeGenerator->PopJumpCleanup();
  10804. funcInfo->ReleaseLoc(pnodeTry->pnodeBody);
  10805. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  10806. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  10807. byteCodeGenerator->Writer()->Br(pnodeTryCatch->breakLabel);
  10808. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  10809. Js::RegSlot location = Js::Constants::NoRegister;
  10810. Js::DebuggerScope *debuggerScope = nullptr;
  10811. Js::DebuggerScopePropertyFlags debuggerPropertyFlags = Js::DebuggerScopePropertyFlags_CatchObject;
  10812. ParseNode *tempLocationNode = nullptr;
  10813. if (pnodeCatch->HasPatternParam())
  10814. {
  10815. location = pnodeCatch->GetParam()->AsParseNodeParamPattern()->location;
  10816. }
  10817. else if (pnodeCatch->HasParam())
  10818. {
  10819. location = pnodeCatch->GetParam()->AsParseNodeName()->sym->GetLocation();
  10820. }
  10821. if (location == Js::Constants::NoRegister)
  10822. {
  10823. tempLocationNode = pnodeCatch->HasParam() ? pnodeCatch->GetParam() : pnodeCatch;
  10824. location = funcInfo->AcquireLoc(tempLocationNode);
  10825. }
  10826. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, location);
  10827. Scope *scope = pnodeCatch->scope;
  10828. byteCodeGenerator->PushScope(scope);
  10829. if (scope->GetMustInstantiate())
  10830. {
  10831. Assert(scope->GetLocation() == Js::Constants::NoRegister);
  10832. if (scope->GetIsObject())
  10833. {
  10834. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeTryCatch, Js::DiagCatchScopeInObject, funcInfo->InnerScopeToRegSlot(scope));
  10835. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::NewPseudoScope, scope->GetInnerScopeIndex());
  10836. }
  10837. else
  10838. {
  10839. int index = Js::DebuggerScope::InvalidScopeIndex;
  10840. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeTryCatch, Js::DiagCatchScopeInSlot, funcInfo->InnerScopeToRegSlot(scope), &index);
  10841. byteCodeGenerator->Writer()->Num3(Js::OpCode::NewInnerScopeSlots, scope->GetInnerScopeIndex(), scope->GetScopeSlotCount() + Js::ScopeSlots::FirstSlotIndex, index);
  10842. }
  10843. }
  10844. else
  10845. {
  10846. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeTryCatch, Js::DiagCatchScopeDirect, location);
  10847. }
  10848. auto ParamTrackAndInitialization = [&](Symbol *sym, bool initializeParam, Js::RegSlot location)
  10849. {
  10850. if (sym->IsInSlot(byteCodeGenerator, funcInfo))
  10851. {
  10852. Assert(scope->GetMustInstantiate());
  10853. if (scope->GetIsObject())
  10854. {
  10855. Js::OpCode op = (sym->GetDecl()->nop == knopLetDecl) ? Js::OpCode::InitUndeclLetFld :
  10856. byteCodeGenerator->GetInitFldOp(scope, scope->GetLocation(), funcInfo, false);
  10857. Js::PropertyId propertyId = sym->EnsurePosition(byteCodeGenerator);
  10858. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
  10859. byteCodeGenerator->Writer()->ElementPIndexed(op, location, scope->GetInnerScopeIndex(), cacheId);
  10860. byteCodeGenerator->TrackActivationObjectPropertyForDebugger(debuggerScope, sym, debuggerPropertyFlags);
  10861. }
  10862. else
  10863. {
  10864. byteCodeGenerator->TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(byteCodeGenerator), debuggerPropertyFlags);
  10865. if (initializeParam)
  10866. {
  10867. byteCodeGenerator->EmitLocalPropInit(location, sym, funcInfo);
  10868. }
  10869. else
  10870. {
  10871. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  10872. byteCodeGenerator->Writer()->Reg1(Js::OpCode::InitUndecl, tmpReg);
  10873. byteCodeGenerator->EmitLocalPropInit(tmpReg, sym, funcInfo);
  10874. funcInfo->ReleaseTmpRegister(tmpReg);
  10875. }
  10876. }
  10877. }
  10878. else
  10879. {
  10880. byteCodeGenerator->TrackRegisterPropertyForDebugger(debuggerScope, sym, funcInfo, debuggerPropertyFlags);
  10881. if (initializeParam)
  10882. {
  10883. byteCodeGenerator->EmitLocalPropInit(location, sym, funcInfo);
  10884. }
  10885. else
  10886. {
  10887. byteCodeGenerator->Writer()->Reg1(Js::OpCode::InitUndecl, location);
  10888. }
  10889. }
  10890. };
  10891. ByteCodeGenerator::TryScopeRecord tryRecForCatch(Js::OpCode::ResumeCatch, catchLabel);
  10892. if (pnodeCatch->HasPatternParam())
  10893. {
  10894. ParseNode *pnode1 = pnodeCatch->GetParam()->AsParseNodeParamPattern()->pnode1;
  10895. Parser::MapBindIdentifier(pnode1, [&](ParseNodePtr item)
  10896. {
  10897. Js::RegSlot itemLocation = item->AsParseNodeVar()->sym->GetLocation();
  10898. if (itemLocation == Js::Constants::NoRegister)
  10899. {
  10900. // The var has no assigned register, meaning it's captured, so we have no reg to write to.
  10901. // Emit the designated return reg in the byte code to avoid asserting on bad register.
  10902. itemLocation = ByteCodeGenerator::ReturnRegister;
  10903. }
  10904. ParamTrackAndInitialization(item->AsParseNodeVar()->sym, false /*initializeParam*/, itemLocation);
  10905. });
  10906. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10907. // Now emitting bytecode for destructuring pattern
  10908. byteCodeGenerator->StartStatement(pnodeCatch);
  10909. Assert(pnode1->IsPattern());
  10910. byteCodeGenerator->PushJumpCleanupForTry(Js::OpCode::ResumeCatch);
  10911. EmitAssignment(nullptr, pnode1, location, byteCodeGenerator, funcInfo);
  10912. byteCodeGenerator->EndStatement(pnodeCatch);
  10913. }
  10914. else
  10915. {
  10916. if (pnodeCatch->HasParam())
  10917. {
  10918. Symbol *sym = pnodeCatch->GetParam()->AsParseNodeName()->sym;
  10919. ParamTrackAndInitialization(sym, true /*initializeParam*/, location);
  10920. if (scope->GetMustInstantiate())
  10921. {
  10922. sym->SetIsGlobalCatch(true);
  10923. }
  10924. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10925. }
  10926. // Allow a debugger to stop on the 'catch'
  10927. byteCodeGenerator->StartStatement(pnodeCatch);
  10928. byteCodeGenerator->Writer()->Empty(Js::OpCode::Nop);
  10929. byteCodeGenerator->EndStatement(pnodeCatch);
  10930. byteCodeGenerator->PushJumpCleanupForTry(Js::OpCode::ResumeCatch);
  10931. }
  10932. Emit(pnodeCatch->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10933. byteCodeGenerator->PopJumpCleanup();
  10934. byteCodeGenerator->PopScope();
  10935. byteCodeGenerator->RecordEndScopeObject(pnodeTryCatch);
  10936. funcInfo->ReleaseLoc(pnodeCatch->pnodeBody);
  10937. if (tempLocationNode != nullptr)
  10938. {
  10939. funcInfo->ReleaseLoc(tempLocationNode);
  10940. }
  10941. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  10942. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  10943. byteCodeGenerator->Writer()->MarkLabel(pnodeTryCatch->breakLabel);
  10944. break;
  10945. }
  10946. case knopTryFinally:
  10947. {
  10948. Js::ByteCodeLabel finallyLabel = (Js::ByteCodeLabel) - 1;
  10949. ParseNodeTryFinally * pnodeTryFinally = pnode->AsParseNodeTryFinally();
  10950. ParseNodeTry *pnodeTry = pnodeTryFinally->pnodeTry;
  10951. Assert(pnodeTry);
  10952. ParseNodeFinally *pnodeFinally = pnodeTryFinally->pnodeFinally;
  10953. Assert(pnodeFinally);
  10954. // If we yield from the finally block after an exception, we have to store the exception object for the future next call.
  10955. // When we yield from the Try-Finally the offset to the end of the Try block is needed for the branch instruction.
  10956. Js::RegSlot regException = Js::Constants::NoRegister;
  10957. Js::RegSlot regOffset = Js::Constants::NoRegister;
  10958. finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  10959. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10960. // [CONSIDER][aneeshd] Ideally the TryFinallyWithYield opcode needs to be used only if there is a yield expression.
  10961. // For now, if the function is generator we are using the TryFinallyWithYield.
  10962. if (funcInfo->byteCodeFunction->IsCoroutine())
  10963. {
  10964. regException = funcInfo->AcquireTmpRegister();
  10965. regOffset = funcInfo->AcquireTmpRegister();
  10966. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  10967. byteCodeGenerator->PushJumpCleanupForTry(
  10968. Js::OpCode::TryFinallyWithYield,
  10969. finallyLabel,
  10970. regException,
  10971. regOffset);
  10972. }
  10973. else
  10974. {
  10975. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  10976. byteCodeGenerator->PushJumpCleanupForTry(Js::OpCode::TryFinally, finallyLabel);
  10977. }
  10978. // Increasing the stack as we will be storing the additional values when we enter try..finally.
  10979. funcInfo->StartRecordingOutArgs(1);
  10980. Emit(pnodeTry->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10981. funcInfo->ReleaseLoc(pnodeTry->pnodeBody);
  10982. byteCodeGenerator->PopJumpCleanup();
  10983. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  10984. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  10985. // Note: although we don't use OpCode::Leave for finally block,
  10986. // OpCode::LeaveNull causes a return to parent interpreter thunk.
  10987. // This has to be on offset prior to offset of 1st statement of finally.
  10988. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10989. byteCodeGenerator->Writer()->Br(pnodeTryFinally->breakLabel);
  10990. byteCodeGenerator->Writer()->MarkLabel(finallyLabel);
  10991. byteCodeGenerator->Writer()->Empty(Js::OpCode::Finally);
  10992. byteCodeGenerator->PushJumpCleanupForTry(
  10993. Js::OpCode::ResumeFinally,
  10994. finallyLabel,
  10995. regException,
  10996. regOffset);
  10997. Emit(pnodeFinally->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10998. funcInfo->ReleaseLoc(pnodeFinally->pnodeBody);
  10999. if (funcInfo->byteCodeFunction->IsCoroutine())
  11000. {
  11001. funcInfo->ReleaseTmpRegister(regOffset);
  11002. funcInfo->ReleaseTmpRegister(regException);
  11003. }
  11004. byteCodeGenerator->PopJumpCleanup();
  11005. funcInfo->EndRecordingOutArgs(1);
  11006. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  11007. byteCodeGenerator->Writer()->Empty(Js::OpCode::LeaveNull);
  11008. byteCodeGenerator->Writer()->MarkLabel(pnodeTryFinally->breakLabel);
  11009. break;
  11010. }
  11011. case knopThrow:
  11012. byteCodeGenerator->StartStatement(pnode);
  11013. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  11014. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Throw, pnode->AsParseNodeUni()->pnode1->location);
  11015. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  11016. byteCodeGenerator->EndStatement(pnode);
  11017. break;
  11018. case knopYieldLeaf:
  11019. byteCodeGenerator->StartStatement(pnode);
  11020. funcInfo->AcquireLoc(pnode);
  11021. EmitYield(pnode->location, funcInfo->undefinedConstantRegister, byteCodeGenerator, funcInfo);
  11022. byteCodeGenerator->EndStatement(pnode);
  11023. break;
  11024. case knopAwait:
  11025. byteCodeGenerator->StartStatement(pnode);
  11026. funcInfo->AcquireLoc(pnode);
  11027. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  11028. EmitAwait(pnode->location, pnode->AsParseNodeUni()->pnode1->location, byteCodeGenerator, funcInfo);
  11029. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  11030. byteCodeGenerator->EndStatement(pnode);
  11031. break;
  11032. case knopYield:
  11033. byteCodeGenerator->StartStatement(pnode);
  11034. funcInfo->AcquireLoc(pnode);
  11035. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  11036. EmitYield(pnode->location, pnode->AsParseNodeUni()->pnode1->location, byteCodeGenerator, funcInfo);
  11037. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  11038. byteCodeGenerator->EndStatement(pnode);
  11039. break;
  11040. case knopYieldStar:
  11041. byteCodeGenerator->StartStatement(pnode);
  11042. EmitYieldStar(pnode->AsParseNodeUni(), byteCodeGenerator, funcInfo);
  11043. byteCodeGenerator->EndStatement(pnode);
  11044. break;
  11045. case knopExportDefault:
  11046. Emit(pnode->AsParseNodeExportDefault()->pnodeExpr, byteCodeGenerator, funcInfo, false);
  11047. byteCodeGenerator->EmitAssignmentToDefaultModuleExport(pnode->AsParseNodeExportDefault()->pnodeExpr, funcInfo);
  11048. funcInfo->ReleaseLoc(pnode->AsParseNodeExportDefault()->pnodeExpr);
  11049. pnode = pnode->AsParseNodeExportDefault()->pnodeExpr;
  11050. break;
  11051. default:
  11052. AssertMsg(0, "emit unhandled pnode op");
  11053. break;
  11054. }
  11055. if (fReturnValue && IsExpressionStatement(pnode, byteCodeGenerator->GetScriptContext()) && !pnode->IsPatternDeclaration())
  11056. {
  11057. // If this statement may produce the global function's return value, copy its result to the return register.
  11058. // fReturnValue implies global function, which implies that "return" is a parse error.
  11059. Assert(funcInfo->IsGlobalFunction());
  11060. Assert(pnode->nop != knopReturn);
  11061. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, pnode->location);
  11062. }
  11063. }