ByteCodeEmitter.cpp 430 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "RuntimeByteCodePch.h"
  6. #include "FormalsUtil.h"
  7. #include "Language/AsmJs.h"
  8. void EmitReference(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  9. void EmitAssignment(ParseNode *asgnNode, ParseNode *lhs, Js::RegSlot rhsLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  10. void EmitLoad(ParseNode *rhs, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  11. void EmitCall(ParseNode* pnode, Js::RegSlot rhsLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue, BOOL fEvaluateComponents, BOOL fHasNewTarget, Js::RegSlot overrideThisLocation = Js::Constants::NoRegister);
  12. void EmitSuperFieldPatch(FuncInfo* funcInfo, ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator);
  13. bool EmitUseBeforeDeclaration(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  14. void EmitUseBeforeDeclarationRuntimeError(ByteCodeGenerator *byteCodeGenerator, Js::RegSlot location, bool fLoadUndef = true);
  15. void VisitClearTmpRegs(ParseNode * pnode, ByteCodeGenerator * byteCodeGenerator, FuncInfo * funcInfo);
  16. bool CallTargetIsArray(ParseNode *pnode)
  17. {
  18. return pnode->nop == knopName && pnode->sxPid.PropertyIdFromNameNode() == Js::PropertyIds::Array;
  19. }
  20. #define STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode) \
  21. if ((isTopLevel)) \
  22. { \
  23. byteCodeGenerator->StartStatement(pnode); \
  24. }
  25. #define ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode) \
  26. if ((isTopLevel)) \
  27. { \
  28. byteCodeGenerator->EndStatement(pnode); \
  29. }
  30. BOOL MayHaveSideEffectOnNode(ParseNode *pnode, ParseNode *pnodeSE)
  31. {
  32. // Try to determine whether pnodeSE may kill the named var represented by pnode.
  33. if (pnode->nop == knopComputedName)
  34. {
  35. pnode = pnode->sxUni.pnode1;
  36. }
  37. if (pnode->nop != knopName)
  38. {
  39. // Only investigating named vars here.
  40. return false;
  41. }
  42. uint fnop = ParseNode::Grfnop(pnodeSE->nop);
  43. if (fnop & fnopLeaf)
  44. {
  45. // pnodeSE is a leaf and can't kill anything.
  46. return false;
  47. }
  48. if (fnop & fnopAsg)
  49. {
  50. // pnodeSE is an assignment (=, ++, +=, etc.)
  51. // Trying to examine the LHS of pnodeSE caused small perf regressions,
  52. // maybe because of code layout or some other subtle effect.
  53. return true;
  54. }
  55. if (fnop & fnopUni)
  56. {
  57. // pnodeSE is a unary op, so recurse to the source (if present - e.g., [] may have no opnd).
  58. if (pnodeSE->nop == knopTempRef)
  59. {
  60. return false;
  61. }
  62. else
  63. {
  64. return pnodeSE->sxUni.pnode1 && MayHaveSideEffectOnNode(pnode, pnodeSE->sxUni.pnode1);
  65. }
  66. }
  67. else if (fnop & fnopBin)
  68. {
  69. // pnodeSE is a binary (or ternary) op, so recurse to the sources (if present).
  70. if (pnodeSE->nop == knopQmark)
  71. {
  72. return MayHaveSideEffectOnNode(pnode, pnodeSE->sxTri.pnode1) ||
  73. MayHaveSideEffectOnNode(pnode, pnodeSE->sxTri.pnode2) ||
  74. MayHaveSideEffectOnNode(pnode, pnodeSE->sxTri.pnode3);
  75. }
  76. else if (pnodeSE->nop == knopCall || pnodeSE->nop == knopNew)
  77. {
  78. return MayHaveSideEffectOnNode(pnode, pnodeSE->sxCall.pnodeTarget) ||
  79. (pnodeSE->sxCall.pnodeArgs && MayHaveSideEffectOnNode(pnode, pnodeSE->sxCall.pnodeArgs));
  80. }
  81. else
  82. {
  83. return MayHaveSideEffectOnNode(pnode, pnodeSE->sxBin.pnode1) ||
  84. (pnodeSE->sxBin.pnode2 && MayHaveSideEffectOnNode(pnode, pnodeSE->sxBin.pnode2));
  85. }
  86. }
  87. else if (pnodeSE->nop == knopList)
  88. {
  89. return true;
  90. }
  91. return false;
  92. }
  93. bool IsCallOfConstants(ParseNode *pnode);
  94. bool BlockHasOwnScope(ParseNode* pnodeBlock, ByteCodeGenerator *byteCodeGenerator);
  95. bool CreateNativeArrays(ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  96. bool IsArguments(ParseNode *pnode)
  97. {
  98. for (;;)
  99. {
  100. switch (pnode->nop)
  101. {
  102. case knopName:
  103. return pnode->sxPid.sym && pnode->sxPid.sym->GetIsArguments();
  104. case knopCall:
  105. case knopNew:
  106. if (IsArguments(pnode->sxCall.pnodeTarget))
  107. {
  108. return true;
  109. }
  110. if (pnode->sxCall.pnodeArgs)
  111. {
  112. ParseNode *pnodeArg = pnode->sxCall.pnodeArgs;
  113. while (pnodeArg->nop == knopList)
  114. {
  115. if (IsArguments(pnodeArg->sxBin.pnode1))
  116. return true;
  117. pnodeArg = pnodeArg->sxBin.pnode2;
  118. }
  119. pnode = pnodeArg;
  120. break;
  121. }
  122. return false;
  123. case knopArray:
  124. if (pnode->sxArrLit.arrayOfNumbers || pnode->sxArrLit.count == 0)
  125. {
  126. return false;
  127. }
  128. pnode = pnode->sxUni.pnode1;
  129. break;
  130. case knopQmark:
  131. if (IsArguments(pnode->sxTri.pnode1) || IsArguments(pnode->sxTri.pnode2))
  132. {
  133. return true;
  134. }
  135. pnode = pnode->sxTri.pnode3;
  136. break;
  137. //
  138. // Cases where we don't check for "arguments" yet.
  139. // Assume that they might have it. Disable the optimization is such scenarios
  140. //
  141. case knopList:
  142. case knopObject:
  143. case knopVarDecl:
  144. case knopConstDecl:
  145. case knopLetDecl:
  146. case knopFncDecl:
  147. case knopClassDecl:
  148. case knopFor:
  149. case knopIf:
  150. case knopDoWhile:
  151. case knopWhile:
  152. case knopForIn:
  153. case knopForOf:
  154. case knopReturn:
  155. case knopBlock:
  156. case knopBreak:
  157. case knopContinue:
  158. case knopLabel:
  159. case knopTypeof:
  160. case knopThrow:
  161. case knopWith:
  162. case knopFinally:
  163. case knopTry:
  164. case knopTryCatch:
  165. case knopTryFinally:
  166. case knopArrayPattern:
  167. case knopObjectPattern:
  168. case knopParamPattern:
  169. return true;
  170. default:
  171. {
  172. uint flags = ParseNode::Grfnop(pnode->nop);
  173. if (flags&fnopUni)
  174. {
  175. Assert(pnode->sxUni.pnode1);
  176. pnode = pnode->sxUni.pnode1;
  177. break;
  178. }
  179. else if (flags&fnopBin)
  180. {
  181. Assert(pnode->sxBin.pnode1 && pnode->sxBin.pnode2);
  182. if (IsArguments(pnode->sxBin.pnode1))
  183. {
  184. return true;
  185. }
  186. pnode = pnode->sxBin.pnode2;
  187. break;
  188. }
  189. return false;
  190. }
  191. }
  192. }
  193. }
  194. bool ApplyEnclosesArgs(ParseNode* fncDecl, ByteCodeGenerator* byteCodeGenerator);
  195. void Emit(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue, bool isConstructorCall = false, ParseNode *bindPnode = nullptr, bool isTopLevel = false);
  196. void EmitComputedFunctionNameVar(ParseNode *nameNode, ParseNode *exprNode, ByteCodeGenerator *byteCodeGenerator);
  197. void EmitBinaryOpnds(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  198. bool IsExpressionStatement(ParseNode* stmt, const Js::ScriptContext *const scriptContext);
  199. void EmitInvoke(Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  200. void EmitInvoke(Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot arg1Location);
  201. static const Js::OpCode nopToOp[knopLim] =
  202. {
  203. #define OP(x) Br##x##_A
  204. #define PTNODE(nop,sn,pc,nk,grfnop,json) Js::OpCode::pc,
  205. #include "ptlist.h"
  206. };
  207. static const Js::OpCode nopToCMOp[knopLim] =
  208. {
  209. #define OP(x) Cm##x##_A
  210. #define PTNODE(nop,sn,pc,nk,grfnop,json) Js::OpCode::pc,
  211. #include "ptlist.h"
  212. };
  213. Js::OpCode ByteCodeGenerator::ToChkUndeclOp(Js::OpCode op) const
  214. {
  215. switch(op)
  216. {
  217. case Js::OpCode::StLocalSlot:
  218. return Js::OpCode::StLocalSlotChkUndecl;
  219. case Js::OpCode::StInnerSlot:
  220. return Js::OpCode::StInnerSlotChkUndecl;
  221. case Js::OpCode::StEnvSlot:
  222. return Js::OpCode::StEnvSlotChkUndecl;
  223. case Js::OpCode::StObjSlot:
  224. return Js::OpCode::StObjSlotChkUndecl;
  225. case Js::OpCode::StLocalObjSlot:
  226. return Js::OpCode::StLocalObjSlotChkUndecl;
  227. case Js::OpCode::StInnerObjSlot:
  228. return Js::OpCode::StInnerObjSlotChkUndecl;
  229. case Js::OpCode::StEnvObjSlot:
  230. return Js::OpCode::StEnvObjSlotChkUndecl;
  231. default:
  232. AssertMsg(false, "Unknown opcode for chk undecl mapping");
  233. return Js::OpCode::InvalidOpCode;
  234. }
  235. }
  236. // Tracks a register slot let/const property for the passed in debugger block/catch scope.
  237. // debuggerScope - The scope to add the variable to.
  238. // symbol - The symbol that represents the register property.
  239. // funcInfo - The function info used to store the property into the tracked debugger register slot list.
  240. // flags - The flags to assign to the property.
  241. // isFunctionDeclaration - Whether or not the register is a function declaration, which requires that its byte code offset be updated immediately.
  242. void ByteCodeGenerator::TrackRegisterPropertyForDebugger(
  243. Js::DebuggerScope *debuggerScope,
  244. Symbol *symbol,
  245. FuncInfo *funcInfo,
  246. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  247. bool isFunctionDeclaration /*= false*/)
  248. {
  249. Assert(debuggerScope);
  250. Assert(symbol);
  251. Assert(funcInfo);
  252. Js::RegSlot location = symbol->GetLocation();
  253. Js::DebuggerScope *correctDebuggerScope = debuggerScope;
  254. if (debuggerScope->scopeType != Js::DiagExtraScopesType::DiagBlockScopeDirect && debuggerScope->scopeType != Js::DiagExtraScopesType::DiagCatchScopeDirect)
  255. {
  256. // We have to get the appropriate scope and add property over there.
  257. // Make sure the scope is created whether we're in debug mode or not, because we
  258. // need the empty scopes present during reparsing for debug mode.
  259. correctDebuggerScope = debuggerScope->GetSiblingScope(location, Writer()->GetFunctionWrite());
  260. }
  261. if (this->ShouldTrackDebuggerMetadata() && !symbol->GetIsTrackedForDebugger())
  262. {
  263. // Only track the property if we're in debug mode since it's only needed by the debugger.
  264. Js::PropertyId propertyId = symbol->EnsurePosition(this);
  265. this->Writer()->AddPropertyToDebuggerScope(
  266. correctDebuggerScope,
  267. location,
  268. propertyId,
  269. /*shouldConsumeRegister*/ true,
  270. flags,
  271. isFunctionDeclaration);
  272. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  273. byteCodeFunction->InsertSymbolToRegSlotList(location, propertyId, funcInfo->varRegsCount);
  274. symbol->SetIsTrackedForDebugger(true);
  275. }
  276. }
  277. void ByteCodeGenerator::TrackActivationObjectPropertyForDebugger(
  278. Js::DebuggerScope *debuggerScope,
  279. Symbol *symbol,
  280. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  281. bool isFunctionDeclaration /*= false*/)
  282. {
  283. Assert(debuggerScope);
  284. Assert(symbol);
  285. // Only need to track activation object properties in debug mode.
  286. if (ShouldTrackDebuggerMetadata() && !symbol->GetIsTrackedForDebugger())
  287. {
  288. Js::RegSlot location = symbol->GetLocation();
  289. Js::PropertyId propertyId = symbol->EnsurePosition(this);
  290. this->Writer()->AddPropertyToDebuggerScope(
  291. debuggerScope,
  292. location,
  293. propertyId,
  294. /*shouldConsumeRegister*/ false,
  295. flags,
  296. isFunctionDeclaration);
  297. symbol->SetIsTrackedForDebugger(true);
  298. }
  299. }
  300. void ByteCodeGenerator::TrackSlotArrayPropertyForDebugger(
  301. Js::DebuggerScope *debuggerScope,
  302. Symbol* symbol,
  303. Js::PropertyId propertyId,
  304. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  305. bool isFunctionDeclaration /*= false*/)
  306. {
  307. // Note: Slot array properties are tracked even in non-debug mode in order to support slot array serialization
  308. // of let/const variables between non-debug and debug mode (for example, when a slot array var escapes and is retrieved
  309. // after a debugger attach or for WWA apps). They are also needed for heap enumeration.
  310. Assert(debuggerScope);
  311. Assert(symbol);
  312. if (!symbol->GetIsTrackedForDebugger())
  313. {
  314. Js::RegSlot location = symbol->GetScopeSlot();
  315. Assert(location != Js::Constants::NoRegister);
  316. Assert(propertyId != Js::Constants::NoProperty);
  317. this->Writer()->AddPropertyToDebuggerScope(
  318. debuggerScope,
  319. location,
  320. propertyId,
  321. /*shouldConsumeRegister*/ false,
  322. flags,
  323. isFunctionDeclaration);
  324. symbol->SetIsTrackedForDebugger(true);
  325. }
  326. }
  327. // Tracks a function declaration inside a block scope for the debugger metadata's current scope (let binding).
  328. void ByteCodeGenerator::TrackFunctionDeclarationPropertyForDebugger(Symbol *functionDeclarationSymbol, FuncInfo *funcInfoParent)
  329. {
  330. Assert(functionDeclarationSymbol);
  331. Assert(funcInfoParent);
  332. AssertMsg(functionDeclarationSymbol->GetIsBlockVar(), "We should only track inner function let bindings for the debugger.");
  333. // Note: we don't have to check symbol->GetIsTrackedForDebugger, as we are not doing actual work here,
  334. // which is done in other Track* functions that we call.
  335. if (functionDeclarationSymbol->IsInSlot(funcInfoParent))
  336. {
  337. if (functionDeclarationSymbol->GetScope()->GetIsObject())
  338. {
  339. this->TrackActivationObjectPropertyForDebugger(
  340. this->Writer()->GetCurrentDebuggerScope(),
  341. functionDeclarationSymbol,
  342. Js::DebuggerScopePropertyFlags_None,
  343. true /*isFunctionDeclaration*/);
  344. }
  345. else
  346. {
  347. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  348. // Note that slot array inner function bindings are tracked even in non-debug mode in order
  349. // to keep the lifetime of the closure binding that could escape around for heap enumeration.
  350. functionDeclarationSymbol->EnsureScopeSlot(funcInfoParent);
  351. functionDeclarationSymbol->EnsurePosition(this);
  352. this->TrackSlotArrayPropertyForDebugger(
  353. this->Writer()->GetCurrentDebuggerScope(),
  354. functionDeclarationSymbol,
  355. functionDeclarationSymbol->GetPosition(),
  356. Js::DebuggerScopePropertyFlags_None,
  357. true /*isFunctionDeclaration*/);
  358. }
  359. }
  360. else
  361. {
  362. this->TrackRegisterPropertyForDebugger(
  363. this->Writer()->GetCurrentDebuggerScope(),
  364. functionDeclarationSymbol,
  365. funcInfoParent,
  366. Js::DebuggerScopePropertyFlags_None,
  367. true /*isFunctionDeclaration*/);
  368. }
  369. }
  370. // Updates the byte code offset of the property with the passed in location and ID.
  371. // Used to track let/const variables that are in the dead zone debugger side.
  372. // location - The activation object, scope slot index, or register location for the property.
  373. // propertyId - The ID of the property to update.
  374. // shouldConsumeRegister - Whether or not the a register should be consumed (used for reg slot locations).
  375. void ByteCodeGenerator::UpdateDebuggerPropertyInitializationOffset(Js::RegSlot location, Js::PropertyId propertyId, bool shouldConsumeRegister)
  376. {
  377. Assert(this->Writer());
  378. Js::DebuggerScope* currentDebuggerScope = this->Writer()->GetCurrentDebuggerScope();
  379. Assert(currentDebuggerScope);
  380. if (currentDebuggerScope != nullptr)
  381. {
  382. this->Writer()->UpdateDebuggerPropertyInitializationOffset(
  383. currentDebuggerScope,
  384. location,
  385. propertyId,
  386. shouldConsumeRegister);
  387. }
  388. }
  389. void ByteCodeGenerator::LoadHeapArguments(FuncInfo *funcInfo)
  390. {
  391. if (funcInfo->GetHasCachedScope())
  392. {
  393. this->LoadCachedHeapArguments(funcInfo);
  394. }
  395. else
  396. {
  397. this->LoadUncachedHeapArguments(funcInfo);
  398. }
  399. }
  400. void GetFormalArgsArray(ByteCodeGenerator *byteCodeGenerator, FuncInfo * funcInfo, Js::PropertyIdArray *propIds)
  401. {
  402. Assert(funcInfo);
  403. Assert(propIds);
  404. Assert(byteCodeGenerator);
  405. bool hadDuplicates = false;
  406. Js::ArgSlot i = 0;
  407. auto processArg = [&](ParseNode *pnode)
  408. {
  409. if (pnode->IsVarLetOrConst())
  410. {
  411. Assert(i < propIds->count);
  412. Symbol *sym = pnode->sxVar.sym;
  413. Assert(sym);
  414. Js::PropertyId symPos = sym->EnsurePosition(byteCodeGenerator);
  415. //
  416. // Check if the function has any same name parameters
  417. // For the same name param, only the last one will be passed the correct propertyid
  418. // For remaining dup param names, pass Constants::NoProperty
  419. //
  420. for (Js::ArgSlot j = 0; j < i; j++)
  421. {
  422. if (propIds->elements[j] == symPos)
  423. {
  424. // Found a dup parameter name
  425. propIds->elements[j] = Js::Constants::NoProperty;
  426. hadDuplicates = true;
  427. break;
  428. }
  429. }
  430. propIds->elements[i] = symPos;
  431. }
  432. else
  433. {
  434. propIds->elements[i] = Js::Constants::NoProperty;
  435. }
  436. ++i;
  437. };
  438. MapFormals(funcInfo->root, processArg);
  439. propIds->hadDuplicates = hadDuplicates;
  440. }
  441. void ByteCodeGenerator::LoadUncachedHeapArguments(FuncInfo *funcInfo)
  442. {
  443. Assert(funcInfo->GetHasHeapArguments());
  444. Scope *scope = funcInfo->GetBodyScope();
  445. Assert(scope);
  446. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  447. Assert(argSym && argSym->GetIsArguments());
  448. Js::RegSlot argumentsLoc = argSym->GetLocation();
  449. Js::RegSlot propIdsLoc = funcInfo->nullConstantRegister;
  450. Js::OpCode opcode = !funcInfo->root->sxFnc.HasNonSimpleParameterList() ? Js::OpCode::LdHeapArguments : Js::OpCode::LdLetHeapArguments;
  451. bool hasRest = funcInfo->root->sxFnc.pnodeRest != nullptr;
  452. uint count = funcInfo->inArgsCount + (hasRest ? 1 : 0) - 1;
  453. if (count == 0)
  454. {
  455. // If no formals to function (only "this"), then no need to create the scope object.
  456. // Leave both the arguments location and the propertyIds location as null.
  457. Assert(funcInfo->root->sxFnc.pnodeParams == nullptr && !hasRest);
  458. }
  459. else if (!NeedScopeObjectForArguments(funcInfo, funcInfo->root))
  460. {
  461. // We may not need a scope object for arguments, e.g. strict mode with no eval.
  462. }
  463. else if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  464. {
  465. // Pass the frame object and ID array to the runtime, and put the resulting Arguments object
  466. // at the expected location.
  467. propIdsLoc = argumentsLoc;
  468. Js::PropertyIdArray *propIds = AnewPlus(GetAllocator(), count * sizeof(Js::PropertyId), Js::PropertyIdArray, count);
  469. GetFormalArgsArray(this, funcInfo, propIds);
  470. // Generate the opcode with propIds
  471. Writer()->Auxiliary(
  472. Js::OpCode::LdPropIds,
  473. propIdsLoc,
  474. propIds,
  475. sizeof(Js::PropertyIdArray) + count * sizeof(Js::PropertyId),
  476. count);
  477. AdeletePlus(GetAllocator(), count * sizeof(Js::PropertyId), propIds);
  478. }
  479. this->m_writer.Reg2(opcode, argumentsLoc, propIdsLoc);
  480. EmitLocalPropInit(argSym->GetLocation(), argSym, funcInfo);
  481. }
  482. void ByteCodeGenerator::LoadCachedHeapArguments(FuncInfo *funcInfo)
  483. {
  484. Assert(funcInfo->GetHasHeapArguments());
  485. Scope *scope = funcInfo->GetBodyScope();
  486. Assert(scope);
  487. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  488. Assert(argSym && argSym->GetIsArguments());
  489. Js::RegSlot argumentsLoc = argSym->GetLocation();
  490. Js::OpCode op = !funcInfo->root->sxFnc.HasNonSimpleParameterList() ? Js::OpCode::LdHeapArgsCached : Js::OpCode::LdLetHeapArgsCached;
  491. this->m_writer.Reg1(op, argumentsLoc);
  492. EmitLocalPropInit(argumentsLoc, argSym, funcInfo);
  493. }
  494. Js::JavascriptArray* ByteCodeGenerator::BuildArrayFromStringList(ParseNode* stringNodeList, uint arrayLength, Js::ScriptContext* scriptContext)
  495. {
  496. Assert(stringNodeList);
  497. uint index = 0;
  498. Js::Var str;
  499. IdentPtr pid;
  500. Js::JavascriptArray* pArr = scriptContext->GetLibrary()->CreateArray(arrayLength);
  501. while (stringNodeList->nop == knopList)
  502. {
  503. Assert(stringNodeList->sxBin.pnode1->nop == knopStr);
  504. pid = stringNodeList->sxBin.pnode1->sxPid.pid;
  505. str = Js::JavascriptString::NewCopyBuffer(pid->Psz(), pid->Cch(), scriptContext);
  506. pArr->SetItemWithAttributes(index, str, PropertyEnumerable);
  507. stringNodeList = stringNodeList->sxBin.pnode2;
  508. index++;
  509. }
  510. Assert(stringNodeList->nop == knopStr);
  511. pid = stringNodeList->sxPid.pid;
  512. str = Js::JavascriptString::NewCopyBuffer(pid->Psz(), pid->Cch(), scriptContext);
  513. pArr->SetItemWithAttributes(index, str, PropertyEnumerable);
  514. return pArr;
  515. }
  516. // For now, this just assigns field ids for the current script.
  517. // Later, we will combine this information with the global field id map.
  518. // This temporary code will not work if a global member is accessed both with and without a LHS.
  519. void ByteCodeGenerator::AssignPropertyIds(Js::ParseableFunctionInfo* functionInfo)
  520. {
  521. globalScope->ForEachSymbol([this, functionInfo](Symbol * sym)
  522. {
  523. this->AssignPropertyId(sym, functionInfo);
  524. });
  525. }
  526. void ByteCodeGenerator::InitBlockScopedContent(ParseNode *pnodeBlock, Js::DebuggerScope* debuggerScope, FuncInfo *funcInfo)
  527. {
  528. Assert(pnodeBlock->nop == knopBlock);
  529. auto genBlockInit = [this, debuggerScope, funcInfo](ParseNode *pnode)
  530. {
  531. // Only check if the scope is valid when let/const vars are in the scope. If there are no let/const vars,
  532. // the debugger scope will not be created.
  533. AssertMsg(debuggerScope, "Missing a case of scope tracking in BeginEmitBlock.");
  534. FuncInfo *funcInfo = this->TopFuncInfo();
  535. Symbol *sym = pnode->sxVar.sym;
  536. Scope *scope = sym->GetScope();
  537. if (sym->GetIsGlobal())
  538. {
  539. Js::PropertyId propertyId = sym->EnsurePosition(this);
  540. if (this->flags & fscrEval)
  541. {
  542. AssertMsg(this->IsConsoleScopeEval(), "Let/Consts cannot be in global scope outside of console eval");
  543. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ? Js::OpCode::InitUndeclConsoleConstFld : Js::OpCode::InitUndeclConsoleLetFld;
  544. this->m_writer.ElementScopedU(op, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  545. }
  546. else if (!sym->GetIsModuleExportStorage())
  547. {
  548. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  549. Js::OpCode::InitUndeclRootConstFld : Js::OpCode::InitUndeclRootLetFld;
  550. this->m_writer.ElementRootU(op, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  551. }
  552. }
  553. else if (sym->IsInSlot(funcInfo) || (scope->GetIsObject() && sym->NeedsSlotAlloc(funcInfo)))
  554. {
  555. if (scope->GetIsObject())
  556. {
  557. Js::RegSlot scopeLocation = scope->GetLocation();
  558. Js::PropertyId propertyId = sym->EnsurePosition(this);
  559. if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  560. {
  561. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  562. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  563. Js::OpCode::InitUndeclLocalConstFld : Js::OpCode::InitUndeclLocalLetFld;
  564. this->m_writer.ElementP(op, ByteCodeGenerator::ReturnRegister, cacheId);
  565. }
  566. else
  567. {
  568. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
  569. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  570. Js::OpCode::InitUndeclConstFld : Js::OpCode::InitUndeclLetFld;
  571. this->m_writer.ElementPIndexed(op, ByteCodeGenerator::ReturnRegister, scope->GetInnerScopeIndex(), cacheId);
  572. }
  573. TrackActivationObjectPropertyForDebugger(debuggerScope, sym, pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  574. }
  575. else
  576. {
  577. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  578. this->m_writer.Reg1(Js::OpCode::InitUndecl, tmpReg);
  579. this->EmitLocalPropInit(tmpReg, sym, funcInfo);
  580. funcInfo->ReleaseTmpRegister(tmpReg);
  581. // Slot array properties are tracked in non-debug mode as well because they need to stay
  582. // around for heap enumeration and escaping during attach/detach.
  583. TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(this), pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  584. }
  585. }
  586. else
  587. {
  588. if (sym->GetDecl()->sxVar.isSwitchStmtDecl)
  589. {
  590. // let/const declared in a switch is the only case of a variable that must be checked for
  591. // use-before-declaration dynamically within its own function.
  592. this->m_writer.Reg1(Js::OpCode::InitUndecl, sym->GetLocation());
  593. }
  594. // Syms that begin in register may be delay-captured. In debugger mode, such syms
  595. // will live only in slots, so tell the debugger to find them there.
  596. if (sym->NeedsSlotAlloc(funcInfo))
  597. {
  598. TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(this), pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  599. }
  600. else
  601. {
  602. TrackRegisterPropertyForDebugger(debuggerScope, sym, funcInfo, pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  603. }
  604. }
  605. };
  606. IterateBlockScopedVariables(pnodeBlock, genBlockInit);
  607. }
  608. // Records the start of a debugger scope if the passed in node has any let/const variables (or is not a block node).
  609. // If it has no let/const variables, nullptr will be returned as no scope will be created.
  610. Js::DebuggerScope* ByteCodeGenerator::RecordStartScopeObject(ParseNode *pnodeBlock, Js::DiagExtraScopesType scopeType, Js::RegSlot scopeLocation /*= Js::Constants::NoRegister*/, int* index /*= nullptr*/)
  611. {
  612. Assert(pnodeBlock);
  613. if (pnodeBlock->nop == knopBlock && !pnodeBlock->sxBlock.HasBlockScopedContent())
  614. {
  615. // In order to reduce allocations now that we track debugger scopes in non-debug mode,
  616. // don't add a block to the chain if it has no let/const variables at all.
  617. return nullptr;
  618. }
  619. return this->Writer()->RecordStartScopeObject(scopeType, scopeLocation, index);
  620. }
  621. // Records the end of the current scope, but only if the current block has block scoped content.
  622. // Otherwise, a scope would not have been added (see ByteCodeGenerator::RecordStartScopeObject()).
  623. void ByteCodeGenerator::RecordEndScopeObject(ParseNode *pnodeBlock)
  624. {
  625. Assert(pnodeBlock);
  626. if (pnodeBlock->nop == knopBlock && !pnodeBlock->sxBlock.HasBlockScopedContent())
  627. {
  628. return;
  629. }
  630. this->Writer()->RecordEndScopeObject();
  631. }
  632. void BeginEmitBlock(ParseNode *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  633. {
  634. Js::DebuggerScope* debuggerScope = nullptr;
  635. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  636. {
  637. Scope *scope = pnodeBlock->sxBlock.scope;
  638. byteCodeGenerator->PushScope(scope);
  639. Js::RegSlot scopeLocation = scope->GetLocation();
  640. if (scope->GetMustInstantiate())
  641. {
  642. Assert(scopeLocation == Js::Constants::NoRegister);
  643. scopeLocation = funcInfo->FirstInnerScopeReg() + scope->GetInnerScopeIndex();
  644. if (scope->GetIsObject())
  645. {
  646. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInObject, scopeLocation);
  647. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::NewBlockScope, scope->GetInnerScopeIndex());
  648. }
  649. else
  650. {
  651. int scopeIndex = Js::DebuggerScope::InvalidScopeIndex;
  652. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInSlot, scopeLocation, &scopeIndex);
  653. // TODO: Handle heap enumeration
  654. int scopeSlotCount = scope->GetScopeSlotCount();
  655. byteCodeGenerator->Writer()->Num3(Js::OpCode::NewInnerScopeSlots, scope->GetInnerScopeIndex(), scopeSlotCount + Js::ScopeSlots::FirstSlotIndex, scopeIndex);
  656. }
  657. }
  658. else
  659. {
  660. // In the direct register access case, there is no block scope emitted but we can still track
  661. // the start and end offset of the block. The location registers for let/const variables will still be
  662. // captured along with this range in InitBlockScopedContent().
  663. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeDirect);
  664. }
  665. bool const isGlobalEvalBlockScope = scope->IsGlobalEvalBlockScope();
  666. Js::RegSlot frameDisplayLoc = Js::Constants::NoRegister;
  667. Js::RegSlot tmpInnerEnvReg = Js::Constants::NoRegister;
  668. ParseNodePtr pnodeScope;
  669. for (pnodeScope = pnodeBlock->sxBlock.pnodeScopes; pnodeScope;)
  670. {
  671. switch (pnodeScope->nop)
  672. {
  673. case knopFncDecl:
  674. if (pnodeScope->sxFnc.IsDeclaration())
  675. {
  676. // The frameDisplayLoc register's lifetime has to be controlled by this function. We can't let
  677. // it be released by DefineOneFunction, because further iterations of this loop can allocate
  678. // temps, and we can't let frameDisplayLoc be re-purposed until this loop completes.
  679. // So we'll supply a temp that we allocate and release here.
  680. if (frameDisplayLoc == Js::Constants::NoRegister)
  681. {
  682. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  683. {
  684. frameDisplayLoc = funcInfo->frameDisplayRegister;
  685. }
  686. else
  687. {
  688. frameDisplayLoc = funcInfo->GetEnvRegister();
  689. }
  690. tmpInnerEnvReg = funcInfo->AcquireTmpRegister();
  691. frameDisplayLoc = byteCodeGenerator->PrependLocalScopes(frameDisplayLoc, tmpInnerEnvReg, funcInfo);
  692. }
  693. byteCodeGenerator->DefineOneFunction(pnodeScope, funcInfo, true, frameDisplayLoc);
  694. }
  695. // If this is the global eval block scope, the function is actually assigned to the global
  696. // so we don't need to keep the registers.
  697. if (isGlobalEvalBlockScope)
  698. {
  699. funcInfo->ReleaseLoc(pnodeScope);
  700. pnodeScope->location = Js::Constants::NoRegister;
  701. }
  702. pnodeScope = pnodeScope->sxFnc.pnodeNext;
  703. break;
  704. case knopBlock:
  705. pnodeScope = pnodeScope->sxBlock.pnodeNext;
  706. break;
  707. case knopCatch:
  708. pnodeScope = pnodeScope->sxCatch.pnodeNext;
  709. break;
  710. case knopWith:
  711. pnodeScope = pnodeScope->sxWith.pnodeNext;
  712. break;
  713. }
  714. }
  715. if (tmpInnerEnvReg != Js::Constants::NoRegister)
  716. {
  717. funcInfo->ReleaseTmpRegister(tmpInnerEnvReg);
  718. }
  719. if (pnodeBlock->sxBlock.scope->IsGlobalEvalBlockScope() && funcInfo->thisScopeSlot != Js::Constants::NoRegister)
  720. {
  721. Scope* globalEvalBlockScope = funcInfo->GetGlobalEvalBlockScope();
  722. byteCodeGenerator->EmitInitCapturedThis(funcInfo, globalEvalBlockScope);
  723. }
  724. }
  725. else
  726. {
  727. Scope *scope = pnodeBlock->sxBlock.scope;
  728. if (scope)
  729. {
  730. if (scope->GetMustInstantiate())
  731. {
  732. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInObject);
  733. }
  734. else
  735. {
  736. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeDirect);
  737. }
  738. }
  739. else
  740. {
  741. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInSlot);
  742. }
  743. }
  744. byteCodeGenerator->InitBlockScopedContent(pnodeBlock, debuggerScope, funcInfo);
  745. }
  746. void EndEmitBlock(ParseNode *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  747. {
  748. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  749. {
  750. Scope *scope = pnodeBlock->sxBlock.scope;
  751. Assert(scope);
  752. Assert(scope == byteCodeGenerator->GetCurrentScope());
  753. byteCodeGenerator->PopScope();
  754. }
  755. byteCodeGenerator->RecordEndScopeObject(pnodeBlock);
  756. }
  757. void CloneEmitBlock(ParseNode *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  758. {
  759. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  760. {
  761. // Only let variables have observable behavior when there are per iteration
  762. // bindings. const variables do not since they are immutable. Therefore,
  763. // (and the spec agrees), only create new scope clones if the loop variable
  764. // is a let declaration.
  765. bool isConst = false;
  766. pnodeBlock->sxBlock.scope->ForEachSymbolUntil([&isConst](Symbol * const sym) {
  767. // Exploit the fact that a for loop sxBlock can only have let and const
  768. // declarations, and can only have one or the other, regardless of how
  769. // many syms there might be. Thus only check the first sym.
  770. isConst = sym->GetDecl()->nop == knopConstDecl;
  771. return true;
  772. });
  773. if (!isConst)
  774. {
  775. Scope *scope = pnodeBlock->sxBlock.scope;
  776. Assert(scope == byteCodeGenerator->GetCurrentScope());
  777. if (scope->GetMustInstantiate())
  778. {
  779. Js::OpCode op = scope->GetIsObject() ? Js::OpCode::CloneBlockScope : Js::OpCode::CloneInnerScopeSlots;
  780. byteCodeGenerator->Writer()->Unsigned1(op, scope->GetInnerScopeIndex());
  781. }
  782. }
  783. }
  784. }
  785. void EmitBlock(ParseNode *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue)
  786. {
  787. Assert(pnodeBlock->nop == knopBlock);
  788. ParseNode *pnode = pnodeBlock->sxBlock.pnodeStmt;
  789. if (pnode == nullptr)
  790. {
  791. return;
  792. }
  793. BeginEmitBlock(pnodeBlock, byteCodeGenerator, funcInfo);
  794. ParseNode *pnodeLastValStmt = pnodeBlock->sxBlock.pnodeLastValStmt;
  795. while (pnode->nop == knopList)
  796. {
  797. ParseNode* stmt = pnode->sxBin.pnode1;
  798. if (stmt == pnodeLastValStmt)
  799. {
  800. // This is the last guaranteed return value, so any potential return values have to be
  801. // copied to the return register from this point forward.
  802. pnodeLastValStmt = nullptr;
  803. }
  804. byteCodeGenerator->EmitTopLevelStatement(stmt, funcInfo, fReturnValue && (pnodeLastValStmt == nullptr));
  805. pnode = pnode->sxBin.pnode2;
  806. }
  807. if (pnode == pnodeLastValStmt)
  808. {
  809. pnodeLastValStmt = nullptr;
  810. }
  811. byteCodeGenerator->EmitTopLevelStatement(pnode, funcInfo, fReturnValue && (pnodeLastValStmt == nullptr));
  812. EndEmitBlock(pnodeBlock, byteCodeGenerator, funcInfo);
  813. }
  814. void ClearTmpRegs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* emitFunc)
  815. {
  816. if (emitFunc->IsTmpReg(pnode->location))
  817. {
  818. pnode->location = Js::Constants::NoRegister;
  819. }
  820. }
  821. void ByteCodeGenerator::EmitTopLevelStatement(ParseNode *stmt, FuncInfo *funcInfo, BOOL fReturnValue)
  822. {
  823. if (stmt->nop == knopFncDecl && stmt->sxFnc.IsDeclaration())
  824. {
  825. // Function declarations (not function-declaration RHS's) are already fully processed.
  826. // Skip them here so the temp registers don't get messed up.
  827. return;
  828. }
  829. if (stmt->nop == knopName || stmt->nop == knopDot)
  830. {
  831. // Generating span for top level names are mostly useful in debugging mode, because user can debug it even though no side-effect expected.
  832. // But the name can have runtime error, e.g., foo.bar; // where foo is not defined.
  833. // At this time we need to throw proper line number and offset. so recording on all modes will be useful.
  834. StartStatement(stmt);
  835. Writer()->Empty(Js::OpCode::Nop);
  836. EndStatement(stmt);
  837. }
  838. Emit(stmt, this, funcInfo, fReturnValue, false/*isConstructorCall*/, nullptr/*bindPnode*/, true/*isTopLevel*/);
  839. if (funcInfo->IsTmpReg(stmt->location))
  840. {
  841. if (!stmt->isUsed && !fReturnValue)
  842. {
  843. m_writer.Reg1(Js::OpCode::Unused, stmt->location);
  844. }
  845. funcInfo->ReleaseLoc(stmt);
  846. }
  847. }
  848. // ByteCodeGenerator::DefineFunctions
  849. //
  850. // Emit byte code for scope-wide function definitions before any calls in the scope, regardless of lexical
  851. // order. Note that stores to the closure array are not emitted until we see the knopFncDecl in the tree
  852. // to make sure that sources of the stores have been defined.
  853. void ByteCodeGenerator::DefineFunctions(FuncInfo *funcInfoParent)
  854. {
  855. // DefineCachedFunctions doesn't depend on whether the user vars are declared or not, so
  856. // we'll just overload this variable to mean that the functions getting called again and we don't need to do anything
  857. if (funcInfoParent->GetHasCachedScope())
  858. {
  859. this->DefineCachedFunctions(funcInfoParent);
  860. }
  861. else
  862. {
  863. this->DefineUncachedFunctions(funcInfoParent);
  864. }
  865. }
  866. // Iterate over all child functions in a function's parameter and body scopes.
  867. template<typename Fn>
  868. void MapContainerScopeFunctions(ParseNode* pnodeScope, Fn fn)
  869. {
  870. auto mapFncDeclsInScopeList = [&](ParseNode *pnodeHead)
  871. {
  872. for (ParseNode *pnode = pnodeHead; pnode != nullptr;)
  873. {
  874. switch (pnode->nop)
  875. {
  876. case knopFncDecl:
  877. fn(pnode);
  878. pnode = pnode->sxFnc.pnodeNext;
  879. break;
  880. case knopBlock:
  881. pnode = pnode->sxBlock.pnodeNext;
  882. break;
  883. case knopCatch:
  884. pnode = pnode->sxCatch.pnodeNext;
  885. break;
  886. case knopWith:
  887. pnode = pnode->sxWith.pnodeNext;
  888. break;
  889. default:
  890. AssertMsg(false, "Unexpected opcode in tree of scopes");
  891. return;
  892. }
  893. }
  894. };
  895. pnodeScope->sxFnc.MapContainerScopes(mapFncDeclsInScopeList);
  896. }
  897. void ByteCodeGenerator::DefineCachedFunctions(FuncInfo *funcInfoParent)
  898. {
  899. ParseNode *pnodeParent = funcInfoParent->root;
  900. uint slotCount = 0;
  901. auto countFncSlots = [&](ParseNode *pnodeFnc)
  902. {
  903. if (pnodeFnc->sxFnc.GetFuncSymbol() != nullptr && pnodeFnc->sxFnc.IsDeclaration())
  904. {
  905. slotCount++;
  906. }
  907. };
  908. MapContainerScopeFunctions(pnodeParent, countFncSlots);
  909. if (slotCount == 0)
  910. {
  911. return;
  912. }
  913. size_t extraBytesActual = AllocSizeMath::Mul(slotCount, sizeof(Js::FuncInfoEntry));
  914. // Reg2Aux takes int for byteCount so we need to convert to int. OOM if we can't because it would truncate data.
  915. if (extraBytesActual > INT_MAX)
  916. {
  917. Js::Throw::OutOfMemory();
  918. }
  919. int extraBytes = (int)extraBytesActual;
  920. Js::FuncInfoArray *info = AnewPlus(alloc, extraBytes, Js::FuncInfoArray, slotCount);
  921. slotCount = 0;
  922. auto fillEntries = [&](ParseNode *pnodeFnc)
  923. {
  924. Symbol *sym = pnodeFnc->sxFnc.GetFuncSymbol();
  925. if (sym != nullptr && (pnodeFnc->sxFnc.IsDeclaration()))
  926. {
  927. AssertMsg(!pnodeFnc->sxFnc.IsGenerator(), "Generator functions are not supported by InitCachedFuncs but since they always escape they should disable function caching");
  928. Js::FuncInfoEntry *entry = &info->elements[slotCount];
  929. entry->nestedIndex = pnodeFnc->sxFnc.nestedIndex;
  930. entry->scopeSlot = sym->GetScopeSlot();
  931. slotCount++;
  932. }
  933. };
  934. MapContainerScopeFunctions(pnodeParent, fillEntries);
  935. m_writer.AuxNoReg(Js::OpCode::InitCachedFuncs,
  936. info,
  937. sizeof(Js::FuncInfoArray) + extraBytes,
  938. sizeof(Js::FuncInfoArray) + extraBytes);
  939. slotCount = 0;
  940. auto defineOrGetCachedFunc = [&](ParseNode *pnodeFnc)
  941. {
  942. Symbol *sym = pnodeFnc->sxFnc.GetFuncSymbol();
  943. if (pnodeFnc->sxFnc.IsDeclaration())
  944. {
  945. // Do we need to define the function here (i.e., is it not one of our cached locals)?
  946. // Only happens if the sym is null (e.g., function x.y(){}).
  947. if (sym == nullptr)
  948. {
  949. this->DefineOneFunction(pnodeFnc, funcInfoParent);
  950. }
  951. else if (!sym->IsInSlot(funcInfoParent) && sym->GetLocation() != Js::Constants::NoRegister)
  952. {
  953. // If it was defined by InitCachedFuncs, do we need to put it in a register rather than a slot?
  954. m_writer.Reg1Unsigned1(Js::OpCode::GetCachedFunc, sym->GetLocation(), slotCount);
  955. }
  956. // The "x = function() {...}" case is being generated on the fly, during emission,
  957. // so the caller expects to be able to release this register.
  958. funcInfoParent->ReleaseLoc(pnodeFnc);
  959. pnodeFnc->location = Js::Constants::NoRegister;
  960. slotCount++;
  961. }
  962. };
  963. MapContainerScopeFunctions(pnodeParent, defineOrGetCachedFunc);
  964. AdeletePlus(alloc, extraBytes, info);
  965. }
  966. void ByteCodeGenerator::DefineUncachedFunctions(FuncInfo *funcInfoParent)
  967. {
  968. ParseNode *pnodeParent = funcInfoParent->root;
  969. auto defineCheck = [&](ParseNode *pnodeFnc)
  970. {
  971. Assert(pnodeFnc->nop == knopFncDecl);
  972. //
  973. // Don't define the function upfront in following cases
  974. // 1. x = function() {...};
  975. // Don't define the function for all modes.
  976. // Such a function can only be accessed via the LHS, so we define it at the assignment point
  977. // rather than the scope entry to save a register (and possibly save the whole definition).
  978. //
  979. // 2. x = function f() {...};
  980. // f is not visible in the enclosing scope.
  981. // Such function expressions should be emitted only at the assignment point, as can be used only
  982. // after the assignment. Might save register.
  983. //
  984. if (pnodeFnc->sxFnc.IsDeclaration())
  985. {
  986. this->DefineOneFunction(pnodeFnc, funcInfoParent);
  987. // The "x = function() {...}" case is being generated on the fly, during emission,
  988. // so the caller expects to be able to release this register.
  989. funcInfoParent->ReleaseLoc(pnodeFnc);
  990. pnodeFnc->location = Js::Constants::NoRegister;
  991. }
  992. };
  993. MapContainerScopeFunctions(pnodeParent, defineCheck);
  994. }
  995. void EmitAssignmentToFuncName(ParseNode *pnodeFnc, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfoParent)
  996. {
  997. // Assign the location holding the func object reference to the given name.
  998. Symbol *sym = pnodeFnc->sxFnc.pnodeName->sxVar.sym;
  999. if (sym != nullptr && !sym->GetFuncExpr())
  1000. {
  1001. if (sym->GetIsModuleExportStorage())
  1002. {
  1003. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  1004. }
  1005. else if (sym->GetIsGlobal())
  1006. {
  1007. Js::PropertyId propertyId = sym->GetPosition();
  1008. byteCodeGenerator->EmitGlobalFncDeclInit(pnodeFnc->location, propertyId, funcInfoParent);
  1009. if (byteCodeGenerator->GetFlags() & fscrEval && !funcInfoParent->GetIsStrictMode())
  1010. {
  1011. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  1012. }
  1013. }
  1014. else
  1015. {
  1016. if (sym->NeedsSlotAlloc(funcInfoParent))
  1017. {
  1018. if (!sym->GetHasNonCommittedReference() ||
  1019. (funcInfoParent->GetParsedFunctionBody()->DoStackNestedFunc()))
  1020. {
  1021. // No point in trying to optimize if there are no references before we have to commit to slot.
  1022. // And not safe to delay putting a stack function in the slot, since we may miss boxing.
  1023. sym->SetIsCommittedToSlot();
  1024. }
  1025. }
  1026. if (sym->GetScope()->GetFunc() != byteCodeGenerator->TopFuncInfo())
  1027. {
  1028. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  1029. }
  1030. else
  1031. {
  1032. byteCodeGenerator->EmitLocalPropInit(pnodeFnc->location, sym, funcInfoParent);
  1033. }
  1034. Symbol * fncScopeSym = sym->GetFuncScopeVarSym();
  1035. if (fncScopeSym)
  1036. {
  1037. if (fncScopeSym->GetIsGlobal() && byteCodeGenerator->GetFlags() & fscrEval)
  1038. {
  1039. Js::PropertyId propertyId = fncScopeSym->GetPosition();
  1040. byteCodeGenerator->EmitGlobalFncDeclInit(pnodeFnc->location, propertyId, funcInfoParent);
  1041. }
  1042. else
  1043. {
  1044. byteCodeGenerator->EmitPropStore(pnodeFnc->location, fncScopeSym, nullptr, funcInfoParent, false, false, /* isFncDeclVar */true);
  1045. }
  1046. }
  1047. }
  1048. }
  1049. }
  1050. Js::RegSlot ByteCodeGenerator::DefineOneFunction(ParseNode *pnodeFnc, FuncInfo *funcInfoParent, bool generateAssignment, Js::RegSlot regEnv, Js::RegSlot frameDisplayTemp)
  1051. {
  1052. Assert(pnodeFnc->nop == knopFncDecl);
  1053. funcInfoParent->AcquireLoc(pnodeFnc);
  1054. if (regEnv == Js::Constants::NoRegister)
  1055. {
  1056. // If the child needs a closure, find a heap-allocated frame to pass to it.
  1057. if (frameDisplayTemp != Js::Constants::NoRegister)
  1058. {
  1059. // We allocated a temp to hold a local frame display value. Use that.
  1060. // It's likely that the FD is on the stack, and we used the temp to load it back.
  1061. regEnv = frameDisplayTemp;
  1062. }
  1063. else if (funcInfoParent->frameDisplayRegister != Js::Constants::NoRegister)
  1064. {
  1065. // This function has built a frame display, so pass it down.
  1066. regEnv = funcInfoParent->frameDisplayRegister;
  1067. }
  1068. else
  1069. {
  1070. // This function has no captured locals but inherits a closure environment, so pass it down.
  1071. regEnv = funcInfoParent->GetEnvRegister();
  1072. }
  1073. regEnv = this->PrependLocalScopes(regEnv, Js::Constants::NoRegister, funcInfoParent);
  1074. }
  1075. // AssertMsg(funcInfo->nonLocalSymbols == 0 || regEnv != funcInfoParent->nullConstantRegister,
  1076. // "We need a closure for the nested function");
  1077. // 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
  1078. if (regEnv == funcInfoParent->frameDisplayRegister || regEnv == funcInfoParent->GetEnvRegister())
  1079. {
  1080. m_writer.NewFunction(pnodeFnc->location, pnodeFnc->sxFnc.nestedIndex, pnodeFnc->sxFnc.IsGenerator());
  1081. }
  1082. else
  1083. {
  1084. m_writer.NewInnerFunction(pnodeFnc->location, pnodeFnc->sxFnc.nestedIndex, regEnv, pnodeFnc->sxFnc.IsGenerator());
  1085. }
  1086. if (funcInfoParent->IsGlobalFunction() && (this->flags & fscrEval))
  1087. {
  1088. // A function declared at global scope in eval is untrackable,
  1089. // so make sure the caller's cached scope is invalidated.
  1090. this->funcEscapes = true;
  1091. }
  1092. else
  1093. {
  1094. if (pnodeFnc->sxFnc.IsDeclaration())
  1095. {
  1096. Symbol * funcSymbol = pnodeFnc->sxFnc.GetFuncSymbol();
  1097. if (funcSymbol)
  1098. {
  1099. // In the case where a let/const declaration is the same symbol name
  1100. // as the function declaration (shadowing case), the let/const var and
  1101. // the function declaration symbol are the same and share the same flags
  1102. // (particularly, sym->GetIsBlockVar() for this code path).
  1103. //
  1104. // For example:
  1105. // let a = 0; // <-- sym->GetIsBlockVar() = true
  1106. // function b(){} // <-- sym2->GetIsBlockVar() = false
  1107. //
  1108. // let x = 0; // <-- sym3->GetIsBlockVar() = true
  1109. // function x(){} // <-- sym3->GetIsBlockVar() = true
  1110. //
  1111. // In order to tell if the function is actually part
  1112. // of a block scope, we compare against the function scope here.
  1113. // Note that having a function with the same name as a let/const declaration
  1114. // is a redeclaration error, but we're pushing the fix for this out since it's
  1115. // a bit involved.
  1116. Assert(funcInfoParent->GetBodyScope() != nullptr && funcSymbol->GetScope() != nullptr);
  1117. bool isFunctionDeclarationInBlock = funcSymbol->GetIsBlockVar();
  1118. // Track all vars/lets/consts register slot function declarations.
  1119. if (ShouldTrackDebuggerMetadata()
  1120. // If this is a let binding function declaration at global level, we want to
  1121. // be sure to track the register location as well.
  1122. && !(funcInfoParent->IsGlobalFunction() && !isFunctionDeclarationInBlock))
  1123. {
  1124. if (!funcSymbol->IsInSlot(funcInfoParent))
  1125. {
  1126. funcInfoParent->byteCodeFunction->GetFunctionBody()->InsertSymbolToRegSlotList(funcSymbol->GetName(), pnodeFnc->location, funcInfoParent->varRegsCount);
  1127. }
  1128. }
  1129. if (isFunctionDeclarationInBlock)
  1130. {
  1131. // We only track inner let bindings for the debugger side.
  1132. this->TrackFunctionDeclarationPropertyForDebugger(funcSymbol, funcInfoParent);
  1133. }
  1134. }
  1135. }
  1136. }
  1137. if (pnodeFnc->sxFnc.IsDefaultModuleExport())
  1138. {
  1139. this->EmitAssignmentToDefaultModuleExport(pnodeFnc, funcInfoParent);
  1140. }
  1141. if (pnodeFnc->sxFnc.pnodeName == nullptr || !generateAssignment)
  1142. {
  1143. return regEnv;
  1144. }
  1145. EmitAssignmentToFuncName(pnodeFnc, this, funcInfoParent);
  1146. return regEnv;
  1147. }
  1148. void ByteCodeGenerator::DefineUserVars(FuncInfo *funcInfo)
  1149. {
  1150. // Initialize scope-wide variables on entry to the scope. TODO: optimize by detecting uses that are always reached
  1151. // by an existing initialization.
  1152. BOOL fGlobal = funcInfo->IsGlobalFunction();
  1153. ParseNode *pnode;
  1154. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1155. // Global declarations need a temp register to hold the init value, but the node shouldn't get a register.
  1156. // Just assign one on the fly and re-use it for all initializations.
  1157. Js::RegSlot tmpReg = fGlobal ? funcInfo->AcquireTmpRegister() : Js::Constants::NoRegister;
  1158. for (pnode = funcInfo->root->sxFnc.pnodeVars; pnode; pnode = pnode->sxVar.pnodeNext)
  1159. {
  1160. Symbol* sym = pnode->sxVar.sym;
  1161. if (sym != nullptr && !(pnode->sxVar.isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  1162. {
  1163. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  1164. {
  1165. // The init node was bound to the catch object, because it's inside a catch and has the
  1166. // same name as the catch object. But we want to define a user var at function scope,
  1167. // so find the right symbol. (We'll still assign the RHS value to the catch object symbol.)
  1168. // This also applies to a var declaration in the same scope as a let declaration.
  1169. #if DBG
  1170. if (!sym->GetIsCatch())
  1171. {
  1172. // Assert that catch cannot be at function scope and let and var at function scope is redeclaration error.
  1173. Assert(funcInfo->bodyScope != sym->GetScope());
  1174. }
  1175. #endif
  1176. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  1177. Assert(sym && !sym->GetIsCatch() && !sym->GetIsBlockVar());
  1178. }
  1179. if (sym->GetSymbolType() == STVariable)
  1180. {
  1181. if (fGlobal)
  1182. {
  1183. Js::PropertyId propertyId = sym->EnsurePosition(this);
  1184. // We do need to initialize some globals to avoid JS errors on loading undefined variables.
  1185. // But we first need to make sure we're not trashing built-ins.
  1186. if (this->flags & fscrEval)
  1187. {
  1188. if (funcInfo->byteCodeFunction->GetIsStrictMode())
  1189. {
  1190. // Check/Init the property of the frame object
  1191. this->m_writer.ElementRootU(Js::OpCode::LdLocalElemUndef,
  1192. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1193. }
  1194. else
  1195. {
  1196. // The check and the init involve the first element in the scope chain.
  1197. this->m_writer.ElementScopedU(
  1198. Js::OpCode::LdElemUndefScoped, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1199. }
  1200. }
  1201. else if (sym->GetIsModuleExportStorage())
  1202. {
  1203. Js::RegSlot reg = funcInfo->AcquireTmpRegister();
  1204. this->m_writer.Reg1(Js::OpCode::LdUndef, reg);
  1205. EmitModuleExportAccess(sym, Js::OpCode::StModuleSlot, reg, funcInfo);
  1206. funcInfo->ReleaseTmpRegister(reg);
  1207. }
  1208. else
  1209. {
  1210. this->m_writer.ElementU(Js::OpCode::LdElemUndef, ByteCodeGenerator::RootObjectRegister,
  1211. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1212. }
  1213. }
  1214. else if (!sym->GetIsArguments())
  1215. {
  1216. if (sym->NeedsSlotAlloc(funcInfo))
  1217. {
  1218. if (!sym->GetHasNonCommittedReference() ||
  1219. (sym->GetHasFuncAssignment() && funcInfo->GetParsedFunctionBody()->DoStackNestedFunc()))
  1220. {
  1221. // No point in trying to optimize if there are no references before we have to commit to slot.
  1222. // And not safe to delay putting a stack function in the slot, since we may miss boxing.
  1223. sym->SetIsCommittedToSlot();
  1224. }
  1225. }
  1226. if ((!sym->GetHasInit() && !sym->IsInSlot(funcInfo)) ||
  1227. (funcInfo->bodyScope->GetIsObject() && !funcInfo->GetHasCachedScope()))
  1228. {
  1229. Js::RegSlot reg = sym->GetLocation();
  1230. if (reg == Js::Constants::NoRegister)
  1231. {
  1232. Assert(sym->IsInSlot(funcInfo));
  1233. reg = funcInfo->AcquireTmpRegister();
  1234. }
  1235. this->m_writer.Reg1(Js::OpCode::LdUndef, reg);
  1236. this->EmitLocalPropInit(reg, sym, funcInfo);
  1237. if (ShouldTrackDebuggerMetadata() && !sym->GetHasInit() && !sym->IsInSlot(funcInfo))
  1238. {
  1239. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), reg, funcInfo->varRegsCount);
  1240. }
  1241. funcInfo->ReleaseTmpRegister(reg);
  1242. }
  1243. }
  1244. else if (ShouldTrackDebuggerMetadata())
  1245. {
  1246. if (!sym->GetHasInit() && !sym->IsInSlot(funcInfo))
  1247. {
  1248. Js::RegSlot reg = sym->GetLocation();
  1249. if (reg != Js::Constants::NoRegister)
  1250. {
  1251. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), reg, funcInfo->varRegsCount);
  1252. }
  1253. }
  1254. }
  1255. sym->SetHasInit(TRUE);
  1256. }
  1257. }
  1258. }
  1259. if (tmpReg != Js::Constants::NoRegister)
  1260. {
  1261. funcInfo->ReleaseTmpRegister(tmpReg);
  1262. }
  1263. for (int i = 0; i < funcInfo->nonUserNonTempRegistersToInitialize.Count(); ++i)
  1264. {
  1265. m_writer.Reg1(Js::OpCode::LdUndef, funcInfo->nonUserNonTempRegistersToInitialize.Item(i));
  1266. }
  1267. }
  1268. void ByteCodeGenerator::InitBlockScopedNonTemps(ParseNode *pnode, FuncInfo *funcInfo)
  1269. {
  1270. // Initialize all non-temp register variables on entry to the enclosing func - in particular,
  1271. // those with lifetimes that begin after the start of user code and may not be initialized normally.
  1272. // This protects us from, for instance, trying to restore garbage on bailout.
  1273. // It was originally done in debugger mode only, but we do it always to avoid issues with boxing
  1274. // garbage on exit from jitted loop bodies.
  1275. while (pnode)
  1276. {
  1277. switch (pnode->nop)
  1278. {
  1279. case knopFncDecl:
  1280. {
  1281. // If this is a block-scoped function, initialize it.
  1282. ParseNode *pnodeName = pnode->sxFnc.pnodeName;
  1283. if (!pnode->sxFnc.IsMethod() && pnodeName && pnodeName->nop == knopVarDecl)
  1284. {
  1285. Symbol *sym = pnodeName->sxVar.sym;
  1286. Assert(sym);
  1287. if (sym->GetLocation() != Js::Constants::NoRegister &&
  1288. sym->GetScope()->IsBlockScope(funcInfo) &&
  1289. sym->GetScope()->GetFunc() == funcInfo)
  1290. {
  1291. this->m_writer.Reg1(Js::OpCode::LdUndef, sym->GetLocation());
  1292. }
  1293. }
  1294. // No need to recurse to the nested scopes, as they belong to a nested function.
  1295. pnode = pnode->sxFnc.pnodeNext;
  1296. break;
  1297. }
  1298. case knopBlock:
  1299. {
  1300. Scope *scope = pnode->sxBlock.scope;
  1301. if (scope)
  1302. {
  1303. if (scope->IsBlockScope(funcInfo))
  1304. {
  1305. Js::RegSlot scopeLoc = scope->GetLocation();
  1306. if (scopeLoc != Js::Constants::NoRegister && !funcInfo->IsTmpReg(scopeLoc))
  1307. {
  1308. this->m_writer.Reg1(Js::OpCode::LdUndef, scopeLoc);
  1309. }
  1310. }
  1311. auto fnInit = [this, funcInfo](ParseNode *pnode)
  1312. {
  1313. Symbol *sym = pnode->sxVar.sym;
  1314. if (!sym->IsInSlot(funcInfo) && !sym->GetIsGlobal())
  1315. {
  1316. this->m_writer.Reg1(Js::OpCode::InitUndecl, pnode->sxVar.sym->GetLocation());
  1317. }
  1318. };
  1319. IterateBlockScopedVariables(pnode, fnInit);
  1320. }
  1321. InitBlockScopedNonTemps(pnode->sxBlock.pnodeScopes, funcInfo);
  1322. pnode = pnode->sxBlock.pnodeNext;
  1323. break;
  1324. }
  1325. case knopCatch:
  1326. InitBlockScopedNonTemps(pnode->sxCatch.pnodeScopes, funcInfo);
  1327. pnode = pnode->sxCatch.pnodeNext;
  1328. break;
  1329. case knopWith:
  1330. {
  1331. Js::RegSlot withLoc = pnode->location;
  1332. AssertMsg(withLoc != Js::Constants::NoRegister && !funcInfo->IsTmpReg(withLoc),
  1333. "We should put with objects at known stack locations in debug mode");
  1334. this->m_writer.Reg1(Js::OpCode::LdUndef, withLoc);
  1335. InitBlockScopedNonTemps(pnode->sxWith.pnodeScopes, funcInfo);
  1336. pnode = pnode->sxWith.pnodeNext;
  1337. break;
  1338. }
  1339. default:
  1340. Assert(false);
  1341. return;
  1342. }
  1343. }
  1344. }
  1345. void ByteCodeGenerator::EmitScopeObjectInit(FuncInfo *funcInfo)
  1346. {
  1347. Assert(!funcInfo->byteCodeFunction->GetFunctionBody()->DoStackNestedFunc());
  1348. if (!funcInfo->GetHasCachedScope() /* || forcing scope/inner func caching */)
  1349. {
  1350. return;
  1351. }
  1352. uint slotCount = funcInfo->bodyScope->GetScopeSlotCount();
  1353. uint cachedFuncCount = 0;
  1354. Js::PropertyId firstFuncSlot = Js::Constants::NoProperty;
  1355. Js::PropertyId firstVarSlot = Js::Constants::NoProperty;
  1356. uint extraAlloc = (slotCount + Js::ActivationObjectEx::ExtraSlotCount()) * sizeof(Js::PropertyId);
  1357. // Create and fill the array of local property ID's.
  1358. // They all have slots assigned to them already (if they need them): see StartEmitFunction.
  1359. Js::PropertyIdArray *propIds = AnewPlus(alloc, extraAlloc, Js::PropertyIdArray, slotCount);
  1360. ParseNode *pnodeFnc = funcInfo->root;
  1361. ParseNode *pnode;
  1362. Symbol *sym;
  1363. if (funcInfo->GetFuncExprNameReference() && pnodeFnc->sxFnc.GetFuncSymbol()->GetScope() == funcInfo->GetBodyScope())
  1364. {
  1365. Symbol::SaveToPropIdArray(pnodeFnc->sxFnc.GetFuncSymbol(), propIds, this);
  1366. }
  1367. if (funcInfo->GetHasArguments())
  1368. {
  1369. // Because the arguments object can access all instances of same-named formals ("function(x,x){...}"),
  1370. // be sure we initialize any duplicate appearances of a formal parameter to "NoProperty".
  1371. Js::PropertyId slot = 0;
  1372. auto initArg = [&](ParseNode *pnode)
  1373. {
  1374. if (pnode->IsVarLetOrConst())
  1375. {
  1376. Symbol *sym = pnode->sxVar.sym;
  1377. Assert(sym);
  1378. if (sym->GetScopeSlot() == slot)
  1379. {
  1380. // This is the last appearance of the formal, so record the ID.
  1381. Symbol::SaveToPropIdArray(sym, propIds, this);
  1382. }
  1383. else
  1384. {
  1385. // This is an earlier duplicate appearance of the formal, so use NoProperty as a placeholder
  1386. // since this slot can't be accessed by name.
  1387. Assert(sym->GetScopeSlot() != Js::Constants::NoProperty && sym->GetScopeSlot() > slot);
  1388. propIds->elements[slot] = Js::Constants::NoProperty;
  1389. }
  1390. }
  1391. else
  1392. {
  1393. // This is for patterns
  1394. propIds->elements[slot] = Js::Constants::NoProperty;
  1395. }
  1396. slot++;
  1397. };
  1398. MapFormalsWithoutRest(pnodeFnc, initArg);
  1399. // If the rest is in the slot - we need to keep that slot.
  1400. if (pnodeFnc->sxFnc.pnodeRest != nullptr && pnodeFnc->sxFnc.pnodeRest->sxVar.sym->IsInSlot(funcInfo))
  1401. {
  1402. Symbol::SaveToPropIdArray(pnodeFnc->sxFnc.pnodeRest->sxVar.sym, propIds, this);
  1403. }
  1404. }
  1405. else
  1406. {
  1407. MapFormals(pnodeFnc, [&](ParseNode *pnode)
  1408. {
  1409. if (pnode->IsVarLetOrConst())
  1410. {
  1411. Symbol::SaveToPropIdArray(pnode->sxVar.sym, propIds, this);
  1412. }
  1413. });
  1414. }
  1415. auto saveFunctionVarsToPropIdArray = [&](ParseNode *pnodeFunction)
  1416. {
  1417. if (pnodeFunction->sxFnc.IsDeclaration())
  1418. {
  1419. ParseNode *pnodeName = pnodeFunction->sxFnc.pnodeName;
  1420. if (pnodeName != nullptr)
  1421. {
  1422. while (pnodeName->nop == knopList)
  1423. {
  1424. if (pnodeName->sxBin.pnode1->nop == knopVarDecl)
  1425. {
  1426. sym = pnodeName->sxBin.pnode1->sxVar.sym;
  1427. if (sym)
  1428. {
  1429. Symbol::SaveToPropIdArray(sym, propIds, this, &firstFuncSlot);
  1430. }
  1431. }
  1432. pnodeName = pnodeName->sxBin.pnode2;
  1433. }
  1434. if (pnodeName->nop == knopVarDecl)
  1435. {
  1436. sym = pnodeName->sxVar.sym;
  1437. if (sym)
  1438. {
  1439. Symbol::SaveToPropIdArray(sym, propIds, this, &firstFuncSlot);
  1440. cachedFuncCount++;
  1441. }
  1442. }
  1443. }
  1444. }
  1445. };
  1446. MapContainerScopeFunctions(pnodeFnc, saveFunctionVarsToPropIdArray);
  1447. for (pnode = pnodeFnc->sxFnc.pnodeVars; pnode; pnode = pnode->sxVar.pnodeNext)
  1448. {
  1449. sym = pnode->sxVar.sym;
  1450. if (!(pnode->sxVar.isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  1451. {
  1452. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  1453. {
  1454. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  1455. }
  1456. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1457. }
  1458. }
  1459. ParseNode *pnodeBlock = pnodeFnc->sxFnc.pnodeScopes;
  1460. for (pnode = pnodeBlock->sxBlock.pnodeLexVars; pnode; pnode = pnode->sxVar.pnodeNext)
  1461. {
  1462. sym = pnode->sxVar.sym;
  1463. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1464. }
  1465. pnodeBlock = pnodeFnc->sxFnc.pnodeBodyScope;
  1466. for (pnode = pnodeBlock->sxBlock.pnodeLexVars; pnode; pnode = pnode->sxVar.pnodeNext)
  1467. {
  1468. sym = pnode->sxVar.sym;
  1469. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1470. }
  1471. if (funcInfo->thisScopeSlot != Js::Constants::NoRegister)
  1472. {
  1473. propIds->elements[funcInfo->thisScopeSlot] = Js::PropertyIds::_lexicalThisSlotSymbol;
  1474. }
  1475. if (funcInfo->newTargetScopeSlot != Js::Constants::NoRegister)
  1476. {
  1477. propIds->elements[funcInfo->newTargetScopeSlot] = Js::PropertyIds::_lexicalNewTargetSymbol;
  1478. }
  1479. if (funcInfo->superScopeSlot != Js::Constants::NoRegister)
  1480. {
  1481. propIds->elements[funcInfo->superScopeSlot] = Js::PropertyIds::_superReferenceSymbol;
  1482. }
  1483. if (funcInfo->superCtorScopeSlot != Js::Constants::NoRegister)
  1484. {
  1485. propIds->elements[funcInfo->superCtorScopeSlot] = Js::PropertyIds::_superCtorReferenceSymbol;
  1486. }
  1487. // Write the first func slot and first var slot into the auxiliary data
  1488. Js::PropertyId *slots = propIds->elements + slotCount;
  1489. slots[0] = cachedFuncCount;
  1490. slots[1] = firstFuncSlot;
  1491. slots[2] = firstVarSlot;
  1492. slots[3] = funcInfo->GetParsedFunctionBody()->NewObjectLiteral();
  1493. propIds->hasNonSimpleParams = funcInfo->root->sxFnc.HasNonSimpleParameterList();
  1494. funcInfo->localPropIdOffset = m_writer.InsertAuxiliaryData(propIds, sizeof(Js::PropertyIdArray) + extraAlloc);
  1495. Assert(funcInfo->localPropIdOffset == 0);
  1496. funcInfo->GetParsedFunctionBody()->SetHasCachedScopePropIds(true);
  1497. AdeletePlus(alloc, extraAlloc, propIds);
  1498. }
  1499. void ByteCodeGenerator::SetClosureRegisters(FuncInfo* funcInfo, Js::FunctionBody* byteCodeFunction)
  1500. {
  1501. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  1502. {
  1503. byteCodeFunction->MapAndSetLocalFrameDisplayRegister(funcInfo->frameDisplayRegister);
  1504. }
  1505. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  1506. {
  1507. byteCodeFunction->MapAndSetLocalClosureRegister(funcInfo->frameObjRegister);
  1508. byteCodeFunction->SetHasScopeObject(true);
  1509. }
  1510. else if (funcInfo->frameSlotsRegister != Js::Constants::NoRegister)
  1511. {
  1512. byteCodeFunction->MapAndSetLocalClosureRegister(funcInfo->frameSlotsRegister);
  1513. }
  1514. if (funcInfo->paramSlotsRegister != Js::Constants::NoRegister)
  1515. {
  1516. byteCodeFunction->MapAndSetParamClosureRegister(funcInfo->paramSlotsRegister);
  1517. }
  1518. }
  1519. void ByteCodeGenerator::FinalizeRegisters(FuncInfo * funcInfo, Js::FunctionBody * byteCodeFunction)
  1520. {
  1521. if (byteCodeFunction->IsGenerator())
  1522. {
  1523. // EmitYield uses 'false' to create the IteratorResult object
  1524. funcInfo->AssignFalseConstRegister();
  1525. }
  1526. if (funcInfo->NeedEnvRegister())
  1527. {
  1528. bool constReg = !funcInfo->GetIsTopLevelEventHandler() && funcInfo->IsGlobalFunction() && !(this->flags & fscrEval);
  1529. funcInfo->AssignEnvRegister(constReg);
  1530. }
  1531. // Set the function body's constant count before emitting anything so that the byte code writer
  1532. // can distinguish constants from variables.
  1533. byteCodeFunction->CheckAndSetConstantCount(funcInfo->constRegsCount);
  1534. this->SetClosureRegisters(funcInfo, byteCodeFunction);
  1535. if (this->IsInDebugMode())
  1536. {
  1537. // Give permanent registers to the inner scopes in debug mode.
  1538. uint innerScopeCount = funcInfo->InnerScopeCount();
  1539. byteCodeFunction->SetInnerScopeCount(innerScopeCount);
  1540. if (innerScopeCount)
  1541. {
  1542. funcInfo->SetFirstInnerScopeReg(funcInfo->NextVarRegister());
  1543. for (uint i = 1; i < innerScopeCount; i++)
  1544. {
  1545. funcInfo->NextVarRegister();
  1546. }
  1547. }
  1548. }
  1549. // NOTE: The FB expects the yield reg to be the final non-temp.
  1550. if (byteCodeFunction->IsGenerator())
  1551. {
  1552. funcInfo->AssignYieldRegister();
  1553. }
  1554. Js::RegSlot firstTmpReg = funcInfo->varRegsCount;
  1555. funcInfo->SetFirstTmpReg(firstTmpReg);
  1556. byteCodeFunction->SetFirstTmpReg(funcInfo->RegCount());
  1557. }
  1558. void ByteCodeGenerator::InitScopeSlotArray(FuncInfo * funcInfo)
  1559. {
  1560. // Record slots info for ScopeSlots/ScopeObject.
  1561. uint scopeSlotCount = funcInfo->bodyScope->GetScopeSlotCount();
  1562. Assert(funcInfo->paramScope == nullptr || funcInfo->paramScope->GetScopeSlotCount() == 0 || !funcInfo->paramScope->GetCanMergeWithBodyScope());
  1563. uint scopeSlotCountForParamScope = funcInfo->paramScope != nullptr ? funcInfo->paramScope->GetScopeSlotCount() : 0;
  1564. if (scopeSlotCount == 0 && scopeSlotCountForParamScope == 0)
  1565. {
  1566. return;
  1567. }
  1568. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1569. if (scopeSlotCount > 0 || scopeSlotCountForParamScope > 0)
  1570. {
  1571. byteCodeFunction->SetScopeSlotArraySizes(scopeSlotCount, scopeSlotCountForParamScope);
  1572. }
  1573. // TODO: Need to add property ids for the case when scopeSlotCountForParamSCope is non-zero
  1574. if (scopeSlotCount)
  1575. {
  1576. Js::PropertyId *propertyIdsForScopeSlotArray = RecyclerNewArrayLeafZ(scriptContext->GetRecycler(), Js::PropertyId, scopeSlotCount);
  1577. byteCodeFunction->SetPropertyIdsForScopeSlotArray(propertyIdsForScopeSlotArray, scopeSlotCount, scopeSlotCountForParamScope);
  1578. AssertMsg(!byteCodeFunction->IsReparsed() || byteCodeFunction->m_wasEverAsmjsMode || byteCodeFunction->scopeSlotArraySize == scopeSlotCount,
  1579. "The slot array size is different between debug and non-debug mode");
  1580. #if DEBUG
  1581. for (UINT i = 0; i < scopeSlotCount; i++)
  1582. {
  1583. propertyIdsForScopeSlotArray[i] = Js::Constants::NoProperty;
  1584. }
  1585. #endif
  1586. auto setPropIdsForScopeSlotArray = [funcInfo, propertyIdsForScopeSlotArray](Symbol *const sym)
  1587. {
  1588. if (sym->NeedsSlotAlloc(funcInfo))
  1589. {
  1590. // All properties should get correct propertyId here.
  1591. Assert(sym->HasScopeSlot()); // We can't allocate scope slot now. Any symbol needing scope slot must have allocated it before this point.
  1592. propertyIdsForScopeSlotArray[sym->GetScopeSlot()] = sym->EnsurePosition(funcInfo);
  1593. }
  1594. };
  1595. funcInfo->GetBodyScope()->ForEachSymbol(setPropIdsForScopeSlotArray);
  1596. if (funcInfo->thisScopeSlot != Js::Constants::NoRegister)
  1597. {
  1598. propertyIdsForScopeSlotArray[funcInfo->thisScopeSlot] = Js::PropertyIds::_lexicalThisSlotSymbol;
  1599. }
  1600. if (funcInfo->newTargetScopeSlot != Js::Constants::NoRegister)
  1601. {
  1602. propertyIdsForScopeSlotArray[funcInfo->newTargetScopeSlot] = Js::PropertyIds::_lexicalNewTargetSymbol;
  1603. }
  1604. if (funcInfo->superScopeSlot != Js::Constants::NoRegister)
  1605. {
  1606. propertyIdsForScopeSlotArray[funcInfo->superScopeSlot] = Js::PropertyIds::_superReferenceSymbol;
  1607. }
  1608. if (funcInfo->superCtorScopeSlot != Js::Constants::NoRegister)
  1609. {
  1610. propertyIdsForScopeSlotArray[funcInfo->superCtorScopeSlot] = Js::PropertyIds::_superCtorReferenceSymbol;
  1611. }
  1612. #if DEBUG
  1613. for (UINT i = 0; i < scopeSlotCount; i++)
  1614. {
  1615. Assert(propertyIdsForScopeSlotArray[i] != Js::Constants::NoProperty
  1616. || funcInfo->frameObjRegister != Js::Constants::NoRegister); // ScopeObject may have unassigned entries, e.g. for same-named parameters
  1617. }
  1618. #endif
  1619. }
  1620. }
  1621. // temporarily load all constants and special registers in a single block
  1622. void ByteCodeGenerator::LoadAllConstants(FuncInfo *funcInfo)
  1623. {
  1624. Symbol *sym;
  1625. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1626. byteCodeFunction->CreateConstantTable();
  1627. if (funcInfo->nullConstantRegister != Js::Constants::NoRegister)
  1628. {
  1629. byteCodeFunction->RecordNullObject(byteCodeFunction->MapRegSlot(funcInfo->nullConstantRegister));
  1630. }
  1631. if (funcInfo->undefinedConstantRegister != Js::Constants::NoRegister)
  1632. {
  1633. byteCodeFunction->RecordUndefinedObject(byteCodeFunction->MapRegSlot(funcInfo->undefinedConstantRegister));
  1634. }
  1635. if (funcInfo->trueConstantRegister != Js::Constants::NoRegister)
  1636. {
  1637. byteCodeFunction->RecordTrueObject(byteCodeFunction->MapRegSlot(funcInfo->trueConstantRegister));
  1638. }
  1639. if (funcInfo->falseConstantRegister != Js::Constants::NoRegister)
  1640. {
  1641. byteCodeFunction->RecordFalseObject(byteCodeFunction->MapRegSlot(funcInfo->falseConstantRegister));
  1642. }
  1643. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  1644. {
  1645. m_writer.RecordObjectRegister(funcInfo->frameObjRegister);
  1646. if (!funcInfo->GetApplyEnclosesArgs())
  1647. {
  1648. this->EmitScopeObjectInit(funcInfo);
  1649. }
  1650. #if DBG
  1651. uint count = 0;
  1652. funcInfo->GetBodyScope()->ForEachSymbol([&](Symbol *const sym)
  1653. {
  1654. if (sym->NeedsSlotAlloc(funcInfo))
  1655. {
  1656. // All properties should get correct propertyId here.
  1657. count++;
  1658. }
  1659. });
  1660. if (funcInfo->GetParamScope() != nullptr)
  1661. {
  1662. funcInfo->GetParamScope()->ForEachSymbol([&](Symbol *const sym)
  1663. {
  1664. if (sym->NeedsSlotAlloc(funcInfo))
  1665. {
  1666. // All properties should get correct propertyId here.
  1667. count++;
  1668. }
  1669. });
  1670. }
  1671. // A reparse should result in the same size of the activation object.
  1672. // Exclude functions which were created from the ByteCodeCache.
  1673. AssertMsg(!byteCodeFunction->IsReparsed() || byteCodeFunction->HasGeneratedFromByteCodeCache() ||
  1674. byteCodeFunction->scopeObjectSize == count || byteCodeFunction->m_wasEverAsmjsMode,
  1675. "The activation object size is different between debug and non-debug mode");
  1676. byteCodeFunction->scopeObjectSize = count;
  1677. #endif
  1678. }
  1679. else if (funcInfo->frameSlotsRegister != Js::Constants::NoRegister)
  1680. {
  1681. int scopeSlotCount = funcInfo->bodyScope->GetScopeSlotCount();
  1682. int paramSlotCount = funcInfo->paramScope->GetScopeSlotCount();
  1683. if (scopeSlotCount == 0 && paramSlotCount == 0)
  1684. {
  1685. AssertMsg(funcInfo->frameDisplayRegister != Js::Constants::NoRegister, "Why do we need scope slots?");
  1686. m_writer.Reg1(Js::OpCode::LdC_A_Null, funcInfo->frameSlotsRegister);
  1687. }
  1688. }
  1689. if (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject())
  1690. {
  1691. byteCodeFunction->MapAndSetFuncExprScopeRegister(funcInfo->funcExprScope->GetLocation());
  1692. byteCodeFunction->SetEnvDepth((uint16)-1);
  1693. }
  1694. bool thisLoadedFromParams = false;
  1695. if (funcInfo->NeedEnvRegister())
  1696. {
  1697. byteCodeFunction->MapAndSetEnvRegister(funcInfo->GetEnvRegister());
  1698. if (funcInfo->GetIsTopLevelEventHandler())
  1699. {
  1700. byteCodeFunction->MapAndSetThisRegisterForEventHandler(funcInfo->thisPointerRegister);
  1701. // The environment is the namespace hierarchy starting with "this".
  1702. Assert(!funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1703. thisLoadedFromParams = true;
  1704. this->InvalidateCachedOuterScopes(funcInfo);
  1705. }
  1706. else if (funcInfo->IsGlobalFunction() && !(this->flags & fscrEval))
  1707. {
  1708. Assert(funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1709. if (funcInfo->GetIsStrictMode())
  1710. {
  1711. byteCodeFunction->RecordStrictNullDisplayConstant(byteCodeFunction->MapRegSlot(funcInfo->GetEnvRegister()));
  1712. }
  1713. else
  1714. {
  1715. byteCodeFunction->RecordNullDisplayConstant(byteCodeFunction->MapRegSlot(funcInfo->GetEnvRegister()));
  1716. }
  1717. }
  1718. else
  1719. {
  1720. // environment may be required to load "this"
  1721. Assert(!funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1722. this->InvalidateCachedOuterScopes(funcInfo);
  1723. }
  1724. }
  1725. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  1726. {
  1727. m_writer.RecordFrameDisplayRegister(funcInfo->frameDisplayRegister);
  1728. }
  1729. // new.target may be used to construct the 'this' register so make sure to load it first
  1730. if (funcInfo->newTargetRegister != Js::Constants::NoRegister)
  1731. {
  1732. this->LoadNewTargetObject(funcInfo);
  1733. }
  1734. if (funcInfo->thisPointerRegister != Js::Constants::NoRegister)
  1735. {
  1736. this->LoadThisObject(funcInfo, thisLoadedFromParams);
  1737. }
  1738. this->RecordAllIntConstants(funcInfo);
  1739. this->RecordAllStrConstants(funcInfo);
  1740. this->RecordAllStringTemplateCallsiteConstants(funcInfo);
  1741. funcInfo->doubleConstantToRegister.Map([byteCodeFunction](double d, Js::RegSlot location)
  1742. {
  1743. byteCodeFunction->RecordFloatConstant(byteCodeFunction->MapRegSlot(location), d);
  1744. });
  1745. if (funcInfo->GetHasArguments())
  1746. {
  1747. sym = funcInfo->GetArgumentsSymbol();
  1748. Assert(sym);
  1749. Assert(funcInfo->GetHasHeapArguments());
  1750. if (funcInfo->GetCallsEval() || (!funcInfo->GetApplyEnclosesArgs()))
  1751. {
  1752. this->LoadHeapArguments(funcInfo);
  1753. }
  1754. }
  1755. else if (!funcInfo->IsGlobalFunction() && !IsInNonDebugMode())
  1756. {
  1757. uint count = funcInfo->inArgsCount + (funcInfo->root->sxFnc.pnodeRest != nullptr ? 1 : 0) - 1;
  1758. if (count != 0)
  1759. {
  1760. Js::PropertyIdArray *propIds = RecyclerNewPlus(scriptContext->GetRecycler(), count * sizeof(Js::PropertyId), Js::PropertyIdArray, count);
  1761. GetFormalArgsArray(this, funcInfo, propIds);
  1762. byteCodeFunction->SetPropertyIdsOfFormals(propIds);
  1763. }
  1764. }
  1765. //
  1766. // If the function is a function expression with a name,
  1767. // load the function object at runtime to its activation object.
  1768. //
  1769. sym = funcInfo->root->sxFnc.GetFuncSymbol();
  1770. bool funcExprWithName = !funcInfo->IsGlobalFunction() && sym && sym->GetFuncExpr();
  1771. if (funcExprWithName)
  1772. {
  1773. if (funcInfo->GetFuncExprNameReference() ||
  1774. (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject()))
  1775. {
  1776. //
  1777. // x = function f(...) { ... }
  1778. // A named function expression's name (Symbol:f) belongs to the enclosing scope.
  1779. // Thus there are no uses of 'f' within the scope of the function (as references to 'f'
  1780. // are looked up in the closure). So, we can't use f's register as it is from the enclosing
  1781. // scope's register namespace. So use a tmp register.
  1782. // In ES5 mode though 'f' is *not* a part of the enclosing scope. So we always assign 'f' a register
  1783. // from it's register namespace, which LdFuncExpr can use.
  1784. //
  1785. Js::RegSlot ldFuncExprDst = sym->GetLocation();
  1786. this->m_writer.Reg1(Js::OpCode::LdFuncExpr, ldFuncExprDst);
  1787. if (sym->IsInSlot(funcInfo))
  1788. {
  1789. Assert(!this->TopFuncInfo()->GetParsedFunctionBody()->DoStackNestedFunc());
  1790. Js::RegSlot scopeLocation;
  1791. AnalysisAssert(funcInfo->funcExprScope);
  1792. if (funcInfo->funcExprScope->GetIsObject())
  1793. {
  1794. scopeLocation = funcInfo->funcExprScope->GetLocation();
  1795. this->m_writer.Property(Js::OpCode::StFuncExpr, sym->GetLocation(), scopeLocation,
  1796. funcInfo->FindOrAddReferencedPropertyId(sym->GetPosition()));
  1797. }
  1798. else
  1799. {
  1800. this->m_writer.ElementU(Js::OpCode::StLocalFuncExpr, sym->GetLocation(),
  1801. funcInfo->FindOrAddReferencedPropertyId(sym->GetPosition()));
  1802. }
  1803. }
  1804. else if (ShouldTrackDebuggerMetadata())
  1805. {
  1806. funcInfo->byteCodeFunction->GetFunctionBody()->InsertSymbolToRegSlotList(sym->GetName(), sym->GetLocation(), funcInfo->varRegsCount);
  1807. }
  1808. }
  1809. }
  1810. }
  1811. void ByteCodeGenerator::InvalidateCachedOuterScopes(FuncInfo *funcInfo)
  1812. {
  1813. Assert(funcInfo->GetEnvRegister() != Js::Constants::NoRegister);
  1814. // Walk the scope stack, from funcInfo outward, looking for scopes that have been cached.
  1815. Scope *scope = funcInfo->GetBodyScope()->GetEnclosingScope();
  1816. uint32 envIndex = 0;
  1817. while (scope && scope->GetFunc() == funcInfo)
  1818. {
  1819. // Skip over FuncExpr Scope and parameter scope for current funcInfo to get to the first enclosing scope of the outer function.
  1820. scope = scope->GetEnclosingScope();
  1821. }
  1822. for (; scope; scope = scope->GetEnclosingScope())
  1823. {
  1824. FuncInfo *func = scope->GetFunc();
  1825. if (scope == func->GetBodyScope())
  1826. {
  1827. if (func->Escapes() && func->GetHasCachedScope())
  1828. {
  1829. Assert(scope->GetIsObject());
  1830. this->m_writer.Unsigned1(Js::OpCode::InvalCachedScope, envIndex);
  1831. }
  1832. }
  1833. if (scope->GetMustInstantiate())
  1834. {
  1835. envIndex++;
  1836. }
  1837. }
  1838. }
  1839. void ByteCodeGenerator::LoadThisObject(FuncInfo *funcInfo, bool thisLoadedFromParams)
  1840. {
  1841. if (this->scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled() && funcInfo->IsClassConstructor())
  1842. {
  1843. // Derived class constructors initialize 'this' to be Undecl
  1844. // - we'll check this value during a super call and during 'this' access
  1845. // Base class constructors initialize 'this' to a new object using new.target
  1846. if (funcInfo->IsBaseClassConstructor())
  1847. {
  1848. EmitBaseClassConstructorThisObject(funcInfo);
  1849. }
  1850. else
  1851. {
  1852. this->m_writer.Reg1(Js::OpCode::InitUndecl, funcInfo->thisPointerRegister);
  1853. }
  1854. }
  1855. else if (!funcInfo->IsGlobalFunction() || (this->flags & fscrEval))
  1856. {
  1857. //
  1858. // thisLoadedFromParams would be true for the event Handler case,
  1859. // "this" would have been loaded from parameters to put in the environment
  1860. //
  1861. if (!thisLoadedFromParams && !funcInfo->IsLambda())
  1862. {
  1863. m_writer.ArgIn0(funcInfo->thisPointerRegister);
  1864. }
  1865. if (!(this->flags & fscrEval) || !funcInfo->IsGlobalFunction())
  1866. {
  1867. // we don't want to emit 'this' for eval, because 'this' value in eval is equal to 'this' value of caller
  1868. // and does not depend on "use strict" inside of eval.
  1869. // so we pass 'this' directly in GlobalObject::EntryEval()
  1870. EmitThis(funcInfo, funcInfo->thisPointerRegister);
  1871. }
  1872. }
  1873. else
  1874. {
  1875. Assert(funcInfo->IsGlobalFunction());
  1876. Js::RegSlot root = funcInfo->nullConstantRegister;
  1877. EmitThis(funcInfo, root);
  1878. }
  1879. }
  1880. void ByteCodeGenerator::LoadNewTargetObject(FuncInfo *funcInfo)
  1881. {
  1882. if (funcInfo->IsClassConstructor())
  1883. {
  1884. Assert(!funcInfo->IsLambda());
  1885. m_writer.ArgIn0(funcInfo->newTargetRegister);
  1886. }
  1887. else if (funcInfo->IsLambda() && !(this->flags & fscrEval))
  1888. {
  1889. Scope *scope;
  1890. Js::PropertyId envIndex = -1;
  1891. GetEnclosingNonLambdaScope(funcInfo, scope, envIndex);
  1892. if (scope->GetFunc()->IsGlobalFunction())
  1893. {
  1894. m_writer.Reg1(Js::OpCode::LdUndef, funcInfo->newTargetRegister);
  1895. }
  1896. else
  1897. {
  1898. Js::PropertyId slot = scope->GetFunc()->newTargetScopeSlot;
  1899. EmitInternalScopedSlotLoad(funcInfo, scope, envIndex, slot, funcInfo->newTargetRegister);
  1900. }
  1901. }
  1902. else if (this->flags & fscrEval)
  1903. {
  1904. Js::RegSlot scopeLocation;
  1905. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  1906. {
  1907. scopeLocation = funcInfo->frameDisplayRegister;
  1908. }
  1909. else if (funcInfo->NeedEnvRegister())
  1910. {
  1911. scopeLocation = funcInfo->GetEnvRegister();
  1912. }
  1913. else
  1914. {
  1915. // If this eval doesn't have environment register or frame display register, we didn't capture anything from a class constructor.
  1916. m_writer.Reg1(Js::OpCode::LdNewTarget, funcInfo->newTargetRegister);
  1917. return;
  1918. }
  1919. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, Js::PropertyIds::_lexicalNewTargetSymbol, false, false);
  1920. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, funcInfo->newTargetRegister, cacheId);
  1921. }
  1922. else if (funcInfo->IsGlobalFunction())
  1923. {
  1924. m_writer.Reg1(Js::OpCode::LdUndef, funcInfo->newTargetRegister);
  1925. }
  1926. else
  1927. {
  1928. m_writer.Reg1(Js::OpCode::LdNewTarget, funcInfo->newTargetRegister);
  1929. }
  1930. }
  1931. void ByteCodeGenerator::EmitScopeSlotLoadThis(FuncInfo *funcInfo, Js::RegSlot regLoc, bool chkUndecl)
  1932. {
  1933. FuncInfo* nonLambdaFunc = funcInfo;
  1934. if (funcInfo->IsLambda())
  1935. {
  1936. nonLambdaFunc = FindEnclosingNonLambda();
  1937. }
  1938. if (nonLambdaFunc->IsClassConstructor() && !nonLambdaFunc->IsBaseClassConstructor())
  1939. {
  1940. // If we are in a derived class constructor and we have a scope slot for 'this',
  1941. // we need to load 'this' from the scope slot. This is to support the case where
  1942. // the call to initialize 'this' via super() is inside a lambda since the lambda
  1943. // can't assign to the 'this' register of the parent constructor.
  1944. if (nonLambdaFunc->thisScopeSlot != Js::Constants::NoRegister)
  1945. {
  1946. Js::PropertyId slot = nonLambdaFunc->thisScopeSlot;
  1947. EmitInternalScopedSlotLoad(funcInfo, slot, regLoc, chkUndecl);
  1948. }
  1949. else if (funcInfo->thisPointerRegister != Js::Constants::NoRegister && chkUndecl)
  1950. {
  1951. this->m_writer.Reg1(Js::OpCode::ChkUndecl, funcInfo->thisPointerRegister);
  1952. }
  1953. else if (chkUndecl)
  1954. {
  1955. // If we don't have a scope slot for 'this' we know that super could not have
  1956. // been called inside a lambda so we can check to see if we called
  1957. // super and assigned to the this register already. If not, this should trigger
  1958. // a ReferenceError.
  1959. EmitUseBeforeDeclarationRuntimeError(this, regLoc, false);
  1960. }
  1961. }
  1962. else if (this->flags & fscrEval && (funcInfo->IsGlobalFunction() || (funcInfo->IsLambda() && nonLambdaFunc->IsGlobalFunction()))
  1963. && funcInfo->GetBodyScope()->GetIsObject())
  1964. {
  1965. Js::RegSlot scopeLocation;
  1966. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  1967. {
  1968. scopeLocation = funcInfo->frameDisplayRegister;
  1969. }
  1970. else if (funcInfo->NeedEnvRegister())
  1971. {
  1972. scopeLocation = funcInfo->GetEnvRegister();
  1973. }
  1974. else
  1975. {
  1976. // If this eval doesn't have environment register or frame display register, we didn't capture anything from a class constructor
  1977. return;
  1978. }
  1979. // CONSIDER [tawoll] - Should we add a ByteCodeGenerator flag (fscrEvalWithClassConstructorParent) and avoid doing this runtime check?
  1980. Js::ByteCodeLabel skipLabel = this->Writer()->DefineLabel();
  1981. this->Writer()->BrReg1(Js::OpCode::BrNotUndecl_A, skipLabel, funcInfo->thisPointerRegister);
  1982. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, Js::PropertyIds::_lexicalThisSlotSymbol, false, false);
  1983. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, funcInfo->thisPointerRegister, cacheId);
  1984. if (chkUndecl)
  1985. {
  1986. this->m_writer.Reg1(Js::OpCode::ChkUndecl, funcInfo->thisPointerRegister);
  1987. }
  1988. this->Writer()->MarkLabel(skipLabel);
  1989. }
  1990. }
  1991. void ByteCodeGenerator::EmitScopeSlotStoreThis(FuncInfo *funcInfo, Js::RegSlot regLoc, bool chkUndecl)
  1992. {
  1993. if (this->flags & fscrEval && (funcInfo->IsGlobalFunction() || (funcInfo->IsLambda() && FindEnclosingNonLambda()->IsGlobalFunction())))
  1994. {
  1995. Js::RegSlot scopeLocation;
  1996. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  1997. {
  1998. scopeLocation = funcInfo->frameDisplayRegister;
  1999. }
  2000. else
  2001. {
  2002. scopeLocation = funcInfo->GetEnvRegister();
  2003. }
  2004. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, Js::PropertyIds::_lexicalThisSlotSymbol, false, true);
  2005. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo->byteCodeFunction->GetIsStrictMode()), funcInfo->thisPointerRegister, cacheId);
  2006. }
  2007. else if (regLoc != Js::Constants::NoRegister)
  2008. {
  2009. EmitInternalScopedSlotStore(funcInfo, regLoc, funcInfo->thisPointerRegister);
  2010. }
  2011. }
  2012. void ByteCodeGenerator::EmitSuperCall(FuncInfo* funcInfo, ParseNode* pnode, BOOL fReturnValue)
  2013. {
  2014. Assert(pnode->sxCall.pnodeTarget->nop == knopSuper);
  2015. FuncInfo* nonLambdaFunc = funcInfo;
  2016. if (funcInfo->IsLambda())
  2017. {
  2018. nonLambdaFunc = this->FindEnclosingNonLambda();
  2019. }
  2020. if (nonLambdaFunc->IsBaseClassConstructor())
  2021. {
  2022. // super() is not allowed in base class constructors. If we detect this, emit a ReferenceError and skip making the call.
  2023. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_ClassSuperInBaseClass));
  2024. return;
  2025. }
  2026. else
  2027. {
  2028. EmitSuperFieldPatch(funcInfo, pnode, this);
  2029. pnode->isUsed = true;
  2030. }
  2031. // We already know pnode->sxCall.pnodeTarget->nop is super but we can't use the super register in case
  2032. // this is an eval and we will load super dynamically from the scope using ScopedLdSuper.
  2033. // That means we'll have to rely on the location of the call target to be sure.
  2034. // We have to make sure to allocate the location for the node now, before we try to branch on it.
  2035. Emit(pnode->sxCall.pnodeTarget, this, funcInfo, false, /*isConstructorCall*/ true); // reuse isConstructorCall ("new super()" is illegal)
  2036. //
  2037. // if (super is class constructor) {
  2038. // _this = new.target;
  2039. // } else {
  2040. // _this = NewScObjFull(new.target);
  2041. // }
  2042. //
  2043. // temp = super.call(_this, new.target); // CallFlag_New | CallFlag_NewTarget | CallFlag_ExtraArg
  2044. // if (temp is object) {
  2045. // _this = temp;
  2046. // }
  2047. //
  2048. // if (UndeclBlockVar === this) {
  2049. // this = _this;
  2050. // } else {
  2051. // throw ReferenceError;
  2052. // }
  2053. //
  2054. funcInfo->AcquireLoc(pnode);
  2055. Js::RegSlot thisForSuperCall = funcInfo->AcquireTmpRegister();
  2056. Js::ByteCodeLabel useNewTargetForThisLabel = this->Writer()->DefineLabel();
  2057. Js::ByteCodeLabel makeCallLabel = this->Writer()->DefineLabel();
  2058. Js::ByteCodeLabel useSuperCallResultLabel = this->Writer()->DefineLabel();
  2059. Js::ByteCodeLabel doneLabel = this->Writer()->DefineLabel();
  2060. this->Writer()->BrReg1(Js::OpCode::BrOnClassConstructor, useNewTargetForThisLabel, pnode->sxCall.pnodeTarget->location);
  2061. this->Writer()->Reg2(Js::OpCode::NewScObjectNoCtorFull, thisForSuperCall, funcInfo->newTargetRegister);
  2062. this->Writer()->Br(Js::OpCode::Br, makeCallLabel);
  2063. this->Writer()->MarkLabel(useNewTargetForThisLabel);
  2064. this->Writer()->Reg2(Js::OpCode::Ld_A, thisForSuperCall, funcInfo->newTargetRegister);
  2065. this->Writer()->MarkLabel(makeCallLabel);
  2066. EmitCall(pnode, Js::Constants::NoRegister, this, funcInfo, fReturnValue, /*fEvaluateComponents*/ true, /*fHasNewTarget*/ true, thisForSuperCall);
  2067. // We have to use another temp for the this value before assigning to this register.
  2068. // This is because IRBuilder does not expect us to use the value of a temp after potentially assigning to that same temp.
  2069. // Ex:
  2070. // _this = new.target;
  2071. // temp = super.call(_this);
  2072. // if (temp is object) {
  2073. // _this = temp; // creates a new sym for _this as it was previously used
  2074. // }
  2075. // this = _this; // tries to loads a value from the old sym (which is dead)
  2076. Js::RegSlot valueForThis = funcInfo->AcquireTmpRegister();
  2077. this->Writer()->BrReg1(Js::OpCode::BrOnObject_A, useSuperCallResultLabel, pnode->location);
  2078. this->Writer()->Reg2(Js::OpCode::Ld_A, valueForThis, thisForSuperCall);
  2079. this->Writer()->Br(Js::OpCode::Br, doneLabel);
  2080. this->Writer()->MarkLabel(useSuperCallResultLabel);
  2081. this->Writer()->Reg2(Js::OpCode::Ld_A, valueForThis, pnode->location);
  2082. this->Writer()->MarkLabel(doneLabel);
  2083. // The call is done and we know what we will bind to 'this' so let's check to see if 'this' is already decl.
  2084. // We may need to load 'this' from the scope slot.
  2085. EmitScopeSlotLoadThis(funcInfo, funcInfo->thisPointerRegister, false);
  2086. Js::ByteCodeLabel skipLabel = this->Writer()->DefineLabel();
  2087. Js::RegSlot tmpUndeclReg = funcInfo->AcquireTmpRegister();
  2088. this->Writer()->Reg1(Js::OpCode::InitUndecl, tmpUndeclReg);
  2089. this->Writer()->BrReg2(Js::OpCode::BrSrEq_A, skipLabel, funcInfo->thisPointerRegister, tmpUndeclReg);
  2090. funcInfo->ReleaseTmpRegister(tmpUndeclReg);
  2091. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_ClassThisAlreadyAssigned));
  2092. this->Writer()->MarkLabel(skipLabel);
  2093. this->Writer()->Reg2(Js::OpCode::StrictLdThis, funcInfo->thisPointerRegister, valueForThis);
  2094. funcInfo->ReleaseTmpRegister(valueForThis);
  2095. funcInfo->ReleaseTmpRegister(thisForSuperCall);
  2096. // We already assigned the result of super() to the 'this' register but we need to store it in the scope slot, too. If there is one.
  2097. this->EmitScopeSlotStoreThis(funcInfo, nonLambdaFunc->thisScopeSlot);
  2098. }
  2099. void ByteCodeGenerator::EmitClassConstructorEndCode(FuncInfo *funcInfo)
  2100. {
  2101. if (funcInfo->thisPointerRegister != Js::Constants::NoRegister)
  2102. {
  2103. // We need to try and load 'this' from the scope slot, if there is one.
  2104. EmitScopeSlotLoadThis(funcInfo, funcInfo->thisPointerRegister);
  2105. this->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, funcInfo->thisPointerRegister);
  2106. }
  2107. else
  2108. {
  2109. // This is the case where we don't have any references to this or super in the constructor or any nested lambda functions.
  2110. // We know 'this' must be undecl so let's just emit the ReferenceError as part of the fallthrough.
  2111. EmitUseBeforeDeclarationRuntimeError(this, ByteCodeGenerator::ReturnRegister, true);
  2112. }
  2113. }
  2114. void ByteCodeGenerator::EmitBaseClassConstructorThisObject(FuncInfo *funcInfo)
  2115. {
  2116. this->Writer()->Reg2(Js::OpCode::NewScObjectNoCtorFull, funcInfo->thisPointerRegister, funcInfo->newTargetRegister);
  2117. }
  2118. void ByteCodeGenerator::EmitInternalScopedSlotLoad(FuncInfo *funcInfo, Js::RegSlot slot, Js::RegSlot symbolRegister, bool chkUndecl)
  2119. {
  2120. Scope* scope = nullptr;
  2121. if (funcInfo->IsLambda())
  2122. {
  2123. Js::PropertyId envIndex = -1;
  2124. GetEnclosingNonLambdaScope(funcInfo, scope, envIndex);
  2125. EmitInternalScopedSlotLoad(funcInfo, scope, envIndex, slot, symbolRegister, chkUndecl);
  2126. }
  2127. else
  2128. {
  2129. scope = funcInfo->GetBodyScope();
  2130. EmitInternalScopedSlotLoad(funcInfo, scope, -1, slot, symbolRegister, chkUndecl);
  2131. }
  2132. }
  2133. void ByteCodeGenerator::EmitInternalScopedSlotLoad(FuncInfo *funcInfo, Scope *scope, Js::PropertyId envIndex, Js::RegSlot slot, Js::RegSlot symbolRegister, bool chkUndecl)
  2134. {
  2135. Assert(slot != Js::Constants::NoProperty);
  2136. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(scope, symbolRegister);
  2137. Js::OpCode opcode;
  2138. Js::RegSlot scopeLocation = scope->GetLocation();
  2139. opcode = this->GetLdSlotOp(scope, envIndex, scopeLocation, funcInfo);
  2140. slot += (scope->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  2141. if (envIndex != -1)
  2142. {
  2143. this->m_writer.SlotI2(opcode, symbolRegister, envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var), slot, profileId);
  2144. }
  2145. else if (scopeLocation != Js::Constants::NoRegister &&
  2146. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  2147. {
  2148. this->m_writer.SlotI1(opcode, symbolRegister, slot, profileId);
  2149. }
  2150. else
  2151. {
  2152. this->m_writer.Slot(opcode, symbolRegister, scopeLocation, slot, profileId);
  2153. }
  2154. if (chkUndecl)
  2155. {
  2156. this->m_writer.Reg1(Js::OpCode::ChkUndecl, symbolRegister);
  2157. }
  2158. }
  2159. void ByteCodeGenerator::EmitInternalScopedSlotStore(FuncInfo *funcInfo, Js::RegSlot slot, Js::RegSlot symbolRegister)
  2160. {
  2161. Assert(slot != Js::Constants::NoProperty);
  2162. Scope* scope = nullptr;
  2163. Js::OpCode opcode;
  2164. Js::PropertyId envIndex = -1;
  2165. if (funcInfo->IsLambda())
  2166. {
  2167. GetEnclosingNonLambdaScope(funcInfo, scope, envIndex);
  2168. }
  2169. else
  2170. {
  2171. scope = funcInfo->GetBodyScope();
  2172. }
  2173. Js::RegSlot scopeLocation = scope->GetLocation();
  2174. opcode = this->GetStSlotOp(scope, envIndex, scopeLocation, false, funcInfo);
  2175. slot += (scope->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  2176. if (envIndex != -1)
  2177. {
  2178. this->m_writer.SlotI2(opcode, symbolRegister, envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var), slot);
  2179. }
  2180. else if (scopeLocation != Js::Constants::NoRegister &&
  2181. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  2182. {
  2183. this->m_writer.SlotI1(opcode, symbolRegister, slot);
  2184. }
  2185. else if (scope->GetIsObject())
  2186. {
  2187. this->m_writer.Slot(opcode, symbolRegister, scopeLocation, slot);
  2188. }
  2189. else
  2190. {
  2191. this->m_writer.SlotI2(opcode, symbolRegister, scope->GetInnerScopeIndex(), slot);
  2192. }
  2193. }
  2194. void ByteCodeGenerator::EmitInternalScopeObjInit(FuncInfo *funcInfo, Scope *scope, Js::RegSlot valueLocation, Js::PropertyId propertyId)
  2195. {
  2196. Js::RegSlot scopeLocation = scope->GetLocation();
  2197. Js::OpCode opcode = this->GetInitFldOp(scope, scopeLocation, funcInfo);
  2198. if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  2199. {
  2200. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  2201. this->m_writer.ElementP(opcode, valueLocation, cacheId);
  2202. }
  2203. else if (scope->HasInnerScopeIndex())
  2204. {
  2205. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
  2206. this->m_writer.ElementPIndexed(opcode, valueLocation, scope->GetInnerScopeIndex(), cacheId);
  2207. }
  2208. else
  2209. {
  2210. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  2211. this->m_writer.PatchableProperty(opcode, valueLocation, scopeLocation, cacheId);
  2212. }
  2213. }
  2214. void ByteCodeGenerator::GetEnclosingNonLambdaScope(FuncInfo *funcInfo, Scope * &scope, Js::PropertyId &envIndex)
  2215. {
  2216. Assert(funcInfo->IsLambda());
  2217. envIndex = -1;
  2218. for (scope = GetCurrentScope(); scope; scope = scope->GetEnclosingScope())
  2219. {
  2220. if (scope->GetMustInstantiate() && scope->GetFunc() != funcInfo)
  2221. {
  2222. envIndex++;
  2223. }
  2224. if (((scope == scope->GetFunc()->GetBodyScope() || scope == scope->GetFunc()->GetParamScope()) && !scope->GetFunc()->IsLambda()) || scope->IsGlobalEvalBlockScope())
  2225. {
  2226. break;
  2227. }
  2228. }
  2229. }
  2230. void ByteCodeGenerator::EmitThis(FuncInfo *funcInfo, Js::RegSlot fromRegister)
  2231. {
  2232. if (funcInfo->IsLambda())
  2233. {
  2234. Scope *scope;
  2235. Js::PropertyId envIndex = -1;
  2236. GetEnclosingNonLambdaScope(funcInfo, scope, envIndex);
  2237. FuncInfo* parent = scope->GetFunc();
  2238. if (parent->IsGlobalFunction())
  2239. {
  2240. if (this->flags & fscrEval)
  2241. {
  2242. scope = parent->GetGlobalEvalBlockScope();
  2243. Js::PropertyId slot = parent->thisScopeSlot;
  2244. EmitInternalScopedSlotLoad(funcInfo, scope, envIndex, slot, funcInfo->thisPointerRegister, false);
  2245. }
  2246. else
  2247. {
  2248. // Always load global object via LdThis of null to get the possibly protected via secureHostObject global object.
  2249. this->m_writer.Reg2Int1(Js::OpCode::LdThis, funcInfo->thisPointerRegister, funcInfo->nullConstantRegister, this->GetModuleID());
  2250. }
  2251. }
  2252. else if (!parent->IsClassConstructor() || parent->IsBaseClassConstructor())
  2253. {
  2254. // In a lambda inside a derived class constructor, 'this' should be loaded from the scope slot whenever 'this' is accessed.
  2255. // It's safe to load 'this' into the register for base class constructors because there is no complex assignment to 'this'
  2256. // via super call chain.
  2257. Js::PropertyId slot = parent->thisScopeSlot;
  2258. EmitInternalScopedSlotLoad(funcInfo, scope, envIndex, slot, funcInfo->thisPointerRegister, false);
  2259. }
  2260. }
  2261. else if (funcInfo->byteCodeFunction->GetIsStrictMode() && (!funcInfo->IsGlobalFunction() || this->flags & fscrEval))
  2262. {
  2263. m_writer.Reg2(Js::OpCode::StrictLdThis, funcInfo->thisPointerRegister, fromRegister);
  2264. }
  2265. else
  2266. {
  2267. m_writer.Reg2Int1(Js::OpCode::LdThis, funcInfo->thisPointerRegister, fromRegister, this->GetModuleID());
  2268. }
  2269. }
  2270. void ByteCodeGenerator::EmitLoadFormalIntoRegister(ParseNode *pnodeFormal, Js::RegSlot pos, FuncInfo *funcInfo)
  2271. {
  2272. if (pnodeFormal->IsVarLetOrConst())
  2273. {
  2274. // Get the param from its argument position into its assigned register.
  2275. // The position should match the location, otherwise, it has been shadowed by parameter with the same name
  2276. Symbol *formal = pnodeFormal->sxVar.sym;
  2277. if (formal->GetLocation() + 1 == pos)
  2278. {
  2279. // Transfer to the frame object, etc., if necessary.
  2280. this->EmitLocalPropInit(formal->GetLocation(), formal, funcInfo);
  2281. }
  2282. if (ShouldTrackDebuggerMetadata() && !formal->IsInSlot(funcInfo))
  2283. {
  2284. Assert(!formal->GetHasInit());
  2285. funcInfo->GetParsedFunctionBody()->InsertSymbolToRegSlotList(formal->GetName(), formal->GetLocation(), funcInfo->varRegsCount);
  2286. }
  2287. }
  2288. }
  2289. void ByteCodeGenerator::HomeArguments(FuncInfo *funcInfo)
  2290. {
  2291. // Transfer formal parameters to their home locations on the local frame.
  2292. if (funcInfo->GetHasArguments())
  2293. {
  2294. if (funcInfo->root->sxFnc.pnodeRest != nullptr)
  2295. {
  2296. // Since we don't have to iterate over arguments here, we'll trust the location to be correct.
  2297. EmitLoadFormalIntoRegister(funcInfo->root->sxFnc.pnodeRest, funcInfo->root->sxFnc.pnodeRest->sxVar.sym->GetLocation() + 1, funcInfo);
  2298. }
  2299. // The arguments object creation helper does this work for us.
  2300. return;
  2301. }
  2302. Js::ArgSlot pos = 1;
  2303. auto loadFormal = [&](ParseNode *pnodeFormal)
  2304. {
  2305. EmitLoadFormalIntoRegister(pnodeFormal, pos, funcInfo);
  2306. pos++;
  2307. };
  2308. MapFormals(funcInfo->root, loadFormal);
  2309. }
  2310. void ByteCodeGenerator::DefineLabels(FuncInfo *funcInfo)
  2311. {
  2312. funcInfo->singleExit = m_writer.DefineLabel();
  2313. SList<ParseNode *>::Iterator iter(&funcInfo->targetStatements);
  2314. while (iter.Next())
  2315. {
  2316. ParseNode * node = iter.Data();
  2317. node->sxStmt.breakLabel = m_writer.DefineLabel();
  2318. node->sxStmt.continueLabel = m_writer.DefineLabel();
  2319. node->emitLabels = true;
  2320. }
  2321. }
  2322. void ByteCodeGenerator::EmitGlobalBody(FuncInfo *funcInfo)
  2323. {
  2324. // Emit global code (global scope or eval), fixing up the return register with the implicit
  2325. // return value.
  2326. ParseNode *pnode = funcInfo->root->sxFnc.pnodeBody;
  2327. ParseNode *pnodeLastVal = funcInfo->root->sxProg.pnodeLastValStmt;
  2328. if (pnodeLastVal == nullptr)
  2329. {
  2330. // We're not guaranteed to compute any values, so fix up the return register at the top
  2331. // in case.
  2332. this->m_writer.Reg1(Js::OpCode::LdUndef, ReturnRegister);
  2333. }
  2334. while (pnode->nop == knopList)
  2335. {
  2336. ParseNode *stmt = pnode->sxBin.pnode1;
  2337. if (stmt == pnodeLastVal)
  2338. {
  2339. pnodeLastVal = nullptr;
  2340. }
  2341. if (pnodeLastVal == nullptr && (this->flags & fscrReturnExpression))
  2342. {
  2343. EmitTopLevelStatement(stmt, funcInfo, true);
  2344. }
  2345. else
  2346. {
  2347. // Haven't hit the post-dominating return value yet,
  2348. // so don't bother with the return register.
  2349. EmitTopLevelStatement(stmt, funcInfo, false);
  2350. }
  2351. pnode = pnode->sxBin.pnode2;
  2352. }
  2353. EmitTopLevelStatement(pnode, funcInfo, false);
  2354. }
  2355. void ByteCodeGenerator::EmitFunctionBody(FuncInfo *funcInfo)
  2356. {
  2357. // Emit a function body. Only explicit returns and the implicit "undef" at the bottom
  2358. // get copied to the return register.
  2359. ParseNode *pnodeBody = funcInfo->root->sxFnc.pnodeBody;
  2360. ParseNode *pnode = pnodeBody;
  2361. while (pnode->nop == knopList)
  2362. {
  2363. ParseNode *stmt = pnode->sxBin.pnode1;
  2364. if (stmt->CapturesSyms())
  2365. {
  2366. CapturedSymMap *map = funcInfo->EnsureCapturedSymMap();
  2367. SList<Symbol*> *list = map->Item(stmt);
  2368. FOREACH_SLIST_ENTRY(Symbol*, sym, list)
  2369. {
  2370. if (!sym->GetIsCommittedToSlot())
  2371. {
  2372. Assert(sym->GetLocation() != Js::Constants::NoProperty);
  2373. sym->SetIsCommittedToSlot();
  2374. ParseNode *decl = sym->GetDecl();
  2375. Assert(decl);
  2376. if (PHASE_TRACE(Js::DelayCapturePhase, funcInfo->byteCodeFunction))
  2377. {
  2378. Output::Print(_u("--- DelayCapture: Committed symbol '%s' to slot.\n"), sym->GetName());
  2379. Output::Flush();
  2380. }
  2381. this->EmitPropStore(sym->GetLocation(), sym, sym->GetPid(), funcInfo, decl->nop == knopLetDecl, decl->nop == knopConstDecl);
  2382. }
  2383. }
  2384. NEXT_SLIST_ENTRY;
  2385. }
  2386. EmitTopLevelStatement(stmt, funcInfo, false);
  2387. pnode = pnode->sxBin.pnode2;
  2388. }
  2389. Assert(!pnode->CapturesSyms());
  2390. EmitTopLevelStatement(pnode, funcInfo, false);
  2391. }
  2392. void ByteCodeGenerator::EmitProgram(ParseNode *pnodeProg)
  2393. {
  2394. // Indicate that the binding phase is over.
  2395. this->isBinding = false;
  2396. this->trackEnvDepth = true;
  2397. AssignPropertyIds(pnodeProg->sxFnc.funcInfo->byteCodeFunction);
  2398. long initSize = this->maxAstSize / AstBytecodeRatioEstimate;
  2399. // Use the temp allocator in bytecode write temp buffer.
  2400. m_writer.InitData(this->alloc, initSize);
  2401. #ifdef LOG_BYTECODE_AST_RATIO
  2402. // log the max Ast size
  2403. Output::Print(_u("Max Ast size: %d"), initSize);
  2404. #endif
  2405. Assert(pnodeProg && pnodeProg->nop == knopProg);
  2406. if (this->parentScopeInfo)
  2407. {
  2408. // Scope stack is already set up the way we want it, so don't visit the global scope.
  2409. // Start emitting with the nested scope (i.e., the deferred function).
  2410. this->EmitScopeList(pnodeProg->sxProg.pnodeScopes);
  2411. }
  2412. else
  2413. {
  2414. this->EmitScopeList(pnodeProg);
  2415. }
  2416. }
  2417. void ByteCodeGenerator::EmitInitCapturedThis(FuncInfo* funcInfo, Scope* scope)
  2418. {
  2419. if (scope->GetIsObject())
  2420. {
  2421. // Ensure space for the this slot
  2422. this->EmitInternalScopeObjInit(funcInfo, scope, funcInfo->thisPointerRegister, Js::PropertyIds::_lexicalThisSlotSymbol);
  2423. }
  2424. else
  2425. {
  2426. this->EmitInternalScopedSlotStore(funcInfo, funcInfo->thisScopeSlot, funcInfo->thisPointerRegister);
  2427. }
  2428. }
  2429. void ByteCodeGenerator::EmitInitCapturedNewTarget(FuncInfo* funcInfo, Scope* scope)
  2430. {
  2431. if (scope->GetIsObject())
  2432. {
  2433. // Ensure space for the new.target slot
  2434. this->EmitInternalScopeObjInit(funcInfo, scope, funcInfo->newTargetRegister, Js::PropertyIds::_lexicalNewTargetSymbol);
  2435. }
  2436. else
  2437. {
  2438. this->EmitInternalScopedSlotStore(funcInfo, funcInfo->newTargetScopeSlot, funcInfo->newTargetRegister);
  2439. }
  2440. }
  2441. void EmitDestructuredObject(ParseNode *lhs, Js::RegSlot rhsLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  2442. void EmitDestructuredValueOrInitializer(ParseNodePtr lhsElementNode, Js::RegSlot rhsLocation, ParseNodePtr initializer, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  2443. void ByteCodeGenerator::PopulateFormalsScope(uint beginOffset, FuncInfo *funcInfo, ParseNode *pnode)
  2444. {
  2445. Js::DebuggerScope *debuggerScope = nullptr;
  2446. auto processArg = [&](ParseNode *pnodeArg) {
  2447. if (pnodeArg->IsVarLetOrConst())
  2448. {
  2449. if (debuggerScope == nullptr)
  2450. {
  2451. debuggerScope = RecordStartScopeObject(pnode, funcInfo->paramScope && funcInfo->paramScope->GetIsObject() ? Js::DiagParamScopeInObject : Js::DiagParamScope);
  2452. debuggerScope->SetBegin(beginOffset);
  2453. }
  2454. debuggerScope->AddProperty(pnodeArg->sxVar.sym->GetLocation(), pnodeArg->sxVar.sym->EnsurePosition(funcInfo), Js::DebuggerScopePropertyFlags_None);
  2455. }
  2456. };
  2457. MapFormals(pnode, processArg);
  2458. MapFormalsFromPattern(pnode, processArg);
  2459. if (debuggerScope != nullptr)
  2460. {
  2461. RecordEndScopeObject(pnode);
  2462. }
  2463. }
  2464. void ByteCodeGenerator::EmitDefaultArgs(FuncInfo *funcInfo, ParseNode *pnode)
  2465. {
  2466. uint beginOffset = m_writer.GetCurrentOffset();
  2467. auto emitDefaultArg = [&](ParseNode *pnodeArg)
  2468. {
  2469. if (pnodeArg->nop == knopParamPattern)
  2470. {
  2471. this->StartStatement(pnodeArg);
  2472. Assert(pnodeArg->sxParamPattern.location != Js::Constants::NoRegister);
  2473. ParseNodePtr pnode1 = pnodeArg->sxParamPattern.pnode1;
  2474. if (pnode1->IsPattern())
  2475. {
  2476. EmitAssignment(nullptr, pnode1, pnodeArg->sxParamPattern.location, this, funcInfo);
  2477. }
  2478. else
  2479. {
  2480. Assert(pnode1->nop == knopAsg);
  2481. Assert(pnode1->sxBin.pnode1->IsPattern());
  2482. EmitDestructuredValueOrInitializer(pnode1->sxBin.pnode1, pnodeArg->sxParamPattern.location, pnode1->sxBin.pnode2, this, funcInfo);
  2483. }
  2484. this->EndStatement(pnodeArg);
  2485. return;
  2486. }
  2487. else if (pnodeArg->IsVarLetOrConst())
  2488. {
  2489. Js::RegSlot location = pnodeArg->sxVar.sym->GetLocation();
  2490. if (pnodeArg->sxVar.pnodeInit == nullptr)
  2491. {
  2492. // Since the formal hasn't been initialized in LdLetHeapArguments, we'll initialize it here.
  2493. EmitPropStore(location, pnodeArg->sxVar.sym, pnodeArg->sxVar.pid, funcInfo, true);
  2494. pnodeArg->sxVar.sym->SetNeedDeclaration(false);
  2495. return;
  2496. }
  2497. // Load the default argument if we got undefined, skip RHS evaluation otherwise.
  2498. Js::ByteCodeLabel noDefaultLabel = this->m_writer.DefineLabel();
  2499. Js::ByteCodeLabel endLabel = this->m_writer.DefineLabel();
  2500. this->StartStatement(pnodeArg);
  2501. // Let us use strict not equal to differentiate between null and undefined
  2502. m_writer.BrReg2(Js::OpCode::BrSrNeq_A, noDefaultLabel, location, funcInfo->undefinedConstantRegister);
  2503. Emit(pnodeArg->sxVar.pnodeInit, this, funcInfo, false);
  2504. pnodeArg->sxVar.sym->SetNeedDeclaration(false); // After emit to prevent foo(a = a)
  2505. if (funcInfo->GetHasArguments() && pnodeArg->sxVar.sym->IsInSlot(funcInfo))
  2506. {
  2507. EmitPropStore(pnodeArg->sxVar.pnodeInit->location, pnodeArg->sxVar.sym, pnodeArg->sxVar.pid, funcInfo, true);
  2508. m_writer.Br(endLabel);
  2509. }
  2510. else
  2511. {
  2512. EmitAssignment(nullptr, pnodeArg, pnodeArg->sxVar.pnodeInit->location, this, funcInfo);
  2513. }
  2514. funcInfo->ReleaseLoc(pnodeArg->sxVar.pnodeInit);
  2515. m_writer.MarkLabel(noDefaultLabel);
  2516. if (funcInfo->GetHasArguments() && pnodeArg->sxVar.sym->IsInSlot(funcInfo))
  2517. {
  2518. EmitPropStore(location, pnodeArg->sxVar.sym, pnodeArg->sxVar.pid, funcInfo, true);
  2519. m_writer.MarkLabel(endLabel);
  2520. }
  2521. this->EndStatement(pnodeArg);
  2522. }
  2523. };
  2524. // If the function is async, we wrap the default arguments in a try catch and reject a Promise in case of error.
  2525. if (pnode->sxFnc.IsAsync())
  2526. {
  2527. uint cacheId;
  2528. Js::ByteCodeLabel catchLabel = m_writer.DefineLabel();
  2529. Js::ByteCodeLabel doneLabel = m_writer.DefineLabel();
  2530. Js::RegSlot catchArgLocation = funcInfo->AcquireTmpRegister();
  2531. Js::RegSlot promiseLocation = funcInfo->AcquireTmpRegister();
  2532. Js::RegSlot rejectLocation = funcInfo->AcquireTmpRegister();
  2533. // try
  2534. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  2535. m_writer.Br(Js::OpCode::TryCatch, catchLabel);
  2536. // Rest cannot have a default argument, so we ignore it.
  2537. MapFormalsWithoutRest(pnode, emitDefaultArg);
  2538. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  2539. m_writer.Empty(Js::OpCode::Leave);
  2540. m_writer.Br(doneLabel);
  2541. // catch
  2542. m_writer.MarkLabel(catchLabel);
  2543. m_writer.Reg1(Js::OpCode::Catch, catchArgLocation);
  2544. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  2545. m_writer.Empty(Js::OpCode::Nop);
  2546. // return Promise.reject(error);
  2547. cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(Js::PropertyIds::Promise, false, false);
  2548. m_writer.PatchableRootProperty(Js::OpCode::LdRootFld, promiseLocation, cacheId, false, false);
  2549. EmitInvoke(rejectLocation, promiseLocation, Js::PropertyIds::reject, this, funcInfo, catchArgLocation);
  2550. m_writer.Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, rejectLocation);
  2551. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  2552. m_writer.Empty(Js::OpCode::Leave);
  2553. m_writer.Br(funcInfo->singleExit);
  2554. m_writer.Empty(Js::OpCode::Leave);
  2555. m_writer.MarkLabel(doneLabel);
  2556. this->SetHasTry(true);
  2557. funcInfo->ReleaseTmpRegister(rejectLocation);
  2558. funcInfo->ReleaseTmpRegister(promiseLocation);
  2559. funcInfo->ReleaseTmpRegister(catchArgLocation);
  2560. }
  2561. else
  2562. {
  2563. // Rest cannot have a default argument, so we ignore it.
  2564. MapFormalsWithoutRest(pnode, emitDefaultArg);
  2565. }
  2566. if (ShouldTrackDebuggerMetadata() && m_writer.GetCurrentOffset() > beginOffset)
  2567. {
  2568. PopulateFormalsScope(beginOffset, funcInfo, pnode);
  2569. }
  2570. }
  2571. void ByteCodeGenerator::EmitOneFunction(ParseNode *pnode)
  2572. {
  2573. Assert(pnode && (pnode->nop == knopProg || pnode->nop == knopFncDecl));
  2574. FuncInfo *funcInfo = pnode->sxFnc.funcInfo;
  2575. Assert(funcInfo != nullptr);
  2576. if (funcInfo->IsFakeGlobalFunction(this->flags))
  2577. {
  2578. return;
  2579. }
  2580. Js::ParseableFunctionInfo* deferParseFunction = funcInfo->byteCodeFunction;
  2581. deferParseFunction->SetGrfscr(deferParseFunction->GetGrfscr() | (this->flags & ~fscrDeferredFncExpression));
  2582. deferParseFunction->SetSourceInfo(this->GetCurrentSourceIndex(),
  2583. funcInfo->root,
  2584. !!(this->flags & fscrEvalCode),
  2585. ((this->flags & fscrDynamicCode) && !(this->flags & fscrEvalCode)));
  2586. deferParseFunction->SetInParamsCount(funcInfo->inArgsCount);
  2587. if (pnode->sxFnc.HasDefaultArguments())
  2588. {
  2589. deferParseFunction->SetReportedInParamsCount(pnode->sxFnc.firstDefaultArg + 1);
  2590. }
  2591. else
  2592. {
  2593. deferParseFunction->SetReportedInParamsCount(funcInfo->inArgsCount);
  2594. }
  2595. if (funcInfo->root->sxFnc.pnodeBody == nullptr)
  2596. {
  2597. if (!PHASE_OFF1(Js::SkipNestedDeferredPhase))
  2598. {
  2599. deferParseFunction->BuildDeferredStubs(funcInfo->root);
  2600. }
  2601. return;
  2602. }
  2603. Js::FunctionBody* byteCodeFunction = funcInfo->GetParsedFunctionBody();
  2604. // We've now done a full parse of this function, so we no longer need to remember the extents
  2605. // and attributes of the top-level nested functions. (The above code has run for all of those,
  2606. // so they have pointers to the stub sub-trees they need.)
  2607. byteCodeFunction->SetDeferredStubs(nullptr);
  2608. try
  2609. {
  2610. // Bug : 301517
  2611. // In the debug mode the hasOnlyThis optimization needs to be disabled, since user can break in this function
  2612. // and do operation on 'this' and its property, which may not be defined yet.
  2613. if (funcInfo->root->sxFnc.HasOnlyThisStmts() && !IsInDebugMode())
  2614. {
  2615. byteCodeFunction->SetHasOnlyThisStmts(true);
  2616. }
  2617. if (byteCodeFunction->IsInlineApplyDisabled() || this->scriptContext->GetConfig()->IsNoNative())
  2618. {
  2619. if ((pnode->nop == knopFncDecl) && (funcInfo->GetHasHeapArguments()) && (!funcInfo->GetCallsEval()) && ApplyEnclosesArgs(pnode, this))
  2620. {
  2621. bool applyEnclosesArgs = true;
  2622. for (ParseNode* pnodeVar = funcInfo->root->sxFnc.pnodeVars; pnodeVar; pnodeVar = pnodeVar->sxVar.pnodeNext)
  2623. {
  2624. Symbol* sym = pnodeVar->sxVar.sym;
  2625. if (sym->GetSymbolType() == STVariable && !sym->GetIsArguments())
  2626. {
  2627. applyEnclosesArgs = false;
  2628. break;
  2629. }
  2630. }
  2631. auto constAndLetCheck = [](ParseNode *pnodeBlock, bool *applyEnclosesArgs)
  2632. {
  2633. if (*applyEnclosesArgs)
  2634. {
  2635. for (auto lexvar = pnodeBlock->sxBlock.pnodeLexVars; lexvar; lexvar = lexvar->sxVar.pnodeNext)
  2636. {
  2637. Symbol* sym = lexvar->sxVar.sym;
  2638. if (sym->GetSymbolType() == STVariable && !sym->GetIsArguments())
  2639. {
  2640. *applyEnclosesArgs = false;
  2641. break;
  2642. }
  2643. }
  2644. }
  2645. };
  2646. constAndLetCheck(funcInfo->root->sxFnc.pnodeScopes, &applyEnclosesArgs);
  2647. constAndLetCheck(funcInfo->root->sxFnc.pnodeBodyScope, &applyEnclosesArgs);
  2648. funcInfo->SetApplyEnclosesArgs(applyEnclosesArgs);
  2649. }
  2650. }
  2651. if (!funcInfo->IsGlobalFunction())
  2652. {
  2653. if (CanStackNestedFunc(funcInfo, true))
  2654. {
  2655. #if DBG
  2656. byteCodeFunction->SetCanDoStackNestedFunc();
  2657. #endif
  2658. if (funcInfo->root->sxFnc.astSize <= PnFnc::MaxStackClosureAST)
  2659. {
  2660. byteCodeFunction->SetStackNestedFunc(true);
  2661. }
  2662. }
  2663. }
  2664. InitScopeSlotArray(funcInfo);
  2665. FinalizeRegisters(funcInfo, byteCodeFunction);
  2666. DebugOnly(Js::RegSlot firstTmpReg = funcInfo->varRegsCount);
  2667. // Reserve temp registers for the inner scopes. We prefer temps because the JIT will then renumber them
  2668. // and see different lifetimes. (Note that debug mode requires permanent registers. See FinalizeRegisters.)
  2669. uint innerScopeCount = funcInfo->InnerScopeCount();
  2670. if (!this->IsInDebugMode())
  2671. {
  2672. byteCodeFunction->SetInnerScopeCount(innerScopeCount);
  2673. if (innerScopeCount)
  2674. {
  2675. funcInfo->SetFirstInnerScopeReg(funcInfo->AcquireTmpRegister());
  2676. for (uint i = 1; i < innerScopeCount; i++)
  2677. {
  2678. funcInfo->AcquireTmpRegister();
  2679. }
  2680. }
  2681. }
  2682. funcInfo->inlineCacheMap = Anew(alloc, FuncInfo::InlineCacheMap,
  2683. alloc,
  2684. funcInfo->RegCount() // Pass the actual register count. // TODO: Check if we can reduce this count
  2685. );
  2686. funcInfo->rootObjectLoadInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2687. alloc,
  2688. 10);
  2689. funcInfo->rootObjectLoadMethodInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2690. alloc,
  2691. 10);
  2692. funcInfo->rootObjectStoreInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2693. alloc,
  2694. 10);
  2695. funcInfo->referencedPropertyIdToMapIndex = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2696. alloc,
  2697. 10);
  2698. byteCodeFunction->AllocateLiteralRegexArray();
  2699. m_callSiteId = 0;
  2700. m_writer.Begin(this, byteCodeFunction, alloc, this->DoJitLoopBodies(funcInfo), funcInfo->hasLoop);
  2701. this->PushFuncInfo(_u("EmitOneFunction"), funcInfo);
  2702. this->inPrologue = true;
  2703. // Class constructors do not have a [[call]] slot but we don't implement a generic way to express this.
  2704. // What we do is emit a check for the new flag here. If we don't have CallFlags_New set, the opcode will throw.
  2705. // We need to do this before emitting 'this' since the base class constructor will try to construct a new object.
  2706. if (funcInfo->IsClassConstructor())
  2707. {
  2708. m_writer.Empty(Js::OpCode::ChkNewCallFlag);
  2709. }
  2710. // For now, emit all constant loads at top of function (should instead put in closest dominator of uses).
  2711. LoadAllConstants(funcInfo);
  2712. Scope* paramScope = funcInfo->GetParamScope();
  2713. if (!pnode->sxFnc.HasNonSimpleParameterList() || paramScope->GetCanMergeWithBodyScope())
  2714. {
  2715. HomeArguments(funcInfo);
  2716. }
  2717. if (funcInfo->root->sxFnc.pnodeRest != nullptr)
  2718. {
  2719. byteCodeFunction->SetHasRestParameter();
  2720. }
  2721. if (funcInfo->thisScopeSlot != Js::Constants::NoRegister && !(funcInfo->IsLambda() || (funcInfo->IsGlobalFunction() && this->flags & fscrEval)))
  2722. {
  2723. EmitInitCapturedThis(funcInfo, funcInfo->bodyScope);
  2724. }
  2725. // Any function with a super reference or an eval call inside a class method needs to load super,
  2726. if ((funcInfo->HasSuperReference() || (funcInfo->GetCallsEval() && funcInfo->root->sxFnc.IsClassMember()))
  2727. // unless we are already inside the 'global' scope inside an eval (in which case 'ScopedLdSuper' is emitted at every 'super' reference).
  2728. && !((GetFlags() & fscrEval) && funcInfo->IsGlobalFunction()))
  2729. {
  2730. if (funcInfo->IsLambda())
  2731. {
  2732. Scope *scope;
  2733. Js::PropertyId envIndex = -1;
  2734. GetEnclosingNonLambdaScope(funcInfo, scope, envIndex);
  2735. FuncInfo* parent = scope->GetFunc();
  2736. if (!parent->IsGlobalFunction())
  2737. {
  2738. // lambda in non-global scope (eval and non-eval)
  2739. EmitInternalScopedSlotLoad(funcInfo, scope, envIndex, parent->superScopeSlot, funcInfo->superRegister);
  2740. if (funcInfo->superCtorRegister != Js::Constants::NoRegister)
  2741. {
  2742. EmitInternalScopedSlotLoad(funcInfo, scope, envIndex, parent->superCtorScopeSlot, funcInfo->superCtorRegister);
  2743. }
  2744. }
  2745. else if (!(GetFlags() & fscrEval))
  2746. {
  2747. // lambda in non-eval global scope
  2748. m_writer.Reg1(Js::OpCode::LdUndef, funcInfo->superRegister);
  2749. }
  2750. // lambda in eval global scope: ScopedLdSuper will handle error throwing
  2751. }
  2752. else
  2753. {
  2754. m_writer.Reg1(Js::OpCode::LdSuper, funcInfo->superRegister);
  2755. if (funcInfo->superCtorRegister != Js::Constants::NoRegister) // super() is allowed only in derived class constructors
  2756. {
  2757. m_writer.Reg1(Js::OpCode::LdSuperCtor, funcInfo->superCtorRegister);
  2758. }
  2759. if (!funcInfo->IsGlobalFunction())
  2760. {
  2761. if (funcInfo->bodyScope->GetIsObject() && funcInfo->bodyScope->GetLocation() != Js::Constants::NoRegister)
  2762. {
  2763. // Stash the super reference in case something inside the eval or lambda references it.
  2764. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->bodyScope->GetLocation(), Js::PropertyIds::_superReferenceSymbol, false, true);
  2765. m_writer.ElementP(Js::OpCode::InitLocalFld, funcInfo->superRegister, cacheId);
  2766. if (funcInfo->superCtorRegister != Js::Constants::NoRegister)
  2767. {
  2768. cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->bodyScope->GetLocation(), Js::PropertyIds::_superCtorReferenceSymbol, false, true);
  2769. m_writer.ElementP(Js::OpCode::InitLocalFld, funcInfo->superCtorRegister, cacheId);
  2770. }
  2771. }
  2772. else if (funcInfo->superScopeSlot == Js::Constants::NoProperty || funcInfo->superCtorScopeSlot == Js::Constants::NoProperty)
  2773. {
  2774. // While the diag locals walker will pick up super from scoped slots or an activation object,
  2775. // it will not pick it up when it is only in a register.
  2776. byteCodeFunction->InsertSymbolToRegSlotList(funcInfo->superRegister, Js::PropertyIds::_superReferenceSymbol, funcInfo->varRegsCount);
  2777. if (funcInfo->superCtorRegister != Js::Constants::NoRegister)
  2778. {
  2779. byteCodeFunction->InsertSymbolToRegSlotList(funcInfo->superCtorRegister, Js::PropertyIds::_superCtorReferenceSymbol, funcInfo->varRegsCount);
  2780. }
  2781. }
  2782. }
  2783. }
  2784. }
  2785. if (funcInfo->newTargetScopeSlot != Js::Constants::NoRegister && !funcInfo->IsGlobalFunction())
  2786. {
  2787. EmitInitCapturedNewTarget(funcInfo, funcInfo->bodyScope);
  2788. }
  2789. // We don't want to load super if we are already in an eval. ScopedLdSuper will take care of loading super in that case.
  2790. if (!(GetFlags() & fscrEval) && !funcInfo->bodyScope->GetIsObject())
  2791. {
  2792. if (funcInfo->superScopeSlot != Js::Constants::NoRegister)
  2793. {
  2794. this->EmitInternalScopedSlotStore(funcInfo, funcInfo->superScopeSlot, funcInfo->superRegister);
  2795. }
  2796. if (funcInfo->superCtorScopeSlot != Js::Constants::NoRegister)
  2797. {
  2798. this->EmitInternalScopedSlotStore(funcInfo, funcInfo->superCtorScopeSlot, funcInfo->superCtorRegister);
  2799. }
  2800. }
  2801. if (byteCodeFunction->DoStackNestedFunc())
  2802. {
  2803. uint nestedCount = byteCodeFunction->GetNestedCount();
  2804. for (uint i = 0; i < nestedCount; i++)
  2805. {
  2806. Js::FunctionProxy * nested = byteCodeFunction->GetNestedFunc(i);
  2807. if (nested->IsFunctionBody())
  2808. {
  2809. nested->GetFunctionBody()->SetStackNestedFuncParent(byteCodeFunction);
  2810. }
  2811. }
  2812. }
  2813. if (funcInfo->IsGlobalFunction())
  2814. {
  2815. EnsureNoRedeclarations(pnode->sxFnc.pnodeScopes, funcInfo);
  2816. }
  2817. ::BeginEmitBlock(pnode->sxFnc.pnodeScopes, this, funcInfo);
  2818. DefineLabels(funcInfo);
  2819. if (pnode->sxFnc.HasNonSimpleParameterList())
  2820. {
  2821. this->InitBlockScopedNonTemps(funcInfo->root->sxFnc.pnodeScopes, funcInfo);
  2822. Scope* bodyScope = funcInfo->GetBodyScope();
  2823. if (!paramScope->GetCanMergeWithBodyScope())
  2824. {
  2825. byteCodeFunction->SetParamAndBodyScopeNotMerged();
  2826. HomeArguments(funcInfo);
  2827. // Pop the body scope before emitting the default args
  2828. PopScope();
  2829. Assert(this->GetCurrentScope() == paramScope);
  2830. funcInfo->SetCurrentChildScope(paramScope);
  2831. }
  2832. EmitDefaultArgs(funcInfo, pnode);
  2833. if (!paramScope->GetCanMergeWithBodyScope())
  2834. {
  2835. Assert(this->GetCurrentScope() == paramScope);
  2836. // Push the body scope
  2837. PushScope(bodyScope);
  2838. funcInfo->SetCurrentChildScope(bodyScope);
  2839. // Mark the beginning of the body scope so that new scope slots can be created.
  2840. this->Writer()->Empty(Js::OpCode::BeginBodyScope);
  2841. }
  2842. }
  2843. // Emit all scope-wide function definitions before emitting function bodies
  2844. // so that calls may reference functions they precede lexically.
  2845. // Note, global eval scope is a fake local scope and is handled as if it were
  2846. // a lexical block instead of a true global scope, so do not define the functions
  2847. // here. They will be defined during BeginEmitBlock.
  2848. if (!(funcInfo->IsGlobalFunction() && this->IsEvalWithNoParentScopeInfo()))
  2849. {
  2850. // This only handles function declarations, which param scope cannot have any.
  2851. DefineFunctions(funcInfo);
  2852. }
  2853. DefineUserVars(funcInfo);
  2854. if (pnode->sxFnc.HasNonSimpleParameterList())
  2855. {
  2856. this->InitBlockScopedNonTemps(funcInfo->root->sxFnc.pnodeBodyScope, funcInfo);
  2857. }
  2858. else
  2859. {
  2860. this->InitBlockScopedNonTemps(funcInfo->root->sxFnc.pnodeScopes, funcInfo);
  2861. }
  2862. if (!pnode->sxFnc.HasNonSimpleParameterList() && funcInfo->GetHasArguments() && !NeedScopeObjectForArguments(funcInfo, pnode))
  2863. {
  2864. // If we didn't create a scope object and didn't have default args, we still need to transfer the formals to their slots.
  2865. MapFormalsWithoutRest(pnode, [&](ParseNode *pnodeArg) { EmitPropStore(pnodeArg->sxVar.sym->GetLocation(), pnodeArg->sxVar.sym, pnodeArg->sxVar.pid, funcInfo); });
  2866. }
  2867. // Rest needs to trigger use before declaration until all default args have been processed.
  2868. if (pnode->sxFnc.pnodeRest != nullptr)
  2869. {
  2870. pnode->sxFnc.pnodeRest->sxVar.sym->SetNeedDeclaration(false);
  2871. }
  2872. if (paramScope && !paramScope->GetCanMergeWithBodyScope())
  2873. {
  2874. // Emit bytecode to copy the initial values from param names to their corresponding body bindings.
  2875. // We have to do this after the rest param is marked as false for need declaration.
  2876. paramScope->ForEachSymbol([&](Symbol* param) {
  2877. Symbol* varSym = funcInfo->GetBodyScope()->FindLocalSymbol(param->GetName());
  2878. Assert(varSym || param->GetIsArguments() || pnode->sxFnc.pnodeName->sxVar.sym == param);
  2879. Assert(param->GetIsArguments() || param->IsInSlot(funcInfo));
  2880. if (varSym && varSym->GetSymbolType() == STVariable && (varSym->IsInSlot(funcInfo) || varSym->GetLocation() != Js::Constants::NoRegister))
  2881. {
  2882. // Simulating EmitPropLoad here. We can't directly call the method as we have to use the param scope specifically.
  2883. // Walking the scope chain is not possible at this time.
  2884. Js::RegSlot tempReg = funcInfo->AcquireTmpRegister();
  2885. Js::PropertyId slot = param->EnsureScopeSlot(funcInfo);
  2886. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(paramScope, slot);
  2887. Js::OpCode op = paramScope->GetIsObject() ? Js::OpCode::LdParamObjSlot : Js::OpCode::LdParamSlot;
  2888. slot = slot + (paramScope->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  2889. this->m_writer.SlotI1(op, tempReg, slot, profileId);
  2890. if (ShouldTrackDebuggerMetadata() && !varSym->GetIsArguments() && !varSym->IsInSlot(funcInfo))
  2891. {
  2892. byteCodeFunction->InsertSymbolToRegSlotList(varSym->GetName(), varSym->GetLocation(), funcInfo->varRegsCount);
  2893. }
  2894. this->EmitPropStore(tempReg, varSym, varSym->GetPid(), funcInfo);
  2895. funcInfo->ReleaseTmpRegister(tempReg);
  2896. }
  2897. });
  2898. }
  2899. if (pnode->sxFnc.pnodeBodyScope != nullptr)
  2900. {
  2901. ::BeginEmitBlock(pnode->sxFnc.pnodeBodyScope, this, funcInfo);
  2902. }
  2903. this->inPrologue = false;
  2904. if (funcInfo->IsGlobalFunction())
  2905. {
  2906. EmitGlobalBody(funcInfo);
  2907. }
  2908. else
  2909. {
  2910. EmitFunctionBody(funcInfo);
  2911. }
  2912. if (pnode->sxFnc.pnodeBodyScope != nullptr)
  2913. {
  2914. ::EndEmitBlock(pnode->sxFnc.pnodeBodyScope, this, funcInfo);
  2915. }
  2916. ::EndEmitBlock(pnode->sxFnc.pnodeScopes, this, funcInfo);
  2917. if (!this->IsInDebugMode())
  2918. {
  2919. // Release the temp registers that we reserved for inner scopes above.
  2920. if (innerScopeCount)
  2921. {
  2922. Js::RegSlot tmpReg = funcInfo->FirstInnerScopeReg() + innerScopeCount - 1;
  2923. for (uint i = 0; i < innerScopeCount; i++)
  2924. {
  2925. funcInfo->ReleaseTmpRegister(tmpReg);
  2926. tmpReg--;
  2927. }
  2928. }
  2929. }
  2930. Assert(funcInfo->firstTmpReg == firstTmpReg);
  2931. Assert(funcInfo->curTmpReg == firstTmpReg);
  2932. Assert(byteCodeFunction->GetFirstTmpReg() == firstTmpReg + byteCodeFunction->GetConstantCount());
  2933. byteCodeFunction->CheckAndSetVarCount(funcInfo->varRegsCount);
  2934. byteCodeFunction->CheckAndSetOutParamMaxDepth(funcInfo->outArgsMaxDepth);
  2935. // Do a uint32 add just to verify that we haven't overflowed the reg slot type.
  2936. UInt32Math::Add(funcInfo->varRegsCount, funcInfo->constRegsCount);
  2937. #if DBG_DUMP
  2938. if (PHASE_STATS1(Js::ByteCodePhase))
  2939. {
  2940. Output::Print(_u(" BCode: %-10d, Aux: %-10d, AuxC: %-10d Total: %-10d, %s\n"),
  2941. m_writer.ByteCodeDataSize(),
  2942. m_writer.AuxiliaryDataSize(),
  2943. m_writer.AuxiliaryContextDataSize(),
  2944. m_writer.ByteCodeDataSize() + m_writer.AuxiliaryDataSize() + m_writer.AuxiliaryContextDataSize(),
  2945. funcInfo->name);
  2946. this->scriptContext->byteCodeDataSize += m_writer.ByteCodeDataSize();
  2947. this->scriptContext->byteCodeAuxiliaryDataSize += m_writer.AuxiliaryDataSize();
  2948. this->scriptContext->byteCodeAuxiliaryContextDataSize += m_writer.AuxiliaryContextDataSize();
  2949. }
  2950. #endif
  2951. this->MapCacheIdsToPropertyIds(funcInfo);
  2952. this->MapReferencedPropertyIds(funcInfo);
  2953. Assert(this->TopFuncInfo() == funcInfo);
  2954. PopFuncInfo(_u("EmitOneFunction"));
  2955. m_writer.SetCallSiteCount(m_callSiteId);
  2956. #ifdef LOG_BYTECODE_AST_RATIO
  2957. m_writer.End(funcInfo->root->sxFnc.astSize, this->maxAstSize);
  2958. #else
  2959. m_writer.End();
  2960. #endif
  2961. }
  2962. catch (...)
  2963. {
  2964. // Failed to generate byte-code for this function body (likely OOM or stack overflow). Notify the function body so that
  2965. // it can revert intermediate state changes that may have taken place during byte code generation before the failure.
  2966. byteCodeFunction->ResetByteCodeGenState();
  2967. m_writer.Reset();
  2968. throw;
  2969. }
  2970. #ifdef PERF_HINT
  2971. if (PHASE_TRACE1(Js::PerfHintPhase) && !byteCodeFunction->GetIsGlobalFunc())
  2972. {
  2973. if (byteCodeFunction->GetHasTry())
  2974. {
  2975. WritePerfHint(PerfHints::HasTryBlock_Verbose, byteCodeFunction);
  2976. }
  2977. if (funcInfo->GetCallsEval())
  2978. {
  2979. WritePerfHint(PerfHints::CallsEval_Verbose, byteCodeFunction);
  2980. }
  2981. else if (funcInfo->GetChildCallsEval())
  2982. {
  2983. WritePerfHint(PerfHints::ChildCallsEval, byteCodeFunction);
  2984. }
  2985. }
  2986. #endif
  2987. byteCodeFunction->SetInitialDefaultEntryPoint();
  2988. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2989. if (byteCodeFunction->IsInDebugMode() != scriptContext->IsScriptContextInDebugMode()) // debug mode mismatch
  2990. {
  2991. if (m_utf8SourceInfo->GetIsLibraryCode())
  2992. {
  2993. Assert(!byteCodeFunction->IsInDebugMode()); // Library script byteCode is never in debug mode
  2994. }
  2995. else
  2996. {
  2997. Js::Throw::FatalInternalError();
  2998. }
  2999. }
  3000. #endif
  3001. #if DBG_DUMP
  3002. if (PHASE_DUMP(Js::ByteCodePhase, funcInfo->byteCodeFunction) && Js::Configuration::Global.flags.Verbose)
  3003. {
  3004. pnode->Dump();
  3005. }
  3006. if (this->Trace() || PHASE_DUMP(Js::ByteCodePhase, funcInfo->byteCodeFunction))
  3007. {
  3008. Js::ByteCodeDumper::Dump(byteCodeFunction);
  3009. }
  3010. if (PHASE_DUMP(Js::DebuggerScopePhase, funcInfo->byteCodeFunction))
  3011. {
  3012. byteCodeFunction->DumpScopes();
  3013. }
  3014. #endif
  3015. #if ENABLE_NATIVE_CODEGEN
  3016. if ((!PHASE_OFF(Js::BackEndPhase, funcInfo->byteCodeFunction))
  3017. && !this->forceNoNative
  3018. && !this->scriptContext->GetConfig()->IsNoNative())
  3019. {
  3020. GenerateFunction(this->scriptContext->GetNativeCodeGenerator(), byteCodeFunction);
  3021. }
  3022. #endif
  3023. }
  3024. void ByteCodeGenerator::MapCacheIdsToPropertyIds(FuncInfo *funcInfo)
  3025. {
  3026. Js::FunctionBody *functionBody = funcInfo->GetParsedFunctionBody();
  3027. uint rootObjectLoadInlineCacheStart = funcInfo->GetInlineCacheCount();
  3028. uint rootObjectLoadMethodInlineCacheStart = rootObjectLoadInlineCacheStart + funcInfo->GetRootObjectLoadInlineCacheCount();
  3029. uint rootObjectStoreInlineCacheStart = rootObjectLoadMethodInlineCacheStart + funcInfo->GetRootObjectLoadMethodInlineCacheCount();
  3030. uint totalFieldAccessInlineCacheCount = rootObjectStoreInlineCacheStart + funcInfo->GetRootObjectStoreInlineCacheCount();
  3031. functionBody->CreateCacheIdToPropertyIdMap(rootObjectLoadInlineCacheStart, rootObjectLoadMethodInlineCacheStart,
  3032. rootObjectStoreInlineCacheStart, totalFieldAccessInlineCacheCount, funcInfo->GetIsInstInlineCacheCount());
  3033. if (totalFieldAccessInlineCacheCount == 0)
  3034. {
  3035. return;
  3036. }
  3037. funcInfo->inlineCacheMap->Map([functionBody](Js::RegSlot regSlot, FuncInfo::InlineCacheIdMap *inlineCacheIdMap)
  3038. {
  3039. inlineCacheIdMap->Map([functionBody](Js::PropertyId propertyId, FuncInfo::InlineCacheList* inlineCacheList)
  3040. {
  3041. if (inlineCacheList)
  3042. {
  3043. inlineCacheList->Iterate([functionBody, propertyId](InlineCacheUnit cacheUnit)
  3044. {
  3045. CompileAssert(offsetof(InlineCacheUnit, cacheId) == offsetof(InlineCacheUnit, loadCacheId));
  3046. if (cacheUnit.loadCacheId != -1)
  3047. {
  3048. functionBody->SetPropertyIdForCacheId(cacheUnit.loadCacheId, propertyId);
  3049. }
  3050. if (cacheUnit.loadMethodCacheId != -1)
  3051. {
  3052. functionBody->SetPropertyIdForCacheId(cacheUnit.loadMethodCacheId, propertyId);
  3053. }
  3054. if (cacheUnit.storeCacheId != -1)
  3055. {
  3056. functionBody->SetPropertyIdForCacheId(cacheUnit.storeCacheId, propertyId);
  3057. }
  3058. });
  3059. }
  3060. });
  3061. });
  3062. funcInfo->rootObjectLoadInlineCacheMap->Map([functionBody, rootObjectLoadInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  3063. {
  3064. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectLoadInlineCacheStart, propertyId);
  3065. });
  3066. funcInfo->rootObjectLoadMethodInlineCacheMap->Map([functionBody, rootObjectLoadMethodInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  3067. {
  3068. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectLoadMethodInlineCacheStart, propertyId);
  3069. });
  3070. funcInfo->rootObjectStoreInlineCacheMap->Map([functionBody, rootObjectStoreInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  3071. {
  3072. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectStoreInlineCacheStart, propertyId);
  3073. });
  3074. SListBase<uint>::Iterator valueOfIter(&funcInfo->valueOfStoreCacheIds);
  3075. while (valueOfIter.Next())
  3076. {
  3077. functionBody->SetPropertyIdForCacheId(valueOfIter.Data(), Js::PropertyIds::valueOf);
  3078. }
  3079. SListBase<uint>::Iterator toStringIter(&funcInfo->toStringStoreCacheIds);
  3080. while (toStringIter.Next())
  3081. {
  3082. functionBody->SetPropertyIdForCacheId(toStringIter.Data(), Js::PropertyIds::toString);
  3083. }
  3084. #if DBG
  3085. functionBody->VerifyCacheIdToPropertyIdMap();
  3086. #endif
  3087. }
  3088. void ByteCodeGenerator::MapReferencedPropertyIds(FuncInfo * funcInfo)
  3089. {
  3090. Js::FunctionBody *functionBody = funcInfo->GetParsedFunctionBody();
  3091. uint referencedPropertyIdCount = funcInfo->GetReferencedPropertyIdCount();
  3092. functionBody->CreateReferencedPropertyIdMap(referencedPropertyIdCount);
  3093. funcInfo->referencedPropertyIdToMapIndex->Map([functionBody](Js::PropertyId propertyId, uint mapIndex)
  3094. {
  3095. functionBody->SetReferencedPropertyIdWithMapIndex(mapIndex, propertyId);
  3096. });
  3097. #if DBG
  3098. functionBody->VerifyReferencedPropertyIdMap();
  3099. #endif
  3100. }
  3101. void ByteCodeGenerator::EmitScopeList(ParseNode *pnode, ParseNode *breakOnBodyScopeNode)
  3102. {
  3103. while (pnode)
  3104. {
  3105. switch (pnode->nop)
  3106. {
  3107. case knopFncDecl:
  3108. #ifndef TEMP_DISABLE_ASMJS
  3109. if (pnode->sxFnc.GetAsmjsMode())
  3110. {
  3111. Js::ExclusiveContext context(this, GetScriptContext());
  3112. if (Js::AsmJSCompiler::Compile(&context, pnode, pnode->sxFnc.pnodeParams))
  3113. {
  3114. pnode = pnode->sxFnc.pnodeNext;
  3115. break;
  3116. }
  3117. else if (CONFIG_FLAG(AsmJsStopOnError))
  3118. {
  3119. exit(JSERR_AsmJsCompileError);
  3120. }
  3121. else if (!(flags & fscrDeferFncParse))
  3122. {
  3123. // If deferral is not allowed, throw and reparse everything with asm.js disabled.
  3124. throw Js::AsmJsParseException();
  3125. }
  3126. }
  3127. #endif
  3128. // FALLTHROUGH
  3129. case knopProg:
  3130. if (pnode->sxFnc.funcInfo)
  3131. {
  3132. this->StartEmitFunction(pnode);
  3133. Scope* paramScope = pnode->sxFnc.funcInfo->GetParamScope();
  3134. // Persist outer func scope info if nested func is deferred
  3135. if (CONFIG_FLAG(DeferNested))
  3136. {
  3137. FuncInfo* parentFunc = TopFuncInfo();
  3138. Js::ScopeInfo::SaveScopeInfoForDeferParse(this, parentFunc, pnode->sxFnc.funcInfo);
  3139. PushFuncInfo(_u("StartEmitFunction"), pnode->sxFnc.funcInfo);
  3140. }
  3141. if (paramScope && !paramScope->GetCanMergeWithBodyScope())
  3142. {
  3143. this->EmitScopeList(pnode->sxFnc.pnodeBodyScope->sxBlock.pnodeScopes);
  3144. }
  3145. else
  3146. {
  3147. this->EmitScopeList(pnode->sxFnc.pnodeScopes);
  3148. }
  3149. this->EmitOneFunction(pnode);
  3150. this->EndEmitFunction(pnode);
  3151. }
  3152. pnode = pnode->sxFnc.pnodeNext;
  3153. break;
  3154. case knopBlock:
  3155. this->StartEmitBlock(pnode);
  3156. this->EmitScopeList(pnode->sxBlock.pnodeScopes);
  3157. this->EndEmitBlock(pnode);
  3158. pnode = pnode->sxBlock.pnodeNext;
  3159. break;
  3160. case knopCatch:
  3161. this->StartEmitCatch(pnode);
  3162. this->EmitScopeList(pnode->sxCatch.pnodeScopes);
  3163. this->EndEmitCatch(pnode);
  3164. pnode = pnode->sxCatch.pnodeNext;
  3165. break;
  3166. case knopWith:
  3167. this->StartEmitWith(pnode);
  3168. this->EmitScopeList(pnode->sxWith.pnodeScopes);
  3169. this->EndEmitWith(pnode);
  3170. pnode = pnode->sxWith.pnodeNext;
  3171. break;
  3172. default:
  3173. AssertMsg(false, "Unexpected opcode in tree of scopes");
  3174. break;
  3175. }
  3176. if (breakOnBodyScopeNode != nullptr && breakOnBodyScopeNode == pnode)
  3177. {
  3178. break;
  3179. }
  3180. }
  3181. }
  3182. void EnsureFncDeclScopeSlot(ParseNode *pnodeFnc, FuncInfo *funcInfo)
  3183. {
  3184. if (pnodeFnc->sxFnc.pnodeName)
  3185. {
  3186. Assert(pnodeFnc->sxFnc.pnodeName->nop == knopVarDecl);
  3187. Symbol *sym = pnodeFnc->sxFnc.pnodeName->sxVar.sym;
  3188. if (sym)
  3189. {
  3190. sym->EnsureScopeSlot(funcInfo);
  3191. }
  3192. }
  3193. }
  3194. // Similar to EnsureFncScopeSlot visitor function, but verifies that a slot is needed before assigning it.
  3195. void CheckFncDeclScopeSlot(ParseNode *pnodeFnc, FuncInfo *funcInfo)
  3196. {
  3197. if (pnodeFnc->sxFnc.pnodeName && pnodeFnc->sxFnc.pnodeName->nop == knopVarDecl)
  3198. {
  3199. Assert(pnodeFnc->sxFnc.pnodeName->nop == knopVarDecl);
  3200. Symbol *sym = pnodeFnc->sxFnc.pnodeName->sxVar.sym;
  3201. if (sym && sym->NeedsSlotAlloc(funcInfo))
  3202. {
  3203. sym->EnsureScopeSlot(funcInfo);
  3204. }
  3205. }
  3206. }
  3207. void ByteCodeGenerator::EnsureSpecialScopeSlots(FuncInfo* funcInfo, Scope* scope)
  3208. {
  3209. if (scope->GetIsObject())
  3210. {
  3211. if (funcInfo->isThisLexicallyCaptured)
  3212. {
  3213. funcInfo->EnsureThisScopeSlot(scope);
  3214. }
  3215. if (((!funcInfo->IsLambda() && funcInfo->GetCallsEval())
  3216. || funcInfo->isSuperLexicallyCaptured))
  3217. {
  3218. if (funcInfo->superRegister != Js::Constants::NoRegister)
  3219. {
  3220. funcInfo->EnsureSuperScopeSlot(scope);
  3221. }
  3222. if (funcInfo->superCtorRegister != Js::Constants::NoRegister)
  3223. {
  3224. funcInfo->EnsureSuperCtorScopeSlot(scope);
  3225. }
  3226. }
  3227. if (funcInfo->isNewTargetLexicallyCaptured)
  3228. {
  3229. funcInfo->EnsureNewTargetScopeSlot(scope);
  3230. }
  3231. }
  3232. else
  3233. {
  3234. // Don't rely on the Emit() pass to assign scope slots where needed, because peeps/shortcuts
  3235. // may cause some expressions not to be emitted. Assign the slots we need before we start
  3236. // emitting the prolog.
  3237. // TODO: Investigate moving detection of non-local references to Emit() so we don't assign
  3238. // slots to symbols that are never referenced in emitted code.
  3239. if (funcInfo->isThisLexicallyCaptured)
  3240. {
  3241. funcInfo->EnsureThisScopeSlot(scope);
  3242. }
  3243. if (funcInfo->isSuperLexicallyCaptured)
  3244. {
  3245. funcInfo->EnsureSuperScopeSlot(scope);
  3246. }
  3247. if (funcInfo->isSuperCtorLexicallyCaptured)
  3248. {
  3249. funcInfo->EnsureSuperCtorScopeSlot(scope);
  3250. }
  3251. if (funcInfo->isNewTargetLexicallyCaptured)
  3252. {
  3253. funcInfo->EnsureNewTargetScopeSlot(scope);
  3254. }
  3255. }
  3256. }
  3257. void ByteCodeGenerator::StartEmitFunction(ParseNode *pnodeFnc)
  3258. {
  3259. Assert(pnodeFnc->nop == knopFncDecl || pnodeFnc->nop == knopProg);
  3260. FuncInfo *funcInfo = pnodeFnc->sxFnc.funcInfo;
  3261. if (funcInfo->byteCodeFunction->IsFunctionParsed() &&
  3262. !(flags & (fscrEval | fscrImplicitThis | fscrImplicitParents)))
  3263. {
  3264. // Only set the environment depth if it's truly known (i.e., not in eval or event handler).
  3265. funcInfo->GetParsedFunctionBody()->SetEnvDepth(this->envDepth);
  3266. }
  3267. if (funcInfo->GetCallsEval())
  3268. {
  3269. funcInfo->byteCodeFunction->SetDontInline(true);
  3270. }
  3271. Scope * const funcExprScope = funcInfo->funcExprScope;
  3272. if (funcExprScope)
  3273. {
  3274. if (funcInfo->GetCallsEval())
  3275. {
  3276. Assert(funcExprScope->GetIsObject());
  3277. }
  3278. if (funcExprScope->GetIsObject())
  3279. {
  3280. funcExprScope->SetCapturesAll(true);
  3281. funcExprScope->SetMustInstantiate(true);
  3282. PushScope(funcExprScope);
  3283. }
  3284. else
  3285. {
  3286. Symbol *sym = funcInfo->root->sxFnc.GetFuncSymbol();
  3287. if (funcInfo->paramScope->GetCanMergeWithBodyScope())
  3288. {
  3289. funcInfo->bodyScope->AddSymbol(sym);
  3290. }
  3291. else
  3292. {
  3293. funcInfo->paramScope->AddSymbol(sym);
  3294. }
  3295. }
  3296. }
  3297. Scope * const bodyScope = funcInfo->GetBodyScope();
  3298. Scope * const paramScope = funcInfo->GetParamScope();
  3299. if (pnodeFnc->nop != knopProg)
  3300. {
  3301. if (!bodyScope->GetIsObject() && NeedObjectAsFunctionScope(funcInfo, pnodeFnc))
  3302. {
  3303. Assert(bodyScope->GetIsObject());
  3304. }
  3305. if (bodyScope->GetIsObject())
  3306. {
  3307. bodyScope->SetLocation(funcInfo->frameObjRegister);
  3308. }
  3309. else
  3310. {
  3311. bodyScope->SetLocation(funcInfo->frameSlotsRegister);
  3312. }
  3313. if (!paramScope->GetCanMergeWithBodyScope())
  3314. {
  3315. if (paramScope->GetIsObject())
  3316. {
  3317. paramScope->SetLocation(funcInfo->frameObjRegister);
  3318. }
  3319. else
  3320. {
  3321. paramScope->SetLocation(funcInfo->frameSlotsRegister);
  3322. }
  3323. }
  3324. if (bodyScope->GetIsObject())
  3325. {
  3326. // Win8 908700: Disable under F12 debugger because there are too many cached scopes holding onto locals.
  3327. funcInfo->SetHasCachedScope(
  3328. !PHASE_OFF(Js::CachedScopePhase, funcInfo->byteCodeFunction) &&
  3329. !funcInfo->Escapes() &&
  3330. funcInfo->frameObjRegister != Js::Constants::NoRegister &&
  3331. !ApplyEnclosesArgs(pnodeFnc, this) &&
  3332. (PHASE_FORCE(Js::CachedScopePhase, funcInfo->byteCodeFunction) || !IsInDebugMode()));
  3333. if (funcInfo->GetHasCachedScope())
  3334. {
  3335. Assert(funcInfo->funcObjRegister == Js::Constants::NoRegister);
  3336. Symbol *funcSym = funcInfo->root->sxFnc.GetFuncSymbol();
  3337. if (funcSym && funcSym->GetFuncExpr())
  3338. {
  3339. if (funcSym->GetLocation() == Js::Constants::NoRegister)
  3340. {
  3341. funcInfo->funcObjRegister = funcInfo->NextVarRegister();
  3342. }
  3343. else
  3344. {
  3345. funcInfo->funcObjRegister = funcSym->GetLocation();
  3346. }
  3347. }
  3348. else
  3349. {
  3350. funcInfo->funcObjRegister = funcInfo->NextVarRegister();
  3351. }
  3352. Assert(funcInfo->funcObjRegister != Js::Constants::NoRegister);
  3353. }
  3354. ParseNode *pnode;
  3355. Symbol *sym;
  3356. // Turns on capturesAll temporarily if func has deferred child, so that the following EnsureScopeSlot
  3357. // will allocate scope slots no matter if symbol hasNonLocalRefence or not.
  3358. Js::ScopeInfo::AutoCapturesAllScope autoCapturesAllScope(bodyScope, funcInfo->HasDeferredChild());
  3359. if (funcInfo->GetHasArguments())
  3360. {
  3361. // Process function's formal parameters
  3362. MapFormals(pnodeFnc, [&](ParseNode *pnode)
  3363. {
  3364. if (pnode->IsVarLetOrConst())
  3365. {
  3366. pnode->sxVar.sym->EnsureScopeSlot(funcInfo);
  3367. }
  3368. });
  3369. MapFormalsFromPattern(pnodeFnc, [&](ParseNode *pnode) { pnode->sxVar.sym->EnsureScopeSlot(funcInfo); });
  3370. // Only allocate scope slot for "arguments" when really necessary. "hasDeferredChild"
  3371. // doesn't require scope slot for "arguments" because inner functions can't access
  3372. // outer function's arguments directly.
  3373. sym = funcInfo->GetArgumentsSymbol();
  3374. Assert(sym);
  3375. if (sym->GetHasNonLocalReference() || autoCapturesAllScope.OldCapturesAll())
  3376. {
  3377. sym->EnsureScopeSlot(funcInfo);
  3378. }
  3379. }
  3380. sym = funcInfo->root->sxFnc.GetFuncSymbol();
  3381. if (sym && sym->NeedsSlotAlloc(funcInfo))
  3382. {
  3383. if (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject())
  3384. {
  3385. sym->SetScopeSlot(0);
  3386. }
  3387. else if (funcInfo->GetFuncExprNameReference())
  3388. {
  3389. sym->EnsureScopeSlot(funcInfo);
  3390. }
  3391. }
  3392. if (!funcInfo->GetHasArguments())
  3393. {
  3394. Symbol *formal;
  3395. Js::ArgSlot pos = 1;
  3396. auto moveArgToReg = [&](ParseNode *pnode)
  3397. {
  3398. if (pnode->IsVarLetOrConst())
  3399. {
  3400. formal = pnode->sxVar.sym;
  3401. // Get the param from its argument position into its assigned register.
  3402. // The position should match the location; otherwise, it has been shadowed by parameter with the same name.
  3403. if (formal->GetLocation() + 1 == pos)
  3404. {
  3405. pnode->sxVar.sym->EnsureScopeSlot(funcInfo);
  3406. }
  3407. }
  3408. pos++;
  3409. };
  3410. MapFormals(pnodeFnc, moveArgToReg);
  3411. MapFormalsFromPattern(pnodeFnc, [&](ParseNode *pnode) { pnode->sxVar.sym->EnsureScopeSlot(funcInfo); });
  3412. }
  3413. if (paramScope->GetCanMergeWithBodyScope())
  3414. {
  3415. this->EnsureSpecialScopeSlots(funcInfo, bodyScope);
  3416. }
  3417. else
  3418. {
  3419. this->EnsureSpecialScopeSlots(funcInfo, paramScope);
  3420. }
  3421. auto ensureFncDeclScopeSlots = [&](ParseNode *pnodeScope)
  3422. {
  3423. for (pnode = pnodeScope; pnode;)
  3424. {
  3425. switch (pnode->nop)
  3426. {
  3427. case knopFncDecl:
  3428. if (pnode->sxFnc.IsDeclaration())
  3429. {
  3430. EnsureFncDeclScopeSlot(pnode, funcInfo);
  3431. }
  3432. pnode = pnode->sxFnc.pnodeNext;
  3433. break;
  3434. case knopBlock:
  3435. pnode = pnode->sxBlock.pnodeNext;
  3436. break;
  3437. case knopCatch:
  3438. pnode = pnode->sxCatch.pnodeNext;
  3439. break;
  3440. case knopWith:
  3441. pnode = pnode->sxWith.pnodeNext;
  3442. break;
  3443. }
  3444. }
  3445. };
  3446. pnodeFnc->sxFnc.MapContainerScopes(ensureFncDeclScopeSlots);
  3447. for (pnode = pnodeFnc->sxFnc.pnodeVars; pnode; pnode = pnode->sxVar.pnodeNext)
  3448. {
  3449. sym = pnode->sxVar.sym;
  3450. if (!(pnode->sxVar.isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  3451. {
  3452. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  3453. {
  3454. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  3455. }
  3456. if (sym->GetSymbolType() == STVariable && !sym->GetIsArguments())
  3457. {
  3458. sym->EnsureScopeSlot(funcInfo);
  3459. }
  3460. }
  3461. }
  3462. if (pnodeFnc->sxFnc.pnodeBody)
  3463. {
  3464. Assert(pnodeFnc->sxFnc.pnodeScopes->nop == knopBlock);
  3465. this->EnsureLetConstScopeSlots(pnodeFnc->sxFnc.pnodeBodyScope, funcInfo);
  3466. }
  3467. }
  3468. else
  3469. {
  3470. ParseNode *pnode;
  3471. Symbol *sym;
  3472. if (paramScope->GetCanMergeWithBodyScope())
  3473. {
  3474. this->EnsureSpecialScopeSlots(funcInfo, bodyScope);
  3475. }
  3476. else
  3477. {
  3478. this->EnsureSpecialScopeSlots(funcInfo, paramScope);
  3479. }
  3480. pnodeFnc->sxFnc.MapContainerScopes([&](ParseNode *pnodeScope) { this->EnsureFncScopeSlots(pnodeScope, funcInfo); });
  3481. for (pnode = pnodeFnc->sxFnc.pnodeVars; pnode; pnode = pnode->sxVar.pnodeNext)
  3482. {
  3483. sym = pnode->sxVar.sym;
  3484. if (!(pnode->sxVar.isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  3485. {
  3486. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  3487. {
  3488. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  3489. }
  3490. if (sym->GetSymbolType() == STVariable && sym->NeedsSlotAlloc(funcInfo) && !sym->GetIsArguments())
  3491. {
  3492. sym->EnsureScopeSlot(funcInfo);
  3493. }
  3494. }
  3495. }
  3496. auto ensureScopeSlot = [&](ParseNode *pnode)
  3497. {
  3498. if (pnode->IsVarLetOrConst())
  3499. {
  3500. sym = pnode->sxVar.sym;
  3501. if (sym->GetSymbolType() == STFormal && sym->NeedsSlotAlloc(funcInfo))
  3502. {
  3503. sym->EnsureScopeSlot(funcInfo);
  3504. }
  3505. }
  3506. };
  3507. // Process function's formal parameters
  3508. MapFormals(pnodeFnc, ensureScopeSlot);
  3509. MapFormalsFromPattern(pnodeFnc, ensureScopeSlot);
  3510. if (pnodeFnc->sxFnc.pnodeBody)
  3511. {
  3512. this->EnsureLetConstScopeSlots(pnodeFnc->sxFnc.pnodeScopes, funcInfo);
  3513. this->EnsureLetConstScopeSlots(pnodeFnc->sxFnc.pnodeBodyScope, funcInfo);
  3514. }
  3515. }
  3516. if (!paramScope->GetCanMergeWithBodyScope() && bodyScope->GetScopeSlotCount() == 0 && !bodyScope->GetHasOwnLocalInClosure())
  3517. {
  3518. // When we have split scope the body scope may be wrongly marked as must instantiate even though the capture occurred
  3519. // in param scope. This check is to make sure if no capture occurs in body scope make in not must instantiate.
  3520. bodyScope->SetMustInstantiate(false);
  3521. }
  3522. else
  3523. {
  3524. bodyScope->SetMustInstantiate(funcInfo->frameObjRegister != Js::Constants::NoRegister || funcInfo->frameSlotsRegister != Js::Constants::NoRegister);
  3525. }
  3526. paramScope->SetMustInstantiate(!paramScope->GetCanMergeWithBodyScope());
  3527. }
  3528. else
  3529. {
  3530. bool newScopeForEval = (funcInfo->byteCodeFunction->GetIsStrictMode() && (this->GetFlags() & fscrEval));
  3531. if (newScopeForEval)
  3532. {
  3533. Assert(bodyScope->GetIsObject());
  3534. }
  3535. }
  3536. if (paramScope && !paramScope->GetCanMergeWithBodyScope())
  3537. {
  3538. ParseNodePtr paramBlock = pnodeFnc->sxFnc.pnodeScopes;
  3539. Assert(paramBlock->nop == knopBlock && paramBlock->sxBlock.blockType == Parameter);
  3540. PushScope(paramScope);
  3541. // While emitting the functions we have to stop when we see the body scope block.
  3542. // Otherwise functions defined in the body scope will not be able to get the right references.
  3543. this->EmitScopeList(paramBlock->sxBlock.pnodeScopes, pnodeFnc->sxFnc.pnodeBodyScope);
  3544. Assert(this->GetCurrentScope() == paramScope);
  3545. }
  3546. PushScope(bodyScope);
  3547. }
  3548. void ByteCodeGenerator::EmitModuleExportAccess(Symbol* sym, Js::OpCode opcode, Js::RegSlot location, FuncInfo* funcInfo)
  3549. {
  3550. if (EnsureSymbolModuleSlots(sym, funcInfo))
  3551. {
  3552. this->Writer()->SlotI2(opcode, location, sym->GetModuleIndex(), sym->GetScopeSlot());
  3553. }
  3554. else
  3555. {
  3556. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(ERRInvalidExportName));
  3557. if (opcode == Js::OpCode::LdModuleSlot)
  3558. {
  3559. this->Writer()->Reg1(Js::OpCode::LdUndef, location);
  3560. }
  3561. }
  3562. }
  3563. bool ByteCodeGenerator::EnsureSymbolModuleSlots(Symbol* sym, FuncInfo* funcInfo)
  3564. {
  3565. Assert(sym->GetIsModuleExportStorage());
  3566. if (sym->GetModuleIndex() != Js::Constants::NoProperty && sym->GetScopeSlot() != Js::Constants::NoProperty)
  3567. {
  3568. return true;
  3569. }
  3570. Js::JavascriptLibrary* library = this->GetScriptContext()->GetLibrary();
  3571. library->EnsureModuleRecordList();
  3572. uint moduleIndex = this->GetModuleID();
  3573. uint moduleSlotIndex;
  3574. Js::SourceTextModuleRecord* moduleRecord = library->GetModuleRecord(moduleIndex);
  3575. if (sym->GetIsModuleImport())
  3576. {
  3577. Js::PropertyId localImportNameId = sym->EnsurePosition(funcInfo);
  3578. Js::ModuleNameRecord* moduleNameRecord = nullptr;
  3579. if (!moduleRecord->ResolveImport(localImportNameId, &moduleNameRecord))
  3580. {
  3581. return false;
  3582. }
  3583. AnalysisAssert(moduleNameRecord != nullptr);
  3584. Assert(moduleNameRecord->module->IsSourceTextModuleRecord());
  3585. Js::SourceTextModuleRecord* resolvedModuleRecord = (Js::SourceTextModuleRecord*)moduleNameRecord->module;
  3586. moduleIndex = resolvedModuleRecord->GetModuleId();
  3587. moduleSlotIndex = resolvedModuleRecord->GetLocalExportSlotIndexByLocalName(moduleNameRecord->bindingName);
  3588. }
  3589. else
  3590. {
  3591. Js::PropertyId exportNameId = sym->EnsurePosition(funcInfo);
  3592. moduleSlotIndex = moduleRecord->GetLocalExportSlotIndexByLocalName(exportNameId);
  3593. }
  3594. sym->SetModuleIndex(moduleIndex);
  3595. sym->SetScopeSlot(moduleSlotIndex);
  3596. return true;
  3597. }
  3598. void ByteCodeGenerator::EmitAssignmentToDefaultModuleExport(ParseNode* pnode, FuncInfo* funcInfo)
  3599. {
  3600. // We are assigning pnode to the default export of the current module.
  3601. uint moduleIndex = this->GetModuleID();
  3602. Js::JavascriptLibrary* library = this->GetScriptContext()->GetLibrary();
  3603. library->EnsureModuleRecordList();
  3604. Js::SourceTextModuleRecord* moduleRecord = library->GetModuleRecord(moduleIndex);
  3605. uint moduleSlotIndex = moduleRecord->GetLocalExportSlotIndexByExportName(Js::PropertyIds::default_);
  3606. this->Writer()->SlotI2(Js::OpCode::StModuleSlot, pnode->location, moduleIndex, moduleSlotIndex);
  3607. }
  3608. void ByteCodeGenerator::EnsureLetConstScopeSlots(ParseNode *pnodeBlock, FuncInfo *funcInfo)
  3609. {
  3610. bool hasNonLocalReference = pnodeBlock->sxBlock.GetCallsEval() || pnodeBlock->sxBlock.GetChildCallsEval();
  3611. auto ensureLetConstSlots = ([this, pnodeBlock, funcInfo, hasNonLocalReference](ParseNode *pnode)
  3612. {
  3613. Symbol *sym = pnode->sxVar.sym;
  3614. sym->EnsureScopeSlot(funcInfo);
  3615. if (hasNonLocalReference)
  3616. {
  3617. sym->SetHasNonLocalReference(true, this);
  3618. }
  3619. });
  3620. IterateBlockScopedVariables(pnodeBlock, ensureLetConstSlots);
  3621. }
  3622. void ByteCodeGenerator::EnsureFncScopeSlots(ParseNode *pnode, FuncInfo *funcInfo)
  3623. {
  3624. while (pnode)
  3625. {
  3626. switch (pnode->nop)
  3627. {
  3628. case knopFncDecl:
  3629. if (pnode->sxFnc.IsDeclaration())
  3630. {
  3631. CheckFncDeclScopeSlot(pnode, funcInfo);
  3632. }
  3633. pnode = pnode->sxFnc.pnodeNext;
  3634. break;
  3635. case knopBlock:
  3636. pnode = pnode->sxBlock.pnodeNext;
  3637. break;
  3638. case knopCatch:
  3639. pnode = pnode->sxCatch.pnodeNext;
  3640. break;
  3641. case knopWith:
  3642. pnode = pnode->sxWith.pnodeNext;
  3643. break;
  3644. }
  3645. }
  3646. }
  3647. void ByteCodeGenerator::EndEmitFunction(ParseNode *pnodeFnc)
  3648. {
  3649. Assert(pnodeFnc->nop == knopFncDecl || pnodeFnc->nop == knopProg);
  3650. Assert(pnodeFnc->nop == knopFncDecl && currentScope->GetEnclosingScope() != nullptr || pnodeFnc->nop == knopProg);
  3651. PopScope(); // function body
  3652. FuncInfo *funcInfo = pnodeFnc->sxFnc.funcInfo;
  3653. Scope* paramScope = funcInfo->paramScope;
  3654. if (paramScope && !paramScope->GetCanMergeWithBodyScope())
  3655. {
  3656. Assert(this->GetCurrentScope() == paramScope);
  3657. PopScope(); // Pop the param scope
  3658. }
  3659. Scope *scope = funcInfo->funcExprScope;
  3660. if (scope && scope->GetMustInstantiate())
  3661. {
  3662. Assert(currentScope == scope);
  3663. PopScope();
  3664. }
  3665. if (CONFIG_FLAG(DeferNested))
  3666. {
  3667. Assert(funcInfo == this->TopFuncInfo());
  3668. PopFuncInfo(_u("EndEmitFunction"));
  3669. }
  3670. }
  3671. void ByteCodeGenerator::StartEmitCatch(ParseNode *pnodeCatch)
  3672. {
  3673. Assert(pnodeCatch->nop == knopCatch);
  3674. Scope *scope = pnodeCatch->sxCatch.scope;
  3675. FuncInfo *funcInfo = scope->GetFunc();
  3676. // 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).
  3677. if (funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval() || (this->flags & (fscrEval | fscrImplicitThis | fscrImplicitParents)))
  3678. {
  3679. scope->SetIsObject();
  3680. }
  3681. if (pnodeCatch->sxCatch.pnodeParam->nop == knopParamPattern)
  3682. {
  3683. scope->SetCapturesAll(funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval());
  3684. scope->SetMustInstantiate(scope->Count() > 0 && (scope->GetMustInstantiate() || scope->GetCapturesAll() || funcInfo->IsGlobalFunction()));
  3685. Parser::MapBindIdentifier(pnodeCatch->sxCatch.pnodeParam->sxParamPattern.pnode1, [&](ParseNodePtr item)
  3686. {
  3687. Symbol *sym = item->sxVar.sym;
  3688. if (funcInfo->IsGlobalFunction())
  3689. {
  3690. sym->SetIsGlobalCatch(true);
  3691. }
  3692. Assert(sym->GetScopeSlot() == Js::Constants::NoProperty);
  3693. if (sym->NeedsSlotAlloc(funcInfo))
  3694. {
  3695. sym->EnsureScopeSlot(funcInfo);
  3696. }
  3697. });
  3698. // In the case of pattern we will always going to push the scope.
  3699. PushScope(scope);
  3700. }
  3701. else
  3702. {
  3703. Symbol *sym = pnodeCatch->sxCatch.pnodeParam->sxPid.sym;
  3704. // Catch object is stored in the catch scope if there may be an ambiguous lookup or a var declaration that hides it.
  3705. scope->SetCapturesAll(funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval() || sym->GetHasNonLocalReference());
  3706. scope->SetMustInstantiate(scope->GetCapturesAll() || funcInfo->IsGlobalFunction() || currentScope != funcInfo->GetBodyScope());
  3707. if (funcInfo->IsGlobalFunction())
  3708. {
  3709. sym->SetIsGlobalCatch(true);
  3710. }
  3711. if (scope->GetMustInstantiate())
  3712. {
  3713. // Since there is only one symbol we are pushing to slot.
  3714. // Also in order to make IsInSlot to return true - forcing the sym-has-non-local-reference.
  3715. sym->SetHasNonLocalReference(true, this);
  3716. sym->EnsureScopeSlot(funcInfo);
  3717. PushScope(scope);
  3718. }
  3719. else
  3720. {
  3721. // Add it to the parent function's scope and treat it like any other local.
  3722. // We can only do this if we don't need to get the symbol from a slot, though, because adding it to the
  3723. // parent's scope object on entry to the catch could re-size the slot array.
  3724. funcInfo->bodyScope->AddSymbol(sym);
  3725. }
  3726. }
  3727. }
  3728. void ByteCodeGenerator::EndEmitCatch(ParseNode *pnodeCatch)
  3729. {
  3730. Assert(pnodeCatch->nop == knopCatch);
  3731. if (pnodeCatch->sxCatch.scope->GetMustInstantiate() || pnodeCatch->sxCatch.pnodeParam->nop == knopParamPattern)
  3732. {
  3733. Assert(currentScope == pnodeCatch->sxCatch.scope);
  3734. PopScope();
  3735. }
  3736. }
  3737. void ByteCodeGenerator::StartEmitBlock(ParseNode *pnodeBlock)
  3738. {
  3739. if (!BlockHasOwnScope(pnodeBlock, this))
  3740. {
  3741. return;
  3742. }
  3743. Assert(pnodeBlock->nop == knopBlock);
  3744. PushBlock(pnodeBlock);
  3745. Scope *scope = pnodeBlock->sxBlock.scope;
  3746. if (pnodeBlock->sxBlock.GetCallsEval() || pnodeBlock->sxBlock.GetChildCallsEval() || (this->flags & (fscrEval | fscrImplicitThis | fscrImplicitParents)))
  3747. {
  3748. Assert(scope->GetIsObject());
  3749. }
  3750. // TODO: Consider nested deferred parsing.
  3751. if (scope->GetMustInstantiate())
  3752. {
  3753. FuncInfo *funcInfo = scope->GetFunc();
  3754. if (scope->IsGlobalEvalBlockScope() && funcInfo->isThisLexicallyCaptured)
  3755. {
  3756. funcInfo->EnsureThisScopeSlot(funcInfo->GetBodyScope());
  3757. }
  3758. this->EnsureFncScopeSlots(pnodeBlock->sxBlock.pnodeScopes, funcInfo);
  3759. this->EnsureLetConstScopeSlots(pnodeBlock, funcInfo);
  3760. PushScope(scope);
  3761. }
  3762. }
  3763. void ByteCodeGenerator::EndEmitBlock(ParseNode *pnodeBlock)
  3764. {
  3765. if (!BlockHasOwnScope(pnodeBlock, this))
  3766. {
  3767. return;
  3768. }
  3769. Assert(pnodeBlock->nop == knopBlock);
  3770. Scope *scope = pnodeBlock->sxBlock.scope;
  3771. if (scope && scope->GetMustInstantiate())
  3772. {
  3773. Assert(currentScope == pnodeBlock->sxBlock.scope);
  3774. PopScope();
  3775. }
  3776. PopBlock();
  3777. }
  3778. void ByteCodeGenerator::StartEmitWith(ParseNode *pnodeWith)
  3779. {
  3780. Assert(pnodeWith->nop == knopWith);
  3781. Scope *scope = pnodeWith->sxWith.scope;
  3782. Assert(scope->GetIsObject());
  3783. PushScope(scope);
  3784. }
  3785. void ByteCodeGenerator::EndEmitWith(ParseNode *pnodeWith)
  3786. {
  3787. Assert(pnodeWith->nop == knopWith);
  3788. Assert(currentScope == pnodeWith->sxWith.scope);
  3789. PopScope();
  3790. }
  3791. Js::RegSlot ByteCodeGenerator::PrependLocalScopes(Js::RegSlot evalEnv, Js::RegSlot tempLoc, FuncInfo *funcInfo)
  3792. {
  3793. Scope *currScope = this->currentScope;
  3794. Scope *funcScope = funcInfo->GetCurrentChildScope() ? funcInfo->GetCurrentChildScope() : funcInfo->GetBodyScope();
  3795. if (currScope == funcScope)
  3796. {
  3797. return evalEnv;
  3798. }
  3799. bool acquireTempLoc = tempLoc == Js::Constants::NoRegister;
  3800. if (acquireTempLoc)
  3801. {
  3802. tempLoc = funcInfo->AcquireTmpRegister();
  3803. }
  3804. // The with/catch objects must be prepended to the environment we pass to eval() or to a func declared inside with,
  3805. // but the list must first be reversed so that innermost scopes appear first in the list.
  3806. while (currScope != funcScope)
  3807. {
  3808. Scope *innerScope;
  3809. for (innerScope = currScope; innerScope->GetEnclosingScope() != funcScope; innerScope = innerScope->GetEnclosingScope())
  3810. ;
  3811. if (innerScope->GetMustInstantiate())
  3812. {
  3813. if (!innerScope->HasInnerScopeIndex())
  3814. {
  3815. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  3816. {
  3817. this->m_writer.Reg2(Js::OpCode::LdInnerFrameDisplayNoParent, tempLoc, innerScope->GetLocation());
  3818. }
  3819. else
  3820. {
  3821. this->m_writer.Reg3(Js::OpCode::LdInnerFrameDisplay, tempLoc, innerScope->GetLocation(), evalEnv);
  3822. }
  3823. }
  3824. else
  3825. {
  3826. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  3827. {
  3828. this->m_writer.Reg1Unsigned1(Js::OpCode::LdIndexedFrameDisplayNoParent, tempLoc, innerScope->GetInnerScopeIndex());
  3829. }
  3830. else
  3831. {
  3832. this->m_writer.Reg2Int1(Js::OpCode::LdIndexedFrameDisplay, tempLoc, evalEnv, innerScope->GetInnerScopeIndex());
  3833. }
  3834. }
  3835. evalEnv = tempLoc;
  3836. }
  3837. funcScope = innerScope;
  3838. }
  3839. if (acquireTempLoc)
  3840. {
  3841. funcInfo->ReleaseTmpRegister(tempLoc);
  3842. }
  3843. return evalEnv;
  3844. }
  3845. void ByteCodeGenerator::EmitLoadInstance(Symbol *sym, IdentPtr pid, Js::RegSlot *pThisLocation, Js::RegSlot *pInstLocation, FuncInfo *funcInfo)
  3846. {
  3847. Js::ByteCodeLabel doneLabel = 0;
  3848. bool fLabelDefined = false;
  3849. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  3850. Js::RegSlot thisLocation = *pThisLocation;
  3851. Js::RegSlot instLocation = *pInstLocation;
  3852. Js::PropertyId envIndex = -1;
  3853. Scope *scope = nullptr;
  3854. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  3855. Assert(symScope);
  3856. for (;;)
  3857. {
  3858. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  3859. if (scope == this->globalScope)
  3860. {
  3861. break;
  3862. }
  3863. if (scope != symScope)
  3864. {
  3865. // We're not sure where the function is (eval/with/etc).
  3866. // So we're going to need registers to hold the instance where we (dynamically) find
  3867. // the function, and possibly to hold the "this" pointer we will pass to it.
  3868. // Assign them here so that they can't overlap with the scopeLocation assigned below.
  3869. // Otherwise we wind up with temp lifetime confusion in the IRBuilder. (Win8 281689)
  3870. if (instLocation == Js::Constants::NoRegister)
  3871. {
  3872. instLocation = funcInfo->AcquireTmpRegister();
  3873. // The "this" pointer will not be the same as the instance, so give it its own register.
  3874. thisLocation = funcInfo->AcquireTmpRegister();
  3875. }
  3876. }
  3877. if (envIndex == -1)
  3878. {
  3879. Assert(funcInfo == scope->GetFunc());
  3880. scopeLocation = scope->GetLocation();
  3881. }
  3882. if (scope == symScope)
  3883. {
  3884. break;
  3885. }
  3886. // Found a scope to which the property may have been added.
  3887. Assert(scope && scope->GetIsDynamic());
  3888. if (!fLabelDefined)
  3889. {
  3890. fLabelDefined = true;
  3891. doneLabel = this->m_writer.DefineLabel();
  3892. }
  3893. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  3894. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  3895. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  3896. if (envIndex != -1)
  3897. {
  3898. this->m_writer.BrEnvProperty(
  3899. Js::OpCode::BrOnNoEnvProperty, nextLabel,
  3900. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  3901. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  3902. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  3903. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, tmpReg,
  3904. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  3905. Js::OpCode op = unwrapWithObj ? Js::OpCode::UnwrapWithObj : Js::OpCode::Ld_A;
  3906. this->m_writer.Reg2(op, instLocation, tmpReg);
  3907. if (thisLocation != Js::Constants::NoRegister)
  3908. {
  3909. this->m_writer.Reg2(op, thisLocation, tmpReg);
  3910. }
  3911. funcInfo->ReleaseTmpRegister(tmpReg);
  3912. }
  3913. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  3914. {
  3915. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  3916. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  3917. Assert(!unwrapWithObj);
  3918. this->m_writer.Reg1(Js::OpCode::LdLocalObj, instLocation);
  3919. if (thisLocation != Js::Constants::NoRegister)
  3920. {
  3921. this->m_writer.Reg1(Js::OpCode::LdLocalObj, thisLocation);
  3922. }
  3923. }
  3924. else
  3925. {
  3926. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  3927. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  3928. Js::OpCode op = unwrapWithObj ? Js::OpCode::UnwrapWithObj : Js::OpCode::Ld_A;
  3929. this->m_writer.Reg2(op, instLocation, scopeLocation);
  3930. if (thisLocation != Js::Constants::NoRegister)
  3931. {
  3932. this->m_writer.Reg2(op, thisLocation, scopeLocation);
  3933. }
  3934. }
  3935. this->m_writer.Br(doneLabel);
  3936. this->m_writer.MarkLabel(nextLabel);
  3937. }
  3938. if (sym != nullptr && sym->GetIsModuleExportStorage())
  3939. {
  3940. instLocation = Js::Constants::NoRegister;
  3941. }
  3942. else if (sym == nullptr || sym->GetIsGlobal())
  3943. {
  3944. if (this->flags & (fscrEval | fscrImplicitThis | fscrImplicitParents))
  3945. {
  3946. // Load of a symbol with unknown scope from within eval.
  3947. // Get it from the closure environment.
  3948. if (instLocation == Js::Constants::NoRegister)
  3949. {
  3950. instLocation = funcInfo->AcquireTmpRegister();
  3951. }
  3952. // TODO: It should be possible to avoid this double call to ScopedLdInst by having it return both
  3953. // results at once. The reason for the uncertainty here is that we don't know whether the callee
  3954. // belongs to a "with" object. If it does, we have to pass the "with" object as "this"; in all other
  3955. // cases, we pass "undefined". For now, there are apparently no significant performance issues.
  3956. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  3957. if (thisLocation == Js::Constants::NoRegister)
  3958. {
  3959. thisLocation = funcInfo->AcquireTmpRegister();
  3960. }
  3961. this->m_writer.ScopedProperty2(Js::OpCode::ScopedLdInst, instLocation,
  3962. funcInfo->FindOrAddReferencedPropertyId(propertyId), thisLocation);
  3963. }
  3964. else
  3965. {
  3966. if (instLocation == Js::Constants::NoRegister)
  3967. {
  3968. instLocation = ByteCodeGenerator::RootObjectRegister;
  3969. }
  3970. else
  3971. {
  3972. this->m_writer.Reg2(Js::OpCode::Ld_A, instLocation, ByteCodeGenerator::RootObjectRegister);
  3973. }
  3974. if (thisLocation == Js::Constants::NoRegister)
  3975. {
  3976. thisLocation = funcInfo->undefinedConstantRegister;
  3977. }
  3978. else
  3979. {
  3980. this->m_writer.Reg2(Js::OpCode::Ld_A, thisLocation, funcInfo->undefinedConstantRegister);
  3981. }
  3982. }
  3983. }
  3984. else if (instLocation != Js::Constants::NoRegister)
  3985. {
  3986. if (envIndex != -1)
  3987. {
  3988. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation,
  3989. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  3990. }
  3991. else if (scope->HasInnerScopeIndex())
  3992. {
  3993. this->m_writer.Reg1Unsigned1(Js::OpCode::LdInnerScope, instLocation, scope->GetInnerScopeIndex());
  3994. }
  3995. else if (symScope != funcInfo->GetBodyScope())
  3996. {
  3997. this->m_writer.Reg2(Js::OpCode::Ld_A, instLocation, scopeLocation);
  3998. }
  3999. else
  4000. {
  4001. Assert(funcInfo->frameObjRegister != Js::Constants::NoRegister);
  4002. this->m_writer.Reg1(Js::OpCode::LdLocalObj, instLocation);
  4003. }
  4004. if (thisLocation != Js::Constants::NoRegister)
  4005. {
  4006. this->m_writer.Reg2(Js::OpCode::Ld_A, thisLocation, funcInfo->undefinedConstantRegister);
  4007. }
  4008. else
  4009. {
  4010. thisLocation = funcInfo->undefinedConstantRegister;
  4011. }
  4012. }
  4013. *pThisLocation = thisLocation;
  4014. *pInstLocation = instLocation;
  4015. if (fLabelDefined)
  4016. {
  4017. this->m_writer.MarkLabel(doneLabel);
  4018. }
  4019. }
  4020. void ByteCodeGenerator::EmitGlobalFncDeclInit(Js::RegSlot rhsLocation, Js::PropertyId propertyId, FuncInfo * funcInfo)
  4021. {
  4022. // Note: declared variables and assignments in the global function go to the root object directly.
  4023. if (this->flags & fscrEval)
  4024. {
  4025. // Func decl's always get their init values before any use, so we don't pre-initialize the property to undef.
  4026. // That means that we have to use ScopedInitFld so that we initialize the property on the right instance
  4027. // even if the instance doesn't have the property yet (i.e., collapse the init-to-undef and the store
  4028. // into one operation). See WOOB 1121763 and 1120973.
  4029. this->m_writer.ScopedProperty(Js::OpCode::ScopedInitFunc, rhsLocation,
  4030. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4031. }
  4032. else
  4033. {
  4034. this->EmitPatchableRootProperty(Js::OpCode::InitRootFld, rhsLocation, propertyId, false, true, funcInfo);
  4035. }
  4036. }
  4037. void
  4038. ByteCodeGenerator::EmitPatchableRootProperty(Js::OpCode opcode,
  4039. Js::RegSlot regSlot, Js::PropertyId propertyId, bool isLoadMethod, bool isStore, FuncInfo * funcInfo)
  4040. {
  4041. uint cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, isLoadMethod, isStore);
  4042. this->m_writer.PatchableRootProperty(opcode, regSlot, cacheId, isLoadMethod, isStore);
  4043. }
  4044. void ByteCodeGenerator::EmitLocalPropInit(Js::RegSlot rhsLocation, Symbol *sym, FuncInfo *funcInfo)
  4045. {
  4046. Scope *scope = sym->GetScope();
  4047. // Check consistency of sym->IsInSlot.
  4048. Assert(sym->NeedsSlotAlloc(funcInfo) || sym->GetScopeSlot() == Js::Constants::NoProperty);
  4049. // Arrived at the scope in which the property was defined.
  4050. if (sym->NeedsSlotAlloc(funcInfo))
  4051. {
  4052. // The property is in memory rather than register. We'll have to load it from the slots.
  4053. if (scope->GetIsObject())
  4054. {
  4055. Assert(!this->TopFuncInfo()->GetParsedFunctionBody()->DoStackNestedFunc());
  4056. Js::PropertyId propertyId = sym->EnsurePosition(this);
  4057. Js::RegSlot objReg;
  4058. if (scope->HasInnerScopeIndex())
  4059. {
  4060. objReg = funcInfo->InnerScopeToRegSlot(scope);
  4061. }
  4062. else
  4063. {
  4064. objReg = scope->GetLocation();
  4065. }
  4066. uint cacheId = funcInfo->FindOrAddInlineCacheId(objReg, propertyId, false, true);
  4067. Js::OpCode op = this->GetInitFldOp(scope, objReg, funcInfo, sym->GetIsNonSimpleParameter());
  4068. if (objReg != Js::Constants::NoRegister && objReg == funcInfo->frameObjRegister)
  4069. {
  4070. this->m_writer.ElementP(op, rhsLocation, cacheId);
  4071. }
  4072. else if (scope->HasInnerScopeIndex())
  4073. {
  4074. this->m_writer.ElementPIndexed(op, rhsLocation, scope->GetInnerScopeIndex(), cacheId);
  4075. }
  4076. else
  4077. {
  4078. this->m_writer.PatchableProperty(op, rhsLocation, scope->GetLocation(), cacheId);
  4079. }
  4080. }
  4081. else
  4082. {
  4083. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4084. Js::PropertyId slot = sym->EnsureScopeSlot(funcInfo);
  4085. Js::RegSlot slotReg = scope->GetCanMerge() ? funcInfo->frameSlotsRegister : scope->GetLocation();
  4086. // Now store the property to its slot.
  4087. Js::OpCode op = this->GetStSlotOp(scope, -1, slotReg, false, funcInfo);
  4088. if (slotReg != Js::Constants::NoRegister && slotReg == funcInfo->frameSlotsRegister)
  4089. {
  4090. this->m_writer.SlotI1(op, rhsLocation, slot + Js::ScopeSlots::FirstSlotIndex);
  4091. }
  4092. else
  4093. {
  4094. this->m_writer.SlotI2(op, rhsLocation, scope->GetInnerScopeIndex(), slot + Js::ScopeSlots::FirstSlotIndex);
  4095. }
  4096. }
  4097. }
  4098. if (sym->GetLocation() != Js::Constants::NoRegister && rhsLocation != sym->GetLocation())
  4099. {
  4100. this->m_writer.Reg2(Js::OpCode::Ld_A, sym->GetLocation(), rhsLocation);
  4101. }
  4102. }
  4103. Js::OpCode
  4104. ByteCodeGenerator::GetStSlotOp(Scope *scope, int envIndex, Js::RegSlot scopeLocation, bool chkBlockVar, FuncInfo *funcInfo)
  4105. {
  4106. Js::OpCode op;
  4107. if (envIndex != -1)
  4108. {
  4109. if (scope->GetIsObject())
  4110. {
  4111. op = Js::OpCode::StEnvObjSlot;
  4112. }
  4113. else
  4114. {
  4115. op = Js::OpCode::StEnvSlot;
  4116. }
  4117. }
  4118. else if (scopeLocation != Js::Constants::NoRegister &&
  4119. scopeLocation == funcInfo->frameSlotsRegister)
  4120. {
  4121. op = Js::OpCode::StLocalSlot;
  4122. }
  4123. else if (scopeLocation != Js::Constants::NoRegister &&
  4124. scopeLocation == funcInfo->frameObjRegister)
  4125. {
  4126. op = Js::OpCode::StLocalObjSlot;
  4127. }
  4128. else
  4129. {
  4130. Assert(scope->HasInnerScopeIndex());
  4131. if (scope->GetIsObject())
  4132. {
  4133. op = Js::OpCode::StInnerObjSlot;
  4134. }
  4135. else
  4136. {
  4137. op = Js::OpCode::StInnerSlot;
  4138. }
  4139. }
  4140. if (chkBlockVar)
  4141. {
  4142. op = this->ToChkUndeclOp(op);
  4143. }
  4144. return op;
  4145. }
  4146. Js::OpCode
  4147. ByteCodeGenerator::GetInitFldOp(Scope *scope, Js::RegSlot scopeLocation, FuncInfo *funcInfo, bool letDecl)
  4148. {
  4149. Js::OpCode op;
  4150. if (scopeLocation != Js::Constants::NoRegister &&
  4151. scopeLocation == funcInfo->frameObjRegister)
  4152. {
  4153. op = letDecl ? Js::OpCode::InitLocalLetFld : Js::OpCode::InitLocalFld;
  4154. }
  4155. else if (scope->HasInnerScopeIndex())
  4156. {
  4157. op = letDecl ? Js::OpCode::InitInnerLetFld : Js::OpCode::InitInnerFld;
  4158. }
  4159. else
  4160. {
  4161. op = letDecl ? Js::OpCode::InitLetFld : Js::OpCode::InitFld;
  4162. }
  4163. return op;
  4164. }
  4165. void ByteCodeGenerator::EmitPropStore(Js::RegSlot rhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool isLetDecl, bool isConstDecl, bool isFncDeclVar)
  4166. {
  4167. Js::ByteCodeLabel doneLabel = 0;
  4168. bool fLabelDefined = false;
  4169. Js::PropertyId envIndex = -1;
  4170. Scope *symScope = sym == nullptr || sym->GetIsGlobal() ? this->globalScope : sym->GetScope();
  4171. Assert(symScope);
  4172. // isFncDeclVar denotes that the symbol being stored to here is the var
  4173. // binding of a function declaration and we know we want to store directly
  4174. // to it, skipping over any dynamic scopes that may lie in between.
  4175. Scope *scope = nullptr;
  4176. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4177. bool scopeAcquired = false;
  4178. Js::OpCode op;
  4179. if (sym && sym->GetIsModuleExportStorage())
  4180. {
  4181. if (!isConstDecl && sym->GetDecl() && sym->GetDecl()->nop == knopConstDecl)
  4182. {
  4183. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4184. }
  4185. EmitModuleExportAccess(sym, Js::OpCode::StModuleSlot, rhsLocation, funcInfo);
  4186. return;
  4187. }
  4188. if (isFncDeclVar)
  4189. {
  4190. // async functions allow for the fncDeclVar to be in the body or parameter scope
  4191. // of the parent function, so we need to calculate envIndex in lieu of the while
  4192. // loop below.
  4193. do
  4194. {
  4195. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4196. } while (scope != symScope);
  4197. Assert(scope == symScope);
  4198. scopeLocation = scope->GetLocation();
  4199. }
  4200. while (!isFncDeclVar)
  4201. {
  4202. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4203. if (scope == this->globalScope)
  4204. {
  4205. break;
  4206. }
  4207. if (envIndex == -1)
  4208. {
  4209. Assert(funcInfo == scope->GetFunc());
  4210. scopeLocation = scope->GetLocation();
  4211. }
  4212. if (scope == symScope)
  4213. {
  4214. break;
  4215. }
  4216. // Found a scope to which the property may have been added.
  4217. Assert(scope && scope->GetIsDynamic());
  4218. if (!fLabelDefined)
  4219. {
  4220. fLabelDefined = true;
  4221. doneLabel = this->m_writer.DefineLabel();
  4222. }
  4223. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4224. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4225. Js::RegSlot unwrappedScopeLocation = scopeLocation;
  4226. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4227. if (envIndex != -1)
  4228. {
  4229. this->m_writer.BrEnvProperty(
  4230. Js::OpCode::BrOnNoEnvProperty,
  4231. nextLabel,
  4232. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4233. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  4234. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4235. this->m_writer.SlotI1(
  4236. Js::OpCode::LdEnvObj,
  4237. instLocation,
  4238. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  4239. if (unwrapWithObj)
  4240. {
  4241. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4242. }
  4243. this->m_writer.PatchableProperty(
  4244. Js::OpCode::StFld,
  4245. rhsLocation,
  4246. instLocation,
  4247. funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, true));
  4248. funcInfo->ReleaseTmpRegister(instLocation);
  4249. }
  4250. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4251. {
  4252. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4253. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4254. Assert(!unwrapWithObj);
  4255. this->m_writer.ElementP(Js::OpCode::StLocalFld, rhsLocation,
  4256. funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true));
  4257. }
  4258. else
  4259. {
  4260. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4261. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4262. if (unwrapWithObj)
  4263. {
  4264. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4265. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4266. scopeLocation = unwrappedScopeLocation;
  4267. }
  4268. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  4269. this->m_writer.PatchableProperty(Js::OpCode::StFld, rhsLocation, scopeLocation, cacheId);
  4270. if (unwrapWithObj)
  4271. {
  4272. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4273. }
  4274. }
  4275. this->m_writer.Br(doneLabel);
  4276. this->m_writer.MarkLabel(nextLabel);
  4277. }
  4278. // Arrived at the scope in which the property was defined.
  4279. if (sym == nullptr || sym->GetIsGlobal())
  4280. {
  4281. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4282. if (this->flags & fscrEval)
  4283. {
  4284. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4285. {
  4286. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->frameDisplayRegister, propertyId, false, true);
  4287. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo), rhsLocation, cacheId);
  4288. }
  4289. else
  4290. {
  4291. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, true);
  4292. bool isConsoleScopeLetConst = this->IsConsoleScopeEval() && (isLetDecl || isConstDecl);
  4293. // In "eval", store to a symbol with unknown scope goes through the closure environment.
  4294. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo, isConsoleScopeLetConst), rhsLocation, cacheId);
  4295. }
  4296. }
  4297. else if (this->flags & (fscrImplicitThis | fscrImplicitParents))
  4298. {
  4299. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, true);
  4300. // In "eval", store to a symbol with unknown scope goes through the closure environment.
  4301. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo), rhsLocation, cacheId);
  4302. }
  4303. else
  4304. {
  4305. this->EmitPatchableRootProperty(GetStFldOpCode(funcInfo, true, isLetDecl, isConstDecl, false), rhsLocation, propertyId, false, true, funcInfo);
  4306. }
  4307. }
  4308. else if (sym->GetFuncExpr())
  4309. {
  4310. // Store to function expr variable.
  4311. // strict mode: we need to throw type error
  4312. if (funcInfo->byteCodeFunction->GetIsStrictMode())
  4313. {
  4314. // Note that in this case the sym's location belongs to the parent function, so we can't use it.
  4315. // It doesn't matter which register we use, as long as it's valid for this function.
  4316. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_CantAssignToReadOnly));
  4317. }
  4318. }
  4319. else if (sym->IsInSlot(funcInfo) || envIndex != -1)
  4320. {
  4321. if (!isConstDecl && sym->GetDecl() && sym->GetDecl()->nop == knopConstDecl)
  4322. {
  4323. // This is a case where const reassignment can't be proven statically (e.g., eval, with) so
  4324. // we have to catch it at runtime.
  4325. this->m_writer.W1(
  4326. Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4327. }
  4328. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4329. Js::PropertyId slot = sym->EnsureScopeSlot(funcInfo);
  4330. bool chkBlockVar = !isLetDecl && !isConstDecl && NeedCheckBlockVar(sym, scope, funcInfo);
  4331. // The property is in memory rather than register. We'll have to load it from the slots.
  4332. op = this->GetStSlotOp(scope, envIndex, scopeLocation, chkBlockVar, funcInfo);
  4333. if (envIndex != -1)
  4334. {
  4335. this->m_writer.SlotI2(op, rhsLocation,
  4336. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var),
  4337. slot + (sym->GetScope()->GetIsObject()? 0 : Js::ScopeSlots::FirstSlotIndex));
  4338. }
  4339. else if (scopeLocation != Js::Constants::NoRegister &&
  4340. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4341. {
  4342. this->m_writer.SlotI1(op, rhsLocation,
  4343. slot + (sym->GetScope()->GetIsObject()? 0 : Js::ScopeSlots::FirstSlotIndex));
  4344. }
  4345. else
  4346. {
  4347. Assert(scope->HasInnerScopeIndex());
  4348. this->m_writer.SlotI2(op, rhsLocation, scope->GetInnerScopeIndex(),
  4349. slot + (sym->GetScope()->GetIsObject()? 0 : Js::ScopeSlots::FirstSlotIndex));
  4350. }
  4351. if (this->ShouldTrackDebuggerMetadata() && (isLetDecl || isConstDecl))
  4352. {
  4353. Js::PropertyId location = scope->GetIsObject() ? sym->GetLocation() : slot;
  4354. this->UpdateDebuggerPropertyInitializationOffset(location, sym->GetPosition(), false);
  4355. }
  4356. }
  4357. else if (isConstDecl)
  4358. {
  4359. this->m_writer.Reg2(Js::OpCode::InitConst, sym->GetLocation(), rhsLocation);
  4360. if (this->ShouldTrackDebuggerMetadata())
  4361. {
  4362. this->UpdateDebuggerPropertyInitializationOffset(sym->GetLocation(), sym->GetPosition());
  4363. }
  4364. }
  4365. else
  4366. {
  4367. if (!isConstDecl && sym->GetDecl() && sym->GetDecl()->nop == knopConstDecl)
  4368. {
  4369. // This is a case where const reassignment can't be proven statically (e.g., eval, with) so
  4370. // we have to catch it at runtime.
  4371. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4372. }
  4373. if (rhsLocation != sym->GetLocation())
  4374. {
  4375. this->m_writer.Reg2(Js::OpCode::Ld_A, sym->GetLocation(), rhsLocation);
  4376. if (this->ShouldTrackDebuggerMetadata() && isLetDecl)
  4377. {
  4378. this->UpdateDebuggerPropertyInitializationOffset(sym->GetLocation(), sym->GetPosition());
  4379. }
  4380. }
  4381. }
  4382. if (fLabelDefined)
  4383. {
  4384. this->m_writer.MarkLabel(doneLabel);
  4385. }
  4386. if (scopeAcquired)
  4387. {
  4388. funcInfo->ReleaseTmpRegister(scopeLocation);
  4389. }
  4390. }
  4391. Js::OpCode
  4392. ByteCodeGenerator::GetLdSlotOp(Scope *scope, int envIndex, Js::RegSlot scopeLocation, FuncInfo *funcInfo)
  4393. {
  4394. Js::OpCode op;
  4395. if (envIndex != -1)
  4396. {
  4397. if (scope->GetIsObject())
  4398. {
  4399. op = Js::OpCode::LdEnvObjSlot;
  4400. }
  4401. else
  4402. {
  4403. op = Js::OpCode::LdEnvSlot;
  4404. }
  4405. }
  4406. else if (scopeLocation != Js::Constants::NoRegister &&
  4407. scopeLocation == funcInfo->frameSlotsRegister)
  4408. {
  4409. op = Js::OpCode::LdLocalSlot;
  4410. }
  4411. else if (scopeLocation != Js::Constants::NoRegister &&
  4412. scopeLocation == funcInfo->frameObjRegister)
  4413. {
  4414. op = Js::OpCode::LdLocalObjSlot;
  4415. }
  4416. else if (scope->HasInnerScopeIndex())
  4417. {
  4418. if (scope->GetIsObject())
  4419. {
  4420. op = Js::OpCode::LdInnerObjSlot;
  4421. }
  4422. else
  4423. {
  4424. op = Js::OpCode::LdInnerSlot;
  4425. }
  4426. }
  4427. else
  4428. {
  4429. Assert(scope->GetIsObject());
  4430. op = Js::OpCode::LdObjSlot;
  4431. }
  4432. return op;
  4433. }
  4434. void ByteCodeGenerator::EmitPropLoad(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo)
  4435. {
  4436. // If sym belongs to a parent frame, get it from the closure environment.
  4437. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4438. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4439. // Otherwise, just copy the value to the lhsLocation.
  4440. Js::ByteCodeLabel doneLabel = 0;
  4441. bool fLabelDefined = false;
  4442. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4443. Js::PropertyId envIndex = -1;
  4444. Scope *scope = nullptr;
  4445. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4446. Assert(symScope);
  4447. if (sym && sym->GetIsModuleExportStorage())
  4448. {
  4449. EmitModuleExportAccess(sym, Js::OpCode::LdModuleSlot, lhsLocation, funcInfo);
  4450. return;
  4451. }
  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. if (!fLabelDefined)
  4467. {
  4468. fLabelDefined = true;
  4469. doneLabel = this->m_writer.DefineLabel();
  4470. }
  4471. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4472. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4473. Js::RegSlot unwrappedScopeLocation = Js::Constants::NoRegister;
  4474. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4475. if (envIndex != -1)
  4476. {
  4477. this->m_writer.BrEnvProperty(
  4478. Js::OpCode::BrOnNoEnvProperty,
  4479. nextLabel,
  4480. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4481. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  4482. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4483. this->m_writer.SlotI1(
  4484. Js::OpCode::LdEnvObj,
  4485. instLocation,
  4486. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  4487. if (unwrapWithObj)
  4488. {
  4489. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4490. }
  4491. this->m_writer.PatchableProperty(
  4492. Js::OpCode::LdFld,
  4493. lhsLocation,
  4494. instLocation,
  4495. funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, false));
  4496. funcInfo->ReleaseTmpRegister(instLocation);
  4497. }
  4498. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4499. {
  4500. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4501. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4502. Assert(!unwrapWithObj);
  4503. this->m_writer.ElementP(Js::OpCode::LdLocalFld, lhsLocation,
  4504. funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, false));
  4505. }
  4506. else
  4507. {
  4508. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4509. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4510. if (unwrapWithObj)
  4511. {
  4512. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4513. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4514. scopeLocation = unwrappedScopeLocation;
  4515. }
  4516. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, false);
  4517. this->m_writer.PatchableProperty(Js::OpCode::LdFld, lhsLocation, scopeLocation, cacheId);
  4518. if (unwrapWithObj)
  4519. {
  4520. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4521. }
  4522. }
  4523. this->m_writer.Br(doneLabel);
  4524. this->m_writer.MarkLabel(nextLabel);
  4525. }
  4526. // Arrived at the scope in which the property was defined.
  4527. if (sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo)
  4528. {
  4529. // Ensure this symbol has a slot if it needs one.
  4530. if (sym->IsInSlot(funcInfo))
  4531. {
  4532. Js::PropertyId slot = sym->EnsureScopeSlot(funcInfo);
  4533. funcInfo->FindOrAddSlotProfileId(scope, slot);
  4534. }
  4535. EmitUseBeforeDeclarationRuntimeError(this, lhsLocation);
  4536. }
  4537. else if (sym == nullptr || sym->GetIsGlobal())
  4538. {
  4539. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4540. if (this->flags & fscrEval)
  4541. {
  4542. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4543. {
  4544. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->frameDisplayRegister, propertyId, false, false);
  4545. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4546. }
  4547. else
  4548. {
  4549. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, false);
  4550. // Load of a symbol with unknown scope from within eval
  4551. // Get it from the closure environment.
  4552. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4553. }
  4554. }
  4555. else if (this->flags & (fscrImplicitThis | fscrImplicitParents))
  4556. {
  4557. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, false);
  4558. // Load of a symbol with unknown scope from within eval or event handler.
  4559. // Get it from the closure environment.
  4560. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4561. }
  4562. else
  4563. {
  4564. // Special case non-writable built-ins
  4565. // TODO: support non-writable global property in general by detecting what attribute the property have current?
  4566. // But can't be done if we are byte code serialized, because the attribute might be different for use fields
  4567. // next time we run. May want to catch that in the JIT.
  4568. Js::OpCode opcode = Js::OpCode::LdRootFld;
  4569. // These properties are non-writable
  4570. switch (propertyId)
  4571. {
  4572. case Js::PropertyIds::NaN:
  4573. opcode = Js::OpCode::LdNaN;
  4574. break;
  4575. case Js::PropertyIds::Infinity:
  4576. opcode = Js::OpCode::LdInfinity;
  4577. break;
  4578. case Js::PropertyIds::undefined:
  4579. opcode = Js::OpCode::LdUndef;
  4580. break;
  4581. }
  4582. if (opcode == Js::OpCode::LdRootFld)
  4583. {
  4584. this->EmitPatchableRootProperty(Js::OpCode::LdRootFld, lhsLocation, propertyId, false, false, funcInfo);
  4585. }
  4586. else
  4587. {
  4588. this->Writer()->Reg1(opcode, lhsLocation);
  4589. }
  4590. }
  4591. }
  4592. else if (sym->IsInSlot(funcInfo) || envIndex != -1)
  4593. {
  4594. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4595. Js::PropertyId slot = sym->EnsureScopeSlot(funcInfo);
  4596. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(scope, slot);
  4597. bool chkBlockVar = NeedCheckBlockVar(sym, scope, funcInfo);
  4598. Js::OpCode op;
  4599. // Now get the property from its slot.
  4600. op = this->GetLdSlotOp(scope, envIndex, scopeLocation, funcInfo);
  4601. slot = slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  4602. if (envIndex != -1)
  4603. {
  4604. this->m_writer.SlotI2(op, lhsLocation, envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var), slot, profileId);
  4605. }
  4606. else if (scopeLocation != Js::Constants::NoRegister &&
  4607. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4608. {
  4609. this->m_writer.SlotI1(op, lhsLocation, slot, profileId);
  4610. }
  4611. else if (scope->HasInnerScopeIndex())
  4612. {
  4613. this->m_writer.SlotI2(op, lhsLocation, scope->GetInnerScopeIndex(), slot, profileId);
  4614. }
  4615. else
  4616. {
  4617. Assert(scope->GetIsObject());
  4618. this->m_writer.Slot(op, lhsLocation, scopeLocation, slot, profileId);
  4619. }
  4620. if (chkBlockVar)
  4621. {
  4622. this->m_writer.Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4623. }
  4624. }
  4625. else
  4626. {
  4627. if (lhsLocation != sym->GetLocation())
  4628. {
  4629. this->m_writer.Reg2(Js::OpCode::Ld_A, lhsLocation, sym->GetLocation());
  4630. }
  4631. if (sym->GetIsBlockVar() && ((sym->GetDecl()->nop == knopLetDecl || sym->GetDecl()->nop == knopConstDecl) && sym->GetDecl()->sxVar.isSwitchStmtDecl))
  4632. {
  4633. this->m_writer.Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4634. }
  4635. }
  4636. if (fLabelDefined)
  4637. {
  4638. this->m_writer.MarkLabel(doneLabel);
  4639. }
  4640. }
  4641. bool ByteCodeGenerator::NeedCheckBlockVar(Symbol* sym, Scope* scope, FuncInfo* funcInfo) const
  4642. {
  4643. bool tdz = sym->GetIsBlockVar()
  4644. && (scope->GetFunc() != funcInfo || ((sym->GetDecl()->nop == knopLetDecl || sym->GetDecl()->nop == knopConstDecl) && sym->GetDecl()->sxVar.isSwitchStmtDecl));
  4645. return tdz || sym->GetIsNonSimpleParameter();
  4646. }
  4647. void ByteCodeGenerator::EmitPropDelete(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo)
  4648. {
  4649. // If sym belongs to a parent frame, delete it from the closure environment.
  4650. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4651. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4652. // Otherwise, just return false.
  4653. Js::ByteCodeLabel doneLabel = 0;
  4654. bool fLabelDefined = false;
  4655. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4656. Js::PropertyId envIndex = -1;
  4657. Scope *scope = nullptr;
  4658. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4659. Assert(symScope);
  4660. for (;;)
  4661. {
  4662. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4663. if (scope == this->globalScope)
  4664. {
  4665. scopeLocation = ByteCodeGenerator::RootObjectRegister;
  4666. }
  4667. else if (envIndex == -1)
  4668. {
  4669. Assert(funcInfo == scope->GetFunc());
  4670. scopeLocation = scope->GetLocation();
  4671. }
  4672. if (scope == symScope)
  4673. {
  4674. break;
  4675. }
  4676. // Found a scope to which the property may have been added.
  4677. Assert(scope && scope->GetIsDynamic());
  4678. if (!fLabelDefined)
  4679. {
  4680. fLabelDefined = true;
  4681. doneLabel = this->m_writer.DefineLabel();
  4682. }
  4683. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4684. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4685. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4686. if (envIndex != -1)
  4687. {
  4688. this->m_writer.BrEnvProperty(
  4689. Js::OpCode::BrOnNoEnvProperty,
  4690. nextLabel,
  4691. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4692. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  4693. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4694. this->m_writer.SlotI1(
  4695. Js::OpCode::LdEnvObj,
  4696. instLocation,
  4697. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  4698. if (unwrapWithObj)
  4699. {
  4700. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4701. }
  4702. this->m_writer.Property(Js::OpCode::DeleteFld, lhsLocation, instLocation,
  4703. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4704. funcInfo->ReleaseTmpRegister(instLocation);
  4705. }
  4706. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4707. {
  4708. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4709. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4710. Assert(!unwrapWithObj);
  4711. this->m_writer.ElementU(Js::OpCode::DeleteLocalFld, lhsLocation,
  4712. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4713. }
  4714. else
  4715. {
  4716. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4717. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4718. Js::RegSlot unwrappedScopeLocation = Js::Constants::NoRegister;
  4719. if (unwrapWithObj)
  4720. {
  4721. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4722. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4723. scopeLocation = unwrappedScopeLocation;
  4724. }
  4725. this->m_writer.Property(Js::OpCode::DeleteFld, lhsLocation, scopeLocation,
  4726. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4727. if (unwrapWithObj)
  4728. {
  4729. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4730. }
  4731. }
  4732. this->m_writer.Br(doneLabel);
  4733. this->m_writer.MarkLabel(nextLabel);
  4734. }
  4735. // Arrived at the scope in which the property was defined.
  4736. if (sym == nullptr || sym->GetIsGlobal())
  4737. {
  4738. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4739. if (this->flags & (fscrEval | fscrImplicitThis | fscrImplicitParents))
  4740. {
  4741. this->m_writer.ScopedProperty(Js::OpCode::ScopedDeleteFld, lhsLocation,
  4742. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4743. }
  4744. else
  4745. {
  4746. this->m_writer.Property(Js::OpCode::DeleteRootFld, lhsLocation, ByteCodeGenerator::RootObjectRegister,
  4747. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4748. }
  4749. }
  4750. else
  4751. {
  4752. // The delete will look like a non-local reference, so make sure a slot is reserved.
  4753. sym->EnsureScopeSlot(funcInfo);
  4754. this->m_writer.Reg1(Js::OpCode::LdFalse, lhsLocation);
  4755. }
  4756. if (fLabelDefined)
  4757. {
  4758. this->m_writer.MarkLabel(doneLabel);
  4759. }
  4760. }
  4761. void ByteCodeGenerator::EmitTypeOfFld(FuncInfo * funcInfo, Js::PropertyId propertyId, Js::RegSlot value, Js::RegSlot instance, Js::OpCode ldFldOp)
  4762. {
  4763. uint cacheId;
  4764. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  4765. switch (ldFldOp)
  4766. {
  4767. case Js::OpCode::LdRootFldForTypeOf:
  4768. cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, false, false);
  4769. this->Writer()->PatchableRootProperty(ldFldOp, tmpReg, cacheId, false, false);
  4770. break;
  4771. case Js::OpCode::LdLocalFld:
  4772. case Js::OpCode::ScopedLdFldForTypeOf:
  4773. cacheId = funcInfo->FindOrAddInlineCacheId(instance, propertyId, false, false);
  4774. this->Writer()->ElementP(ldFldOp, tmpReg, cacheId);
  4775. break;
  4776. default:
  4777. cacheId = funcInfo->FindOrAddInlineCacheId(instance, propertyId, false, false);
  4778. this->Writer()->PatchableProperty(ldFldOp, tmpReg, instance, cacheId);
  4779. break;
  4780. }
  4781. this->Writer()->Reg2(Js::OpCode::Typeof, value, tmpReg);
  4782. funcInfo->ReleaseTmpRegister(tmpReg);
  4783. }
  4784. void ByteCodeGenerator::EmitPropTypeof(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo)
  4785. {
  4786. // If sym belongs to a parent frame, delete it from the closure environment.
  4787. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4788. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4789. // Otherwise, just return false
  4790. Js::ByteCodeLabel doneLabel = 0;
  4791. bool fLabelDefined = false;
  4792. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4793. Js::PropertyId envIndex = -1;
  4794. Scope *scope = nullptr;
  4795. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4796. Assert(symScope);
  4797. if (sym && sym->GetIsModuleExportStorage())
  4798. {
  4799. Js::RegSlot tmpLocation = funcInfo->AcquireTmpRegister();
  4800. EmitModuleExportAccess(sym, Js::OpCode::LdModuleSlot, tmpLocation, funcInfo);
  4801. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, tmpLocation);
  4802. funcInfo->ReleaseTmpRegister(tmpLocation);
  4803. return;
  4804. }
  4805. for (;;)
  4806. {
  4807. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4808. if (scope == this->globalScope)
  4809. {
  4810. scopeLocation = ByteCodeGenerator::RootObjectRegister;
  4811. }
  4812. else if (envIndex == -1)
  4813. {
  4814. Assert(funcInfo == scope->GetFunc());
  4815. scopeLocation = scope->GetLocation();
  4816. }
  4817. if (scope == symScope)
  4818. {
  4819. break;
  4820. }
  4821. // Found a scope to which the property may have been added.
  4822. Assert(scope && scope->GetIsDynamic());
  4823. if (!fLabelDefined)
  4824. {
  4825. fLabelDefined = true;
  4826. doneLabel = this->m_writer.DefineLabel();
  4827. }
  4828. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4829. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4830. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4831. if (envIndex != -1)
  4832. {
  4833. this->m_writer.BrEnvProperty(Js::OpCode::BrOnNoEnvProperty, nextLabel,
  4834. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4835. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  4836. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4837. this->m_writer.SlotI1(Js::OpCode::LdEnvObj,
  4838. instLocation,
  4839. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  4840. if (unwrapWithObj)
  4841. {
  4842. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4843. }
  4844. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, instLocation, Js::OpCode::LdFldForTypeOf);
  4845. funcInfo->ReleaseTmpRegister(instLocation);
  4846. }
  4847. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4848. {
  4849. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4850. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4851. Assert(!unwrapWithObj);
  4852. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, scopeLocation, Js::OpCode::LdLocalFld);
  4853. }
  4854. else
  4855. {
  4856. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4857. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4858. Js::RegSlot unwrappedScopeLocation = Js::Constants::NoRegister;
  4859. if (unwrapWithObj)
  4860. {
  4861. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4862. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4863. scopeLocation = unwrappedScopeLocation;
  4864. }
  4865. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, scopeLocation, Js::OpCode::LdFldForTypeOf);
  4866. if (unwrapWithObj)
  4867. {
  4868. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4869. }
  4870. }
  4871. this->m_writer.Br(doneLabel);
  4872. this->m_writer.MarkLabel(nextLabel);
  4873. }
  4874. // Arrived at the scope in which the property was defined.
  4875. if (sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo)
  4876. {
  4877. // Ensure this symbol has a slot if it needs one.
  4878. if (sym->IsInSlot(funcInfo))
  4879. {
  4880. Js::PropertyId slot = sym->EnsureScopeSlot(funcInfo);
  4881. funcInfo->FindOrAddSlotProfileId(scope, slot);
  4882. }
  4883. EmitUseBeforeDeclarationRuntimeError(this, lhsLocation);
  4884. }
  4885. else if (sym == nullptr || sym->GetIsGlobal())
  4886. {
  4887. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4888. if (this->flags & fscrEval)
  4889. {
  4890. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4891. {
  4892. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->frameDisplayRegister, Js::OpCode::ScopedLdFldForTypeOf);
  4893. }
  4894. else
  4895. {
  4896. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->GetEnvRegister(), Js::OpCode::ScopedLdFldForTypeOf);
  4897. }
  4898. }
  4899. else if (this->flags & (fscrImplicitThis | fscrImplicitParents))
  4900. {
  4901. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->GetEnvRegister(), Js::OpCode::ScopedLdFldForTypeOf);
  4902. }
  4903. else
  4904. {
  4905. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, ByteCodeGenerator::RootObjectRegister, Js::OpCode::LdRootFldForTypeOf);
  4906. }
  4907. }
  4908. else if (sym->IsInSlot(funcInfo) || envIndex != -1)
  4909. {
  4910. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4911. Js::PropertyId slot = sym->EnsureScopeSlot(funcInfo);
  4912. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(scope, slot);
  4913. Js::RegSlot tmpLocation = funcInfo->AcquireTmpRegister();
  4914. bool chkBlockVar = NeedCheckBlockVar(sym, scope, funcInfo);
  4915. Js::OpCode op;
  4916. op = this->GetLdSlotOp(scope, envIndex, scopeLocation, funcInfo);
  4917. slot = slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  4918. if (envIndex != -1)
  4919. {
  4920. this->m_writer.SlotI2(op, tmpLocation, envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var), slot, profileId);
  4921. }
  4922. else if (scopeLocation != Js::Constants::NoRegister &&
  4923. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4924. {
  4925. this->m_writer.SlotI1(op, tmpLocation, slot, profileId);
  4926. }
  4927. else if (scope->HasInnerScopeIndex())
  4928. {
  4929. this->m_writer.SlotI2(op, tmpLocation, scope->GetInnerScopeIndex(), slot, profileId);
  4930. }
  4931. else
  4932. {
  4933. Assert(scope->GetIsObject());
  4934. this->m_writer.Slot(op, tmpLocation, scopeLocation, slot, profileId);
  4935. }
  4936. if (chkBlockVar)
  4937. {
  4938. this->m_writer.Reg1(Js::OpCode::ChkUndecl, tmpLocation);
  4939. }
  4940. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, tmpLocation);
  4941. funcInfo->ReleaseTmpRegister(tmpLocation);
  4942. }
  4943. else
  4944. {
  4945. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, sym->GetLocation());
  4946. }
  4947. if (fLabelDefined)
  4948. {
  4949. this->m_writer.MarkLabel(doneLabel);
  4950. }
  4951. }
  4952. void ByteCodeGenerator::EnsureNoRedeclarations(ParseNode *pnodeBlock, FuncInfo *funcInfo)
  4953. {
  4954. // Emit dynamic runtime checks for variable re-declarations. Only necessary for global functions (script or eval).
  4955. // In eval only var declarations can cause redeclaration, and only in non-strict mode, because let/const variables
  4956. // remain local to the eval code.
  4957. Assert(pnodeBlock->nop == knopBlock);
  4958. Assert(pnodeBlock->sxBlock.blockType == PnodeBlockType::Global || pnodeBlock->sxBlock.scope->GetScopeType() == ScopeType_GlobalEvalBlock);
  4959. if (!(this->flags & fscrEvalCode))
  4960. {
  4961. IterateBlockScopedVariables(pnodeBlock, [this](ParseNode *pnode)
  4962. {
  4963. FuncInfo *funcInfo = this->TopFuncInfo();
  4964. Symbol *sym = pnode->sxVar.sym;
  4965. Assert(sym->GetIsGlobal());
  4966. Js::PropertyId propertyId = sym->EnsurePosition(this);
  4967. this->m_writer.ElementRootU(Js::OpCode::EnsureNoRootFld, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4968. });
  4969. }
  4970. for (ParseNode *pnode = funcInfo->root->sxFnc.pnodeVars; pnode; pnode = pnode->sxVar.pnodeNext)
  4971. {
  4972. Symbol* sym = pnode->sxVar.sym;
  4973. if (sym == nullptr || pnode->sxVar.isBlockScopeFncDeclVar)
  4974. continue;
  4975. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  4976. {
  4977. // The init node was bound to the catch object, because it's inside a catch and has the
  4978. // same name as the catch object. But we want to define a user var at function scope,
  4979. // so find the right symbol. (We'll still assign the RHS value to the catch object symbol.)
  4980. // This also applies to a var declaration in the same scope as a let declaration.
  4981. // Assert that catch cannot be at function scope and let and var at function scope is redeclaration error.
  4982. Assert(sym->GetIsCatch() || funcInfo->bodyScope != sym->GetScope());
  4983. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  4984. Assert(sym && !sym->GetIsCatch() && !sym->GetIsBlockVar());
  4985. }
  4986. Assert(sym->GetIsGlobal());
  4987. if (sym->GetSymbolType() == STVariable)
  4988. {
  4989. Js::PropertyId propertyId = sym->EnsurePosition(this);
  4990. if (this->flags & fscrEval)
  4991. {
  4992. if (!funcInfo->byteCodeFunction->GetIsStrictMode())
  4993. {
  4994. this->m_writer.ScopedProperty(Js::OpCode::ScopedEnsureNoRedeclFld, ByteCodeGenerator::RootObjectRegister,
  4995. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4996. }
  4997. }
  4998. else
  4999. {
  5000. this->m_writer.ElementRootU(Js::OpCode::EnsureNoRootRedeclFld, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  5001. }
  5002. }
  5003. }
  5004. }
  5005. void ByteCodeGenerator::RecordAllIntConstants(FuncInfo * funcInfo)
  5006. {
  5007. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5008. funcInfo->constantToRegister.Map([byteCodeFunction](unsigned int val, Js::RegSlot location)
  5009. {
  5010. byteCodeFunction->RecordIntConstant(byteCodeFunction->MapRegSlot(location), val);
  5011. });
  5012. }
  5013. void ByteCodeGenerator::RecordAllStrConstants(FuncInfo * funcInfo)
  5014. {
  5015. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5016. funcInfo->stringToRegister.Map([byteCodeFunction](IdentPtr pid, Js::RegSlot location)
  5017. {
  5018. byteCodeFunction->RecordStrConstant(byteCodeFunction->MapRegSlot(location), pid->Psz(), pid->Cch());
  5019. });
  5020. }
  5021. void ByteCodeGenerator::RecordAllStringTemplateCallsiteConstants(FuncInfo* funcInfo)
  5022. {
  5023. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5024. funcInfo->stringTemplateCallsiteRegisterMap.Map([byteCodeFunction](ParseNodePtr pnode, Js::RegSlot location)
  5025. {
  5026. Js::ScriptContext* scriptContext = byteCodeFunction->GetScriptContext();
  5027. Js::JavascriptLibrary* library = scriptContext->GetLibrary();
  5028. Js::RecyclableObject* callsiteObject = library->TryGetStringTemplateCallsiteObject(pnode);
  5029. if (callsiteObject == nullptr)
  5030. {
  5031. Js::RecyclableObject* rawArray = ByteCodeGenerator::BuildArrayFromStringList(pnode->sxStrTemplate.pnodeStringRawLiterals, pnode->sxStrTemplate.countStringLiterals, scriptContext);
  5032. rawArray->Freeze();
  5033. callsiteObject = ByteCodeGenerator::BuildArrayFromStringList(pnode->sxStrTemplate.pnodeStringLiterals, pnode->sxStrTemplate.countStringLiterals, scriptContext);
  5034. callsiteObject->SetPropertyWithAttributes(Js::PropertyIds::raw, rawArray, PropertyNone, nullptr);
  5035. callsiteObject->Freeze();
  5036. library->AddStringTemplateCallsiteObject(callsiteObject);
  5037. }
  5038. byteCodeFunction->RecordConstant(byteCodeFunction->MapRegSlot(location), callsiteObject);
  5039. });
  5040. }
  5041. bool IsApplyArgs(ParseNode* callNode)
  5042. {
  5043. ParseNode* target = callNode->sxCall.pnodeTarget;
  5044. ParseNode* args = callNode->sxCall.pnodeArgs;
  5045. if ((target != nullptr) && (target->nop == knopDot))
  5046. {
  5047. ParseNode* lhsNode = target->sxBin.pnode1;
  5048. if ((lhsNode != nullptr) && ((lhsNode->nop == knopDot) || (lhsNode->nop == knopName)) && !IsArguments(lhsNode))
  5049. {
  5050. ParseNode* nameNode = target->sxBin.pnode2;
  5051. if (nameNode != nullptr)
  5052. {
  5053. bool nameIsApply = nameNode->sxPid.PropertyIdFromNameNode() == Js::PropertyIds::apply;
  5054. if (nameIsApply && args != nullptr && args->nop == knopList)
  5055. {
  5056. ParseNode* arg1 = args->sxBin.pnode1;
  5057. ParseNode* arg2 = args->sxBin.pnode2;
  5058. if ((arg1 != nullptr) && (arg1->nop == knopThis) && (arg2 != nullptr) && (arg2->nop == knopName) && (arg2->sxPid.sym != nullptr))
  5059. {
  5060. return arg2->sxPid.sym->GetIsArguments();
  5061. }
  5062. }
  5063. }
  5064. }
  5065. }
  5066. return false;
  5067. }
  5068. void PostCheckApplyEnclosesArgs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, ApplyCheck* applyCheck)
  5069. {
  5070. if ((pnode == nullptr) || (!applyCheck->matches))
  5071. {
  5072. return;
  5073. }
  5074. if (pnode->nop == knopCall)
  5075. {
  5076. if ((!pnode->isUsed) && IsApplyArgs(pnode))
  5077. {
  5078. if (!applyCheck->insideApplyCall)
  5079. {
  5080. applyCheck->matches = false;
  5081. }
  5082. applyCheck->insideApplyCall = false;
  5083. }
  5084. }
  5085. }
  5086. void CheckApplyEnclosesArgs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, ApplyCheck* applyCheck)
  5087. {
  5088. if ((pnode == nullptr) || (!applyCheck->matches))
  5089. {
  5090. return;
  5091. }
  5092. switch (pnode->nop)
  5093. {
  5094. case knopName:
  5095. {
  5096. Symbol* sym = pnode->sxPid.sym;
  5097. if (sym != nullptr)
  5098. {
  5099. if (sym->GetIsArguments())
  5100. {
  5101. if (!applyCheck->insideApplyCall)
  5102. {
  5103. applyCheck->matches = false;
  5104. }
  5105. }
  5106. }
  5107. break;
  5108. }
  5109. case knopCall:
  5110. if ((!pnode->isUsed) && IsApplyArgs(pnode))
  5111. {
  5112. // no nested apply calls
  5113. if (applyCheck->insideApplyCall)
  5114. {
  5115. applyCheck->matches = false;
  5116. }
  5117. else
  5118. {
  5119. applyCheck->insideApplyCall = true;
  5120. applyCheck->sawApply = true;
  5121. pnode->sxCall.isApplyCall = true;
  5122. }
  5123. }
  5124. break;
  5125. }
  5126. }
  5127. unsigned int CountArguments(ParseNode *pnode, BOOL *pSideEffect = nullptr)
  5128. {
  5129. // If the caller passed us a pSideEffect, it wants to know whether there are potential
  5130. // side-effects in the argument list. We need to know this so that the call target
  5131. // operands can be preserved if necessary.
  5132. // For now, treat any non-leaf op as a potential side-effect. This causes no detectable slowdowns,
  5133. // but we can be more precise if we need to be.
  5134. if (pSideEffect)
  5135. {
  5136. *pSideEffect = FALSE;
  5137. }
  5138. unsigned int argCount = 1;
  5139. if (pnode != nullptr)
  5140. {
  5141. while (pnode->nop == knopList)
  5142. {
  5143. argCount++;
  5144. if (pSideEffect && !(ParseNode::Grfnop(pnode->sxBin.pnode1->nop) & fnopLeaf))
  5145. {
  5146. *pSideEffect = TRUE;
  5147. }
  5148. pnode = pnode->sxBin.pnode2;
  5149. }
  5150. argCount++;
  5151. if (pSideEffect && !(ParseNode::Grfnop(pnode->nop) & fnopLeaf))
  5152. {
  5153. *pSideEffect = TRUE;
  5154. }
  5155. }
  5156. return argCount;
  5157. }
  5158. void SaveOpndValue(ParseNode *pnode, FuncInfo *funcInfo)
  5159. {
  5160. // Save a local name to a register other than its home location.
  5161. // This guards against side-effects in cases like x.foo(x = bar()).
  5162. Symbol *sym = nullptr;
  5163. if (pnode->nop == knopName)
  5164. {
  5165. sym = pnode->sxPid.sym;
  5166. }
  5167. else if (pnode->nop == knopComputedName)
  5168. {
  5169. ParseNode *pnode1 = pnode->sxUni.pnode1;
  5170. if (pnode1->nop == knopName)
  5171. {
  5172. sym = pnode1->sxPid.sym;
  5173. }
  5174. }
  5175. if (sym == nullptr)
  5176. {
  5177. return;
  5178. }
  5179. // If the target is a local being kept in its home location,
  5180. // protect the target's value in the event the home location is overwritten.
  5181. if (pnode->location != Js::Constants::NoRegister &&
  5182. sym->GetScope()->GetFunc() == funcInfo &&
  5183. pnode->location == sym->GetLocation())
  5184. {
  5185. pnode->location = funcInfo->AcquireTmpRegister();
  5186. }
  5187. }
  5188. void ByteCodeGenerator::StartStatement(ParseNode* node)
  5189. {
  5190. Assert(TopFuncInfo() != nullptr);
  5191. m_writer.StartStatement(node, TopFuncInfo()->curTmpReg - TopFuncInfo()->firstTmpReg);
  5192. }
  5193. void ByteCodeGenerator::EndStatement(ParseNode* node)
  5194. {
  5195. m_writer.EndStatement(node);
  5196. }
  5197. void ByteCodeGenerator::StartSubexpression(ParseNode* node)
  5198. {
  5199. Assert(TopFuncInfo() != nullptr);
  5200. m_writer.StartSubexpression(node);
  5201. }
  5202. void ByteCodeGenerator::EndSubexpression(ParseNode* node)
  5203. {
  5204. m_writer.EndSubexpression(node);
  5205. }
  5206. void EmitReference(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  5207. {
  5208. // Generate code for the LHS of an assignment.
  5209. switch (pnode->nop)
  5210. {
  5211. case knopDot:
  5212. Emit(pnode->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  5213. break;
  5214. case knopIndex:
  5215. Emit(pnode->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  5216. Emit(pnode->sxBin.pnode2, byteCodeGenerator, funcInfo, false);
  5217. break;
  5218. case knopName:
  5219. break;
  5220. case knopArrayPattern:
  5221. case knopObjectPattern:
  5222. break;
  5223. case knopCall:
  5224. case knopNew:
  5225. // Emit the operands of a call that will be used as a LHS.
  5226. // These have to be emitted before the RHS, but they have to persist until
  5227. // the end of the expression.
  5228. // Emit the call target operands first.
  5229. switch (pnode->sxCall.pnodeTarget->nop)
  5230. {
  5231. case knopDot:
  5232. case knopIndex:
  5233. funcInfo->AcquireLoc(pnode->sxCall.pnodeTarget);
  5234. EmitReference(pnode->sxCall.pnodeTarget, byteCodeGenerator, funcInfo);
  5235. break;
  5236. case knopName:
  5237. {
  5238. Symbol *sym = pnode->sxCall.pnodeTarget->sxPid.sym;
  5239. if (!sym || sym->GetLocation() == Js::Constants::NoRegister)
  5240. {
  5241. funcInfo->AcquireLoc(pnode->sxCall.pnodeTarget);
  5242. }
  5243. if (sym && (sym->IsInSlot(funcInfo) || sym->GetScope()->GetFunc() != funcInfo))
  5244. {
  5245. // Can't get the value from the assigned register, so load it here.
  5246. EmitLoad(pnode->sxCall.pnodeTarget, byteCodeGenerator, funcInfo);
  5247. }
  5248. else
  5249. {
  5250. EmitReference(pnode->sxCall.pnodeTarget, byteCodeGenerator, funcInfo);
  5251. }
  5252. break;
  5253. }
  5254. default:
  5255. EmitLoad(pnode->sxCall.pnodeTarget, byteCodeGenerator, funcInfo);
  5256. break;
  5257. }
  5258. // Now the arg list. We evaluate everything now and emit the ArgOut's later.
  5259. if (pnode->sxCall.pnodeArgs)
  5260. {
  5261. ParseNode *pnodeArg = pnode->sxCall.pnodeArgs;
  5262. while (pnodeArg->nop == knopList)
  5263. {
  5264. Emit(pnodeArg->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  5265. pnodeArg = pnodeArg->sxBin.pnode2;
  5266. }
  5267. Emit(pnodeArg, byteCodeGenerator, funcInfo, false);
  5268. }
  5269. break;
  5270. default:
  5271. Emit(pnode, byteCodeGenerator, funcInfo, false);
  5272. break;
  5273. }
  5274. }
  5275. void EmitGetIterator(Js::RegSlot iteratorLocation, Js::RegSlot iterableLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5276. void EmitIteratorNext(Js::RegSlot itemLocation, Js::RegSlot iteratorLocation, Js::RegSlot nextInputLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5277. void EmitIteratorComplete(Js::RegSlot doneLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5278. void EmitIteratorValue(Js::RegSlot valueLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5279. void EmitDestructuredElement(ParseNode *elem, Js::RegSlot sourceLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo *funcInfo)
  5280. {
  5281. switch (elem->nop)
  5282. {
  5283. case knopVarDecl:
  5284. case knopLetDecl:
  5285. case knopConstDecl:
  5286. // We manually need to set NeedDeclaration since the node won't be visited.
  5287. elem->sxVar.sym->SetNeedDeclaration(false);
  5288. break;
  5289. case knopName:
  5290. if (elem->sxPid.sym != nullptr && elem->sxPid.sym->GetNeedDeclaration())
  5291. {
  5292. bool needToRelease = elem->location == Js::Constants::NoRegister;
  5293. EmitUseBeforeDeclaration(elem, byteCodeGenerator, funcInfo);
  5294. if (needToRelease && elem->location != Js::Constants::NoRegister)
  5295. {
  5296. // We have acquired register as a part of EmitUseBeforeDeclaration. We need to release that.
  5297. funcInfo->ReleaseTmpRegister(elem->location);
  5298. }
  5299. }
  5300. break;
  5301. default:
  5302. EmitReference(elem, byteCodeGenerator, funcInfo);
  5303. }
  5304. EmitAssignment(nullptr, elem, sourceLocation, byteCodeGenerator, funcInfo);
  5305. funcInfo->ReleaseReference(elem);
  5306. }
  5307. void EmitDestructuredRestArray(ParseNode *elem, Js::RegSlot iteratorLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  5308. {
  5309. Js::RegSlot restArrayLocation = funcInfo->AcquireTmpRegister();
  5310. byteCodeGenerator->Writer()->Reg1Unsigned1(
  5311. Js::OpCode::NewScArray,
  5312. restArrayLocation,
  5313. ByteCodeGenerator::DefaultArraySize);
  5314. // BytecodeGen can't convey to IRBuilder that some of the temporaries used here are live. When we
  5315. // have a rest parameter, a counter is used in a loop for the array index, but there is no way to
  5316. // convey this is live on the back edge.
  5317. // As a workaround, we have a persistent var reg that is used for the loop counter
  5318. Js::RegSlot counterLocation = elem->location;
  5319. // TODO[ianhall]: Is calling EnregisterConstant() during Emit phase allowed?
  5320. Js::RegSlot zeroConstantReg = byteCodeGenerator->EnregisterConstant(0);
  5321. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, counterLocation, zeroConstantReg);
  5322. // loopTop:
  5323. Js::ByteCodeLabel loopTop = byteCodeGenerator->Writer()->DefineLabel();
  5324. byteCodeGenerator->Writer()->MarkLabel(loopTop);
  5325. Js::RegSlot itemLocation = funcInfo->AcquireTmpRegister();
  5326. EmitIteratorNext(itemLocation, iteratorLocation, Js::Constants::NoRegister, byteCodeGenerator, funcInfo);
  5327. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  5328. EmitIteratorComplete(doneLocation, itemLocation, byteCodeGenerator, funcInfo);
  5329. Js::ByteCodeLabel iteratorDone = byteCodeGenerator->Writer()->DefineLabel();
  5330. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, iteratorDone, doneLocation);
  5331. Js::RegSlot valueLocation = funcInfo->AcquireTmpRegister();
  5332. EmitIteratorValue(valueLocation, itemLocation, byteCodeGenerator, funcInfo);
  5333. byteCodeGenerator->Writer()->Element(
  5334. ByteCodeGenerator::GetStElemIOpCode(funcInfo),
  5335. valueLocation, restArrayLocation, counterLocation);
  5336. funcInfo->ReleaseTmpRegister(valueLocation);
  5337. funcInfo->ReleaseTmpRegister(doneLocation);
  5338. funcInfo->ReleaseTmpRegister(itemLocation);
  5339. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Incr_A, counterLocation, counterLocation);
  5340. byteCodeGenerator->Writer()->Br(loopTop);
  5341. // iteratorDone:
  5342. byteCodeGenerator->Writer()->MarkLabel(iteratorDone);
  5343. ParseNode *restElem = elem->sxUni.pnode1;
  5344. EmitDestructuredElement(restElem, restArrayLocation, byteCodeGenerator, funcInfo);
  5345. funcInfo->ReleaseTmpRegister(restArrayLocation);
  5346. }
  5347. /*
  5348. EmitDestructuredArray(lhsArray, rhs):
  5349. iterator = rhs[@@iterator]
  5350. if lhsArray empty
  5351. return
  5352. for each element in lhsArray except rest
  5353. value = iterator.next()
  5354. if element is a nested destructured array
  5355. EmitDestructuredArray(element, value)
  5356. else
  5357. if value is undefined and there is an initializer
  5358. evaluate initializer
  5359. evaluate element reference
  5360. element = initializer
  5361. else
  5362. element = value
  5363. if lhsArray has a rest element
  5364. rest = []
  5365. while iterator is not done
  5366. value = iterator.next()
  5367. rest.append(value)
  5368. */
  5369. void EmitDestructuredArray(
  5370. ParseNode *lhs,
  5371. Js::RegSlot rhsLocation,
  5372. ByteCodeGenerator *byteCodeGenerator,
  5373. FuncInfo *funcInfo)
  5374. {
  5375. byteCodeGenerator->StartStatement(lhs);
  5376. Js::RegSlot iteratorLocation = funcInfo->AcquireTmpRegister();
  5377. EmitGetIterator(iteratorLocation, rhsLocation, byteCodeGenerator, funcInfo);
  5378. Assert(lhs->nop == knopArrayPattern);
  5379. ParseNode *list = lhs->sxArrLit.pnode1;
  5380. if (list == nullptr)
  5381. {
  5382. // No elements to bind or assign.
  5383. funcInfo->ReleaseTmpRegister(iteratorLocation);
  5384. return;
  5385. }
  5386. ParseNode *elem = nullptr;
  5387. while (list != nullptr)
  5388. {
  5389. ParseNode *init = nullptr;
  5390. if (list->nop == knopList)
  5391. {
  5392. elem = list->sxBin.pnode1;
  5393. }
  5394. else
  5395. {
  5396. elem = list;
  5397. }
  5398. if (elem->nop == knopEllipsis)
  5399. {
  5400. // Rest must be the last argument - no need to continue.
  5401. break;
  5402. }
  5403. switch (elem->nop)
  5404. {
  5405. case knopAsg:
  5406. // An assignment node will always have an initializer
  5407. init = elem->sxBin.pnode2;
  5408. elem = elem->sxBin.pnode1;
  5409. break;
  5410. case knopVarDecl:
  5411. case knopLetDecl:
  5412. case knopConstDecl:
  5413. init = elem->sxVar.pnodeInit;
  5414. break;
  5415. default:
  5416. break;
  5417. }
  5418. byteCodeGenerator->StartStatement(elem);
  5419. Js::RegSlot itemLocation = funcInfo->AcquireTmpRegister();
  5420. EmitIteratorNext(itemLocation, iteratorLocation, Js::Constants::NoRegister, byteCodeGenerator, funcInfo);
  5421. if (elem->nop == knopEmpty)
  5422. {
  5423. // Missing elements only require a next call.
  5424. funcInfo->ReleaseTmpRegister(itemLocation);
  5425. if (list->nop == knopList)
  5426. {
  5427. list = list->sxBin.pnode2;
  5428. continue;
  5429. }
  5430. else
  5431. {
  5432. break;
  5433. }
  5434. }
  5435. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  5436. EmitIteratorComplete(doneLocation, itemLocation, byteCodeGenerator, funcInfo);
  5437. // If the iterator hasn't completed, skip assigning undefined.
  5438. Js::ByteCodeLabel iteratorAlreadyDone = byteCodeGenerator->Writer()->DefineLabel();
  5439. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, iteratorAlreadyDone, doneLocation);
  5440. funcInfo->ReleaseTmpRegister(doneLocation);
  5441. // We're not done with the iterator, so assign the .next() value.
  5442. Js::RegSlot valueLocation = funcInfo->AcquireTmpRegister();
  5443. EmitIteratorValue(valueLocation, itemLocation, byteCodeGenerator, funcInfo);
  5444. Js::ByteCodeLabel beforeDefaultAssign = byteCodeGenerator->Writer()->DefineLabel();
  5445. byteCodeGenerator->Writer()->Br(beforeDefaultAssign);
  5446. // iteratorAlreadyDone:
  5447. byteCodeGenerator->Writer()->MarkLabel(iteratorAlreadyDone);
  5448. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocation, funcInfo->undefinedConstantRegister);
  5449. // beforeDefaultAssign:
  5450. byteCodeGenerator->Writer()->MarkLabel(beforeDefaultAssign);
  5451. if (elem->IsPattern())
  5452. {
  5453. // If we get an undefined value and have an initializer, use it in place of undefined.
  5454. if (init != nullptr)
  5455. {
  5456. /*
  5457. the IR builder uses two symbols for a temp register in the if else path
  5458. R9 <- R3
  5459. if (...)
  5460. R9 <- R2
  5461. R10 = R9.<property> // error -> IR creates a new lifetime for the if path, and the direct path dest is not referenced
  5462. hence we have to create a new temp
  5463. TEMP REG USED TO FIX THIS PRODUCES THIS
  5464. R9 <- R3
  5465. if (BrEq_A R9, R3)
  5466. R10 <- R2 :
  5467. else
  5468. R10 <- R9 : skipdefault
  5469. ... = R10[@@iterator] : loadIter
  5470. */
  5471. // Temp Register
  5472. Js::RegSlot valueLocationTmp = funcInfo->AcquireTmpRegister();
  5473. byteCodeGenerator->StartStatement(init);
  5474. Js::ByteCodeLabel skipDefault = byteCodeGenerator->Writer()->DefineLabel();
  5475. Js::ByteCodeLabel loadIter = byteCodeGenerator->Writer()->DefineLabel();
  5476. // check value is undefined
  5477. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrNeq_A, skipDefault, valueLocation, funcInfo->undefinedConstantRegister);
  5478. // Evaluate the default expression and assign it.
  5479. Emit(init, byteCodeGenerator, funcInfo, false);
  5480. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocationTmp, init->location);
  5481. funcInfo->ReleaseLoc(init);
  5482. // jmp to loadIter
  5483. byteCodeGenerator->Writer()->Br(loadIter);
  5484. // skipDefault:
  5485. byteCodeGenerator->Writer()->MarkLabel(skipDefault);
  5486. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocationTmp, valueLocation);
  5487. // loadIter:
  5488. // @@iterator
  5489. byteCodeGenerator->Writer()->MarkLabel(loadIter);
  5490. byteCodeGenerator->EndStatement(init);
  5491. if (elem->nop == knopObjectPattern)
  5492. {
  5493. EmitDestructuredObject(elem, valueLocationTmp, byteCodeGenerator, funcInfo);
  5494. }
  5495. else
  5496. {
  5497. // Recursively emit a destructured array using the current .next() as the RHS.
  5498. EmitDestructuredArray(elem, valueLocationTmp, byteCodeGenerator, funcInfo);
  5499. }
  5500. funcInfo->ReleaseTmpRegister(valueLocationTmp);
  5501. }
  5502. else
  5503. {
  5504. if (elem->nop == knopObjectPattern)
  5505. {
  5506. EmitDestructuredObject(elem, valueLocation, byteCodeGenerator, funcInfo);
  5507. }
  5508. else
  5509. {
  5510. // Recursively emit a destructured array using the current .next() as the RHS.
  5511. EmitDestructuredArray(elem, valueLocation, byteCodeGenerator, funcInfo);
  5512. }
  5513. }
  5514. }
  5515. else
  5516. {
  5517. EmitDestructuredValueOrInitializer(elem, valueLocation, init, byteCodeGenerator, funcInfo);
  5518. }
  5519. funcInfo->ReleaseTmpRegister(valueLocation);
  5520. funcInfo->ReleaseTmpRegister(itemLocation);
  5521. byteCodeGenerator->EndStatement(elem);
  5522. if (list->nop == knopList)
  5523. {
  5524. list = list->sxBin.pnode2;
  5525. }
  5526. else
  5527. {
  5528. break;
  5529. }
  5530. }
  5531. // If we saw a rest element, emit the rest array.
  5532. if (elem != nullptr && elem->nop == knopEllipsis)
  5533. {
  5534. EmitDestructuredRestArray(elem, iteratorLocation, byteCodeGenerator, funcInfo);
  5535. }
  5536. funcInfo->ReleaseTmpRegister(iteratorLocation);
  5537. byteCodeGenerator->EndStatement(lhs);
  5538. }
  5539. void EmitNameInvoke(Js::RegSlot lhsLocation,
  5540. Js::RegSlot objectLocation,
  5541. ParseNodePtr nameNode,
  5542. ByteCodeGenerator* byteCodeGenerator,
  5543. FuncInfo* funcInfo)
  5544. {
  5545. Assert(nameNode != nullptr);
  5546. if (nameNode->nop == knopComputedName)
  5547. {
  5548. ParseNodePtr pnode1 = nameNode->sxUni.pnode1;
  5549. Emit(pnode1, byteCodeGenerator, funcInfo, false/*isConstructorCall*/);
  5550. byteCodeGenerator->Writer()->Element(Js::OpCode::LdElemI_A, lhsLocation, objectLocation, pnode1->location);
  5551. funcInfo->ReleaseLoc(pnode1);
  5552. }
  5553. else
  5554. {
  5555. Assert(nameNode->nop == knopName || nameNode->nop == knopStr);
  5556. Symbol *sym = nameNode->sxPid.sym;
  5557. Js::PropertyId propertyId = sym ? sym->EnsurePosition(byteCodeGenerator) : nameNode->sxPid.pid->GetPropertyId();
  5558. uint cacheId = funcInfo->FindOrAddInlineCacheId(objectLocation, propertyId, false/*isLoadMethod*/, false/*isStore*/);
  5559. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, lhsLocation, objectLocation, cacheId);
  5560. }
  5561. }
  5562. void EmitDestructuredValueOrInitializer(ParseNodePtr lhsElementNode,
  5563. Js::RegSlot rhsLocation,
  5564. ParseNodePtr initializer,
  5565. ByteCodeGenerator *byteCodeGenerator,
  5566. FuncInfo *funcInfo)
  5567. {
  5568. // 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
  5569. Js::ByteCodeLabel useDefault = -1;
  5570. Js::ByteCodeLabel end = -1;
  5571. Js::RegSlot rhsLocationTmp = rhsLocation;
  5572. if (initializer != nullptr)
  5573. {
  5574. rhsLocationTmp = funcInfo->AcquireTmpRegister();
  5575. useDefault = byteCodeGenerator->Writer()->DefineLabel();
  5576. end = byteCodeGenerator->Writer()->DefineLabel();
  5577. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, useDefault, rhsLocation, funcInfo->undefinedConstantRegister);
  5578. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocationTmp, rhsLocation);
  5579. byteCodeGenerator->Writer()->Br(end);
  5580. byteCodeGenerator->Writer()->MarkLabel(useDefault);
  5581. Emit(initializer, byteCodeGenerator, funcInfo, false/*isConstructorCall*/);
  5582. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocationTmp, initializer->location);
  5583. funcInfo->ReleaseLoc(initializer);
  5584. byteCodeGenerator->Writer()->MarkLabel(end);
  5585. }
  5586. if (lhsElementNode->nop == knopArrayPattern)
  5587. {
  5588. EmitDestructuredArray(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5589. }
  5590. else if (lhsElementNode->nop == knopObjectPattern)
  5591. {
  5592. EmitDestructuredObject(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5593. }
  5594. else
  5595. {
  5596. EmitDestructuredElement(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5597. }
  5598. if (initializer != nullptr)
  5599. {
  5600. funcInfo->ReleaseTmpRegister(rhsLocationTmp);
  5601. }
  5602. }
  5603. void EmitDestructuredObjectMember(ParseNodePtr memberNode,
  5604. Js::RegSlot rhsLocation,
  5605. ByteCodeGenerator *byteCodeGenerator,
  5606. FuncInfo *funcInfo)
  5607. {
  5608. Assert(memberNode->nop == knopObjectPatternMember);
  5609. Js::RegSlot nameLocation = funcInfo->AcquireTmpRegister();
  5610. EmitNameInvoke(nameLocation, rhsLocation, memberNode->sxBin.pnode1, byteCodeGenerator, funcInfo);
  5611. // Imagine we are transforming
  5612. // {x:x1} = {} to x1 = {}.x (here x1 is the second node of the member but that is our lhsnode)
  5613. ParseNodePtr lhsElementNode = memberNode->sxBin.pnode2;
  5614. ParseNodePtr init = nullptr;
  5615. if (lhsElementNode->IsVarLetOrConst())
  5616. {
  5617. init = lhsElementNode->sxVar.pnodeInit;
  5618. }
  5619. else if (lhsElementNode->nop == knopAsg)
  5620. {
  5621. init = lhsElementNode->sxBin.pnode2;
  5622. lhsElementNode = lhsElementNode->sxBin.pnode1;
  5623. }
  5624. EmitDestructuredValueOrInitializer(lhsElementNode, nameLocation, init, byteCodeGenerator, funcInfo);
  5625. funcInfo->ReleaseTmpRegister(nameLocation);
  5626. }
  5627. void EmitDestructuredObject(ParseNode *lhs,
  5628. Js::RegSlot rhsLocationOrig,
  5629. ByteCodeGenerator *byteCodeGenerator,
  5630. FuncInfo *funcInfo)
  5631. {
  5632. Assert(lhs->nop == knopObjectPattern);
  5633. ParseNodePtr pnode1 = lhs->sxUni.pnode1;
  5634. byteCodeGenerator->StartStatement(lhs);
  5635. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  5636. Js::RegSlot rhsLocation = funcInfo->AcquireTmpRegister();
  5637. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocation, rhsLocationOrig);
  5638. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrNeq_A, skipThrow, rhsLocation, funcInfo->undefinedConstantRegister);
  5639. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ObjectCoercible));
  5640. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  5641. if (pnode1 != nullptr)
  5642. {
  5643. Assert(pnode1->nop == knopList || pnode1->nop == knopObjectPatternMember);
  5644. ParseNodePtr current = pnode1;
  5645. while (current->nop == knopList)
  5646. {
  5647. ParseNodePtr memberNode = current->sxBin.pnode1;
  5648. EmitDestructuredObjectMember(memberNode, rhsLocation, byteCodeGenerator, funcInfo);
  5649. current = current->sxBin.pnode2;
  5650. }
  5651. EmitDestructuredObjectMember(current, rhsLocation, byteCodeGenerator, funcInfo);
  5652. }
  5653. funcInfo->ReleaseTmpRegister(rhsLocation);
  5654. byteCodeGenerator->EndStatement(lhs);
  5655. }
  5656. void EmitAssignment(
  5657. ParseNode *asgnNode,
  5658. ParseNode *lhs,
  5659. Js::RegSlot rhsLocation,
  5660. ByteCodeGenerator *byteCodeGenerator,
  5661. FuncInfo *funcInfo)
  5662. {
  5663. switch (lhs->nop)
  5664. {
  5665. // assignment to a local or global variable
  5666. case knopVarDecl:
  5667. case knopLetDecl:
  5668. case knopConstDecl:
  5669. {
  5670. Symbol *sym = lhs->sxVar.sym;
  5671. Assert(sym != nullptr);
  5672. byteCodeGenerator->EmitPropStore(rhsLocation, sym, nullptr, funcInfo, lhs->nop == knopLetDecl, lhs->nop == knopConstDecl);
  5673. break;
  5674. }
  5675. case knopName:
  5676. {
  5677. byteCodeGenerator->EmitPropStore(rhsLocation, lhs->sxPid.sym, lhs->sxPid.pid, funcInfo);
  5678. break;
  5679. }
  5680. // x.y =
  5681. case knopDot:
  5682. {
  5683. // PutValue(x, "y", rhs)
  5684. Js::PropertyId propertyId = lhs->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  5685. uint cacheId = funcInfo->FindOrAddInlineCacheId(lhs->sxBin.pnode1->location, propertyId, false, true);
  5686. if (lhs->sxBin.pnode1->nop == knopSuper)
  5687. {
  5688. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(Js::OpCode::StSuperFld, rhsLocation, lhs->sxBin.pnode1->location, funcInfo->thisPointerRegister, cacheId);
  5689. }
  5690. else
  5691. {
  5692. byteCodeGenerator->Writer()->PatchableProperty(
  5693. ByteCodeGenerator::GetStFldOpCode(funcInfo, false, false, false, false), rhsLocation, lhs->sxBin.pnode1->location, cacheId);
  5694. }
  5695. break;
  5696. }
  5697. case knopIndex:
  5698. {
  5699. byteCodeGenerator->Writer()->Element(
  5700. ByteCodeGenerator::GetStElemIOpCode(funcInfo),
  5701. rhsLocation, lhs->sxBin.pnode1->location, lhs->sxBin.pnode2->location);
  5702. break;
  5703. }
  5704. case knopObjectPattern:
  5705. {
  5706. Assert(byteCodeGenerator->IsES6DestructuringEnabled());
  5707. // Copy the rhs value to be the result of the assignment if needed.
  5708. if (asgnNode != nullptr)
  5709. {
  5710. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  5711. }
  5712. return EmitDestructuredObject(lhs, rhsLocation, byteCodeGenerator, funcInfo);
  5713. }
  5714. case knopArrayPattern:
  5715. {
  5716. Assert(byteCodeGenerator->IsES6DestructuringEnabled());
  5717. // Copy the rhs value to be the result of the assignment if needed.
  5718. if (asgnNode != nullptr)
  5719. {
  5720. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  5721. }
  5722. return EmitDestructuredArray(lhs, rhsLocation, byteCodeGenerator, funcInfo);
  5723. }
  5724. case knopArray:
  5725. case knopObject:
  5726. // Assignment to array/object can get through to byte code gen when the parser fails to convert destructuring
  5727. // assignment to pattern (because of structural mismatch between LHS & RHS?). Revisit when we nail
  5728. // down early vs. runtime errors for destructuring.
  5729. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  5730. break;
  5731. default:
  5732. Assert(!PHASE_ON1(Js::EarlyReferenceErrorsPhase));
  5733. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  5734. break;
  5735. }
  5736. if (asgnNode != nullptr)
  5737. {
  5738. // We leave it up to the caller to pass this node only if the assignment expression is used.
  5739. if (asgnNode->location != rhsLocation)
  5740. {
  5741. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  5742. }
  5743. }
  5744. }
  5745. void EmitLoad(
  5746. ParseNode *lhs,
  5747. ByteCodeGenerator *byteCodeGenerator,
  5748. FuncInfo *funcInfo)
  5749. {
  5750. // Emit the instructions to load the value into the LHS location. Do not assign/free any temps
  5751. // in the process.
  5752. // We usually get here as part of an op-equiv expression: x.y += z;
  5753. // In such a case, x has to be emitted first, then the value of x.y loaded (by this function), then z emitted.
  5754. switch (lhs->nop)
  5755. {
  5756. // load of a local or global variable
  5757. case knopName:
  5758. {
  5759. funcInfo->AcquireLoc(lhs);
  5760. byteCodeGenerator->EmitPropLoad(lhs->location, lhs->sxPid.sym, lhs->sxPid.pid, funcInfo);
  5761. break;
  5762. }
  5763. // = x.y
  5764. case knopDot:
  5765. {
  5766. // get field id for "y"
  5767. Js::PropertyId propertyId = lhs->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  5768. funcInfo->AcquireLoc(lhs);
  5769. EmitReference(lhs, byteCodeGenerator, funcInfo);
  5770. uint cacheId = funcInfo->FindOrAddInlineCacheId(lhs->sxBin.pnode1->location, propertyId, false, false);
  5771. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, lhs->location, lhs->sxBin.pnode1->location, cacheId);
  5772. break;
  5773. }
  5774. case knopIndex:
  5775. funcInfo->AcquireLoc(lhs);
  5776. EmitReference(lhs, byteCodeGenerator, funcInfo);
  5777. byteCodeGenerator->Writer()->Element(
  5778. Js::OpCode::LdElemI_A, lhs->location, lhs->sxBin.pnode1->location, lhs->sxBin.pnode2->location);
  5779. break;
  5780. // f(x) +=
  5781. case knopCall:
  5782. funcInfo->AcquireLoc(lhs);
  5783. EmitReference(lhs, byteCodeGenerator, funcInfo);
  5784. EmitCall(lhs, /*rhs=*/ Js::Constants::NoRegister, byteCodeGenerator, funcInfo, /*fReturnValue=*/ false, /*fAssignRegs=*/ false, /*fHasNewTarget=*/ false);
  5785. break;
  5786. default:
  5787. funcInfo->AcquireLoc(lhs);
  5788. Emit(lhs, byteCodeGenerator, funcInfo, false);
  5789. break;
  5790. }
  5791. }
  5792. void EmitList(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  5793. {
  5794. if (pnode != nullptr)
  5795. {
  5796. while (pnode->nop == knopList)
  5797. {
  5798. byteCodeGenerator->EmitTopLevelStatement(pnode->sxBin.pnode1, funcInfo, false);
  5799. pnode = pnode->sxBin.pnode2;
  5800. }
  5801. byteCodeGenerator->EmitTopLevelStatement(pnode, funcInfo, false);
  5802. }
  5803. }
  5804. void EmitSpreadArgToListBytecodeInstr(ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, Js::RegSlot argLoc, Js::ProfileId callSiteId, Js::ArgSlot &argIndex)
  5805. {
  5806. Js::RegSlot regVal = funcInfo->AcquireTmpRegister();
  5807. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, argLoc);
  5808. byteCodeGenerator->Writer()->ArgOut<true>(++argIndex, regVal, callSiteId);
  5809. funcInfo->ReleaseTmpRegister(regVal);
  5810. }
  5811. size_t EmitArgs(
  5812. ParseNode *pnode,
  5813. BOOL fAssignRegs,
  5814. ByteCodeGenerator *byteCodeGenerator,
  5815. FuncInfo *funcInfo,
  5816. Js::ProfileId callSiteId,
  5817. Js::AuxArray<uint32> *spreadIndices = nullptr
  5818. )
  5819. {
  5820. Js::ArgSlot argIndex = 0;
  5821. Js::ArgSlot spreadIndex = 0;
  5822. if (pnode != nullptr)
  5823. {
  5824. while (pnode->nop == knopList)
  5825. {
  5826. // If this is a put, the arguments have already been evaluated (see EmitReference).
  5827. // We just need to emit the ArgOut instructions.
  5828. if (fAssignRegs)
  5829. {
  5830. Emit(pnode->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  5831. }
  5832. if (pnode->sxBin.pnode1->nop == knopEllipsis)
  5833. {
  5834. Assert(spreadIndices != nullptr);
  5835. spreadIndices->elements[spreadIndex++] = argIndex + 1; // account for 'this'
  5836. EmitSpreadArgToListBytecodeInstr(byteCodeGenerator, funcInfo, pnode->sxBin.pnode1->location, callSiteId, argIndex);
  5837. }
  5838. else
  5839. {
  5840. byteCodeGenerator->Writer()->ArgOut<true>(++argIndex, pnode->sxBin.pnode1->location, callSiteId);
  5841. }
  5842. if (fAssignRegs)
  5843. {
  5844. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  5845. }
  5846. pnode = pnode->sxBin.pnode2;
  5847. }
  5848. // If this is a put, the call target has already been evaluated (see EmitReference).
  5849. if (fAssignRegs)
  5850. {
  5851. Emit(pnode, byteCodeGenerator, funcInfo, false);
  5852. }
  5853. if (pnode->nop == knopEllipsis)
  5854. {
  5855. Assert(spreadIndices != nullptr);
  5856. spreadIndices->elements[spreadIndex++] = argIndex + 1; // account for 'this'
  5857. EmitSpreadArgToListBytecodeInstr(byteCodeGenerator, funcInfo, pnode->location, callSiteId, argIndex);
  5858. }
  5859. else
  5860. {
  5861. byteCodeGenerator->Writer()->ArgOut<true>(++argIndex, pnode->location, callSiteId);
  5862. }
  5863. if (fAssignRegs)
  5864. {
  5865. funcInfo->ReleaseLoc(pnode);
  5866. }
  5867. }
  5868. return argIndex;
  5869. }
  5870. void EmitArgListStart(
  5871. Js::RegSlot thisLocation,
  5872. ByteCodeGenerator *byteCodeGenerator,
  5873. FuncInfo *funcInfo,
  5874. Js::ProfileId callSiteId)
  5875. {
  5876. if (thisLocation != Js::Constants::NoRegister)
  5877. {
  5878. // Emit the "this" object.
  5879. byteCodeGenerator->Writer()->ArgOut<true>(0, thisLocation, callSiteId);
  5880. }
  5881. }
  5882. Js::ArgSlot EmitArgListEnd(
  5883. ParseNode *pnode,
  5884. Js::RegSlot rhsLocation,
  5885. Js::RegSlot thisLocation,
  5886. Js::RegSlot evalLocation,
  5887. Js::RegSlot newTargetLocation,
  5888. ByteCodeGenerator *byteCodeGenerator,
  5889. FuncInfo *funcInfo,
  5890. size_t argIndex,
  5891. Js::ProfileId callSiteId)
  5892. {
  5893. BOOL fEvalInModule = false;
  5894. BOOL fIsPut = (rhsLocation != Js::Constants::NoRegister);
  5895. BOOL fIsEval = (evalLocation != Js::Constants::NoRegister);
  5896. BOOL fHasNewTarget = (newTargetLocation != Js::Constants::NoRegister);
  5897. Js::ArgSlot argSlotIndex = (Js::ArgSlot) argIndex;
  5898. static const Js::ArgSlot maxExtraArgSlot = 4; // max(extraEvalArg, extraArg), where extraEvalArg==2 (moduleRoot,env), extraArg==4 (this, eval, evalInModule, newTarget)
  5899. // check for integer overflow with margin for increments below to calculate argument count
  5900. if ((size_t)argSlotIndex != argIndex || argSlotIndex + maxExtraArgSlot < argSlotIndex)
  5901. {
  5902. Js::Throw::OutOfMemory();
  5903. }
  5904. Js::ArgSlot evalIndex;
  5905. if (fIsPut)
  5906. {
  5907. // Emit the assigned value as an additional operand. Note that the value has already been evaluated.
  5908. // We just need to emit the ArgOut instruction.
  5909. argSlotIndex++;
  5910. byteCodeGenerator->Writer()->ArgOut<true>(argSlotIndex, rhsLocation, callSiteId);
  5911. }
  5912. if (fIsEval && argSlotIndex > 0)
  5913. {
  5914. Assert(!fHasNewTarget);
  5915. // Pass the frame display as an extra argument to "eval".
  5916. // Do this only if eval is called with some args
  5917. Js::RegSlot evalEnv;
  5918. if (funcInfo->IsGlobalFunction() && !(funcInfo->GetIsStrictMode() && byteCodeGenerator->GetFlags() & fscrEval))
  5919. {
  5920. // Use current environment as the environment for the function being called when:
  5921. // - this is the root global function (not an eval's global function)
  5922. // - this is an eval's global function that is not in strict mode (see else block)
  5923. evalEnv = funcInfo->GetEnvRegister();
  5924. }
  5925. else
  5926. {
  5927. // Use the frame display as the environment for the function being called when:
  5928. // - this is not a global function and thus it will have its own scope
  5929. // - this is an eval's global function that is in strict mode, since in strict mode the eval's global function
  5930. // has its own scope
  5931. evalEnv = funcInfo->frameDisplayRegister;
  5932. }
  5933. evalEnv = byteCodeGenerator->PrependLocalScopes(evalEnv, evalLocation, funcInfo);
  5934. Js::ModuleID moduleID = byteCodeGenerator->GetModuleID();
  5935. if (moduleID != kmodGlobal)
  5936. {
  5937. // Pass both the module root and the environment.
  5938. fEvalInModule = true;
  5939. byteCodeGenerator->Writer()->ArgOut<true>(argSlotIndex + 1, ByteCodeGenerator::RootObjectRegister, callSiteId);
  5940. evalIndex = argSlotIndex + 2;
  5941. }
  5942. else
  5943. {
  5944. // Just pass the environment.
  5945. evalIndex = argSlotIndex + 1;
  5946. }
  5947. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  5948. {
  5949. byteCodeGenerator->Writer()->ArgOutEnv(evalIndex);
  5950. }
  5951. else
  5952. {
  5953. byteCodeGenerator->Writer()->ArgOut<false>(evalIndex, evalEnv, callSiteId);
  5954. }
  5955. }
  5956. if (fHasNewTarget)
  5957. {
  5958. Assert(!fIsEval);
  5959. byteCodeGenerator->Writer()->ArgOut<true>(argSlotIndex + 1, newTargetLocation, callSiteId);
  5960. }
  5961. Js::ArgSlot argIntCount = argSlotIndex + 1 + (Js::ArgSlot)fIsEval + (Js::ArgSlot)fEvalInModule + (Js::ArgSlot)fHasNewTarget;
  5962. // eval and no args passed, return 1 as argument count
  5963. if (fIsEval && pnode == nullptr)
  5964. {
  5965. return 1;
  5966. }
  5967. return argIntCount;
  5968. }
  5969. Js::ArgSlot EmitArgList(
  5970. ParseNode *pnode,
  5971. Js::RegSlot rhsLocation,
  5972. Js::RegSlot thisLocation,
  5973. Js::RegSlot newTargetLocation,
  5974. BOOL fIsEval,
  5975. BOOL fAssignRegs,
  5976. ByteCodeGenerator *byteCodeGenerator,
  5977. FuncInfo *funcInfo,
  5978. Js::ProfileId callSiteId,
  5979. uint16 spreadArgCount = 0,
  5980. Js::AuxArray<uint32> **spreadIndices = nullptr)
  5981. {
  5982. // This function emits the arguments for a call.
  5983. // ArgOut's with uses immediately following defs.
  5984. EmitArgListStart(thisLocation, byteCodeGenerator, funcInfo, callSiteId);
  5985. Js::RegSlot evalLocation = Js::Constants::NoRegister;
  5986. //
  5987. // If Emitting arguments for eval and assigning registers, get a tmpLocation for eval.
  5988. // This would be used while generating frameDisplay in EmitArgListEnd.
  5989. //
  5990. if (fIsEval)
  5991. {
  5992. evalLocation = funcInfo->AcquireTmpRegister();
  5993. }
  5994. if (spreadArgCount > 0)
  5995. {
  5996. const size_t extraAlloc = spreadArgCount * sizeof(uint32);
  5997. Assert(spreadIndices != nullptr);
  5998. *spreadIndices = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<uint32>, spreadArgCount);
  5999. }
  6000. size_t argIndex = EmitArgs(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, spreadIndices == nullptr ? nullptr : *spreadIndices);
  6001. Js::ArgSlot argumentsCount = EmitArgListEnd(pnode, rhsLocation, thisLocation, evalLocation, newTargetLocation, byteCodeGenerator, funcInfo, argIndex, callSiteId);
  6002. if (fIsEval)
  6003. {
  6004. funcInfo->ReleaseTmpRegister(evalLocation);
  6005. }
  6006. return argumentsCount;
  6007. }
  6008. void EmitConstantArgsToVarArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) Js::Var *vars, ParseNode *args, uint argCount)
  6009. {
  6010. uint index = 0;
  6011. while (args->nop == knopList && index < argCount)
  6012. {
  6013. if (args->sxBin.pnode1->nop == knopInt)
  6014. {
  6015. int value = args->sxBin.pnode1->sxInt.lw;
  6016. vars[index++] = Js::TaggedInt::ToVarUnchecked(value);
  6017. }
  6018. else if (args->sxBin.pnode1->nop == knopFlt)
  6019. {
  6020. Js::Var number = Js::JavascriptNumber::New(args->sxBin.pnode1->sxFlt.dbl, byteCodeGenerator->GetScriptContext());
  6021. #if ! FLOATVAR
  6022. byteCodeGenerator->GetScriptContext()->BindReference(number);
  6023. #endif
  6024. vars[index++] = number;
  6025. }
  6026. else
  6027. {
  6028. AnalysisAssert(false);
  6029. }
  6030. args = args->sxBin.pnode2;
  6031. }
  6032. if (index == argCount)
  6033. {
  6034. Assert(false);
  6035. Js::Throw::InternalError();
  6036. return;
  6037. }
  6038. if (args->nop == knopInt)
  6039. {
  6040. int value = args->sxInt.lw;
  6041. vars[index++] = Js::TaggedInt::ToVarUnchecked(value);
  6042. }
  6043. else if (args->nop == knopFlt)
  6044. {
  6045. Js::Var number = Js::JavascriptNumber::New(args->sxFlt.dbl, byteCodeGenerator->GetScriptContext());
  6046. #if ! FLOATVAR
  6047. byteCodeGenerator->GetScriptContext()->BindReference(number);
  6048. #endif
  6049. vars[index++] = number;
  6050. }
  6051. else
  6052. {
  6053. AnalysisAssert(false);
  6054. }
  6055. }
  6056. void EmitConstantArgsToIntArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) int32 *vars, ParseNode *args, uint argCount)
  6057. {
  6058. uint index = 0;
  6059. while (args->nop == knopList && index < argCount)
  6060. {
  6061. Assert(args->sxBin.pnode1->nop == knopInt);
  6062. vars[index++] = args->sxBin.pnode1->sxInt.lw;
  6063. args = args->sxBin.pnode2;
  6064. }
  6065. if (index == argCount)
  6066. {
  6067. Assert(false);
  6068. Js::Throw::InternalError();
  6069. return;
  6070. }
  6071. Assert(args->nop == knopInt);
  6072. vars[index++] = args->sxInt.lw;
  6073. Assert(index == argCount);
  6074. }
  6075. void EmitConstantArgsToFltArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) double *vars, ParseNode *args, uint argCount)
  6076. {
  6077. uint index = 0;
  6078. while (args->nop == knopList && index < argCount)
  6079. {
  6080. OpCode nop = args->sxBin.pnode1->nop;
  6081. if (nop == knopInt)
  6082. {
  6083. vars[index++] = (double)args->sxBin.pnode1->sxInt.lw;
  6084. }
  6085. else
  6086. {
  6087. Assert(nop == knopFlt);
  6088. vars[index++] = args->sxBin.pnode1->sxFlt.dbl;
  6089. }
  6090. args = args->sxBin.pnode2;
  6091. }
  6092. if (index == argCount)
  6093. {
  6094. Assert(false);
  6095. Js::Throw::InternalError();
  6096. return;
  6097. }
  6098. if (args->nop == knopInt)
  6099. {
  6100. vars[index++] = (double)args->sxInt.lw;
  6101. }
  6102. else
  6103. {
  6104. Assert(args->nop == knopFlt);
  6105. vars[index++] = args->sxFlt.dbl;
  6106. }
  6107. Assert(index == argCount);
  6108. }
  6109. //
  6110. // Called when we have new Ctr(constant, constant...)
  6111. //
  6112. Js::ArgSlot EmitNewObjectOfConstants(
  6113. ParseNode *pnode,
  6114. ByteCodeGenerator *byteCodeGenerator,
  6115. FuncInfo *funcInfo,
  6116. unsigned int argCount)
  6117. {
  6118. EmitArgListStart(Js::Constants::NoRegister, byteCodeGenerator, funcInfo, Js::Constants::NoProfileId);
  6119. // Create the vars array
  6120. Js::VarArrayVarCount *vars = AnewPlus(byteCodeGenerator->GetAllocator(), (argCount - 1) * sizeof(Js::Var), Js::VarArrayVarCount, Js::TaggedInt::ToVarUnchecked(argCount - 1));
  6121. // Emit all constants to the vars array
  6122. EmitConstantArgsToVarArray(byteCodeGenerator, vars->elements, pnode->sxCall.pnodeArgs, argCount - 1);
  6123. // Finish the arg list
  6124. Js::ArgSlot actualArgCount = EmitArgListEnd(
  6125. pnode->sxCall.pnodeArgs,
  6126. Js::Constants::NoRegister,
  6127. Js::Constants::NoRegister,
  6128. Js::Constants::NoRegister,
  6129. Js::Constants::NoRegister,
  6130. byteCodeGenerator,
  6131. funcInfo,
  6132. argCount - 1,
  6133. Js::Constants::NoProfileId);
  6134. // Make sure the cacheId to regSlot map in the ByteCodeWriter is left in a consistent state after writing NewScObject_A
  6135. byteCodeGenerator->Writer()->RemoveEntryForRegSlotFromCacheIdMap(pnode->sxCall.pnodeTarget->location);
  6136. // Generate the opcode with vars
  6137. byteCodeGenerator->Writer()->AuxiliaryContext(
  6138. Js::OpCode::NewScObject_A,
  6139. funcInfo->AcquireLoc(pnode),
  6140. vars,
  6141. sizeof(Js::VarArray) + (argCount - 1) * sizeof(Js::Var),
  6142. pnode->sxCall.pnodeTarget->location);
  6143. AdeletePlus(byteCodeGenerator->GetAllocator(), (argCount - 1) * sizeof(Js::VarArrayVarCount), vars);
  6144. return actualArgCount;
  6145. }
  6146. void EmitMethodFld(bool isRoot, bool isScoped, Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, bool registerCacheIdForCall = true)
  6147. {
  6148. Js::OpCode opcode;
  6149. if (!isRoot)
  6150. {
  6151. if (callObjLocation == funcInfo->frameObjRegister)
  6152. {
  6153. opcode = Js::OpCode::LdLocalMethodFld;
  6154. }
  6155. else
  6156. {
  6157. opcode = Js::OpCode::LdMethodFld;
  6158. }
  6159. }
  6160. else if (isScoped)
  6161. {
  6162. opcode = Js::OpCode::ScopedLdMethodFld;
  6163. }
  6164. else
  6165. {
  6166. opcode = Js::OpCode::LdRootMethodFld;
  6167. }
  6168. if (isScoped || !isRoot)
  6169. {
  6170. Assert(isScoped || !isRoot || callObjLocation == ByteCodeGenerator::RootObjectRegister);
  6171. uint cacheId = funcInfo->FindOrAddInlineCacheId(callObjLocation, propertyId, true, false);
  6172. if (callObjLocation == funcInfo->frameObjRegister)
  6173. {
  6174. byteCodeGenerator->Writer()->ElementP(opcode, location, cacheId, false /*isCtor*/, registerCacheIdForCall);
  6175. }
  6176. else
  6177. {
  6178. byteCodeGenerator->Writer()->PatchableProperty(opcode, location, callObjLocation, cacheId, false /*isCtor*/, registerCacheIdForCall);
  6179. }
  6180. }
  6181. else
  6182. {
  6183. uint cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, true, false);
  6184. byteCodeGenerator->Writer()->PatchableRootProperty(opcode, location, cacheId, true, false, registerCacheIdForCall);
  6185. }
  6186. }
  6187. void EmitMethodFld(ParseNode *pnode, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, bool registerCacheIdForCall = true)
  6188. {
  6189. // Load a call target of the form x.y(). (Call target may be a plain knopName if we're getting it from
  6190. // the global object, etc.)
  6191. bool isRoot = pnode->nop == knopName && (pnode->sxPid.sym == nullptr || pnode->sxPid.sym->GetIsGlobal());
  6192. bool isScoped = (byteCodeGenerator->GetFlags() & fscrEval) != 0 ||
  6193. (isRoot && callObjLocation != ByteCodeGenerator::RootObjectRegister);
  6194. EmitMethodFld(isRoot, isScoped, pnode->location, callObjLocation, propertyId, byteCodeGenerator, funcInfo, registerCacheIdForCall);
  6195. }
  6196. // lhs.apply(this, arguments);
  6197. void EmitApplyCall(ParseNode* pnode, Js::RegSlot rhsLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue, BOOL fAssignRegs)
  6198. {
  6199. ParseNode* applyNode = pnode->sxCall.pnodeTarget;
  6200. ParseNode* thisNode = pnode->sxCall.pnodeArgs->sxBin.pnode1;
  6201. Assert(applyNode->nop == knopDot);
  6202. ParseNode* funcNode = applyNode->sxBin.pnode1;
  6203. Js::ByteCodeLabel slowPath = byteCodeGenerator->Writer()->DefineLabel();
  6204. Js::ByteCodeLabel afterSlowPath = byteCodeGenerator->Writer()->DefineLabel();
  6205. Js::ByteCodeLabel argsAlreadyCreated = byteCodeGenerator->Writer()->DefineLabel();
  6206. Assert(applyNode->nop == knopDot);
  6207. Emit(funcNode, byteCodeGenerator, funcInfo, false);
  6208. funcInfo->AcquireLoc(applyNode);
  6209. Js::PropertyId propertyId = applyNode->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  6210. // As we won't be emitting a call instruction for apply, no need to register the cacheId for apply
  6211. // load to be associated with the call. This is also required, as in the absence of a corresponding
  6212. // call for apply, we won't remove the entry for "apply" cacheId from
  6213. // ByteCodeWriter::callRegToLdFldCacheIndexMap, which is contrary to our assumption that we would
  6214. // have removed an entry from a map upon seeing its corresponding call.
  6215. EmitMethodFld(applyNode, funcNode->location, propertyId, byteCodeGenerator, funcInfo, false /*registerCacheIdForCall*/);
  6216. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  6217. Assert(argSym && argSym->GetIsArguments());
  6218. Js::RegSlot argumentsLoc = argSym->GetLocation();
  6219. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdArgumentsFromFrame, argumentsLoc);
  6220. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrNotNull_A, argsAlreadyCreated, argumentsLoc);
  6221. // If apply is overridden, bail to slow path.
  6222. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFncNeqApply, slowPath, applyNode->location);
  6223. // Note: acquire and release a temp register for this stack arg pointer instead of trying to stash it
  6224. // in funcInfo->stackArgReg. Otherwise, we'll needlessly load and store it in jitted loop bodies and
  6225. // may crash if we try to unbox it on the store.
  6226. Js::RegSlot stackArgReg = funcInfo->AcquireTmpRegister();
  6227. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdStackArgPtr, stackArgReg);
  6228. Js::RegSlot argCountLocation = funcInfo->AcquireTmpRegister();
  6229. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdArgCnt, argCountLocation);
  6230. byteCodeGenerator->Writer()->Reg5(Js::OpCode::ApplyArgs, funcNode->location, funcNode->location, thisNode->location, stackArgReg, argCountLocation);
  6231. funcInfo->ReleaseTmpRegister(argCountLocation);
  6232. funcInfo->ReleaseTmpRegister(stackArgReg);
  6233. funcInfo->ReleaseLoc(applyNode);
  6234. funcInfo->ReleaseLoc(funcNode);
  6235. // Clear these nodes as they are going to be used to re-generate the slow path.
  6236. VisitClearTmpRegs(applyNode, byteCodeGenerator, funcInfo);
  6237. VisitClearTmpRegs(funcNode, byteCodeGenerator, funcInfo);
  6238. byteCodeGenerator->Writer()->Br(afterSlowPath);
  6239. // slow path
  6240. byteCodeGenerator->Writer()->MarkLabel(slowPath);
  6241. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  6242. {
  6243. byteCodeGenerator->EmitScopeObjectInit(funcInfo);
  6244. }
  6245. byteCodeGenerator->LoadHeapArguments(funcInfo);
  6246. byteCodeGenerator->Writer()->MarkLabel(argsAlreadyCreated);
  6247. EmitCall(pnode, rhsLocation, byteCodeGenerator, funcInfo, fReturnValue, fAssignRegs,/*fHasNewTarget*/false);
  6248. byteCodeGenerator->Writer()->MarkLabel(afterSlowPath);
  6249. }
  6250. void EmitMethodElem(ParseNode *pnode, Js::RegSlot callObjLocation, Js::RegSlot indexLocation, ByteCodeGenerator *byteCodeGenerator)
  6251. {
  6252. // Load a call target of the form x[y]().
  6253. byteCodeGenerator->Writer()->Element(Js::OpCode::LdMethodElem, pnode->location, callObjLocation, indexLocation);
  6254. }
  6255. void EmitCallTargetNoEvalComponents(
  6256. ParseNode *pnodeTarget,
  6257. BOOL fSideEffectArgs,
  6258. Js::RegSlot *thisLocation,
  6259. Js::RegSlot *callObjLocation,
  6260. ByteCodeGenerator *byteCodeGenerator,
  6261. FuncInfo *funcInfo)
  6262. {
  6263. // We first get a reference to the call target, then evaluate the arguments, then
  6264. // evaluate the call target.
  6265. // - emit reference to target
  6266. // - copy instance to scratch reg if necessary.
  6267. // - assign this
  6268. // - assign instance for dynamic/global name
  6269. // - emit args
  6270. // - do call (CallFld/Elem/I)
  6271. switch (pnodeTarget->nop)
  6272. {
  6273. case knopDot:
  6274. *thisLocation = pnodeTarget->sxBin.pnode1->location;
  6275. *callObjLocation = pnodeTarget->sxBin.pnode1->location;
  6276. break;
  6277. case knopIndex:
  6278. *thisLocation = pnodeTarget->sxBin.pnode1->location;
  6279. *callObjLocation = pnodeTarget->sxBin.pnode1->location;
  6280. break;
  6281. case knopName:
  6282. // If the call target is a name, do some extra work to get its instance and the "this" pointer.
  6283. byteCodeGenerator->EmitLoadInstance(pnodeTarget->sxPid.sym, pnodeTarget->sxPid.pid, thisLocation, callObjLocation, funcInfo);
  6284. if (*thisLocation == Js::Constants::NoRegister)
  6285. {
  6286. *thisLocation = funcInfo->undefinedConstantRegister;
  6287. }
  6288. EmitUseBeforeDeclaration(pnodeTarget, byteCodeGenerator, funcInfo);
  6289. break;
  6290. default:
  6291. *thisLocation = funcInfo->undefinedConstantRegister;
  6292. break;
  6293. }
  6294. }
  6295. void EmitSuperMethodBegin(
  6296. ParseNode *pnodeTarget,
  6297. ByteCodeGenerator *byteCodeGenerator,
  6298. FuncInfo *funcInfo)
  6299. {
  6300. FuncInfo *parentFuncInfo = funcInfo;
  6301. if (parentFuncInfo->IsLambda())
  6302. {
  6303. parentFuncInfo = byteCodeGenerator->FindEnclosingNonLambda();
  6304. }
  6305. if (pnodeTarget->sxBin.pnode1->nop == knopSuper && parentFuncInfo->IsClassConstructor() && !parentFuncInfo->IsBaseClassConstructor())
  6306. {
  6307. byteCodeGenerator->EmitScopeSlotLoadThis(funcInfo, funcInfo->thisPointerRegister, /*chkUndecl*/ true);
  6308. }
  6309. }
  6310. void EmitCallTarget(
  6311. ParseNode *pnodeTarget,
  6312. BOOL fSideEffectArgs,
  6313. Js::RegSlot *thisLocation,
  6314. Js::RegSlot *callObjLocation,
  6315. ByteCodeGenerator *byteCodeGenerator,
  6316. FuncInfo *funcInfo)
  6317. {
  6318. // - emit target
  6319. // - assign this
  6320. // - emit args
  6321. // - do call
  6322. // The call target is fully evaluated before the argument list. Note that we're not handling
  6323. // put-call cases here currently, as such cases only apply to host objects
  6324. // and are very unlikely to behave differently depending on the order of evaluation.
  6325. switch (pnodeTarget->nop)
  6326. {
  6327. case knopDot:
  6328. {
  6329. funcInfo->AcquireLoc(pnodeTarget);
  6330. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6331. // them from side-effects.
  6332. if (fSideEffectArgs)
  6333. {
  6334. // Though we're done with target evaluation after this point, still protect opnd1 from
  6335. // arg side-effects as it's the "this" pointer.
  6336. SaveOpndValue(pnodeTarget->sxBin.pnode1, funcInfo);
  6337. }
  6338. if ((pnodeTarget->sxBin.pnode2->nop == knopName) && ((pnodeTarget->sxBin.pnode2->sxPid.PropertyIdFromNameNode() == Js::PropertyIds::apply) || (pnodeTarget->sxBin.pnode2->sxPid.PropertyIdFromNameNode() == Js::PropertyIds::call)))
  6339. {
  6340. pnodeTarget->sxBin.pnode1->SetIsCallApplyTargetLoad();
  6341. }
  6342. Emit(pnodeTarget->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  6343. Js::PropertyId propertyId = pnodeTarget->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  6344. Js::RegSlot protoLocation = pnodeTarget->sxBin.pnode1->location;
  6345. EmitSuperMethodBegin(pnodeTarget, byteCodeGenerator, funcInfo);
  6346. EmitMethodFld(pnodeTarget, protoLocation, propertyId, byteCodeGenerator, funcInfo);
  6347. // Function calls on the 'super' object should maintain current 'this' pointer
  6348. *thisLocation = (pnodeTarget->sxBin.pnode1->nop == knopSuper) ? funcInfo->thisPointerRegister : pnodeTarget->sxBin.pnode1->location;
  6349. break;
  6350. }
  6351. case knopIndex:
  6352. {
  6353. funcInfo->AcquireLoc(pnodeTarget);
  6354. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6355. // them from side-effects.
  6356. if (fSideEffectArgs || !(ParseNode::Grfnop(pnodeTarget->sxBin.pnode2->nop) & fnopLeaf))
  6357. {
  6358. // Though we're done with target evaluation after this point, still protect opnd1 from
  6359. // arg or opnd2 side-effects as it's the "this" pointer.
  6360. SaveOpndValue(pnodeTarget->sxBin.pnode1, funcInfo);
  6361. }
  6362. Emit(pnodeTarget->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  6363. Emit(pnodeTarget->sxBin.pnode2, byteCodeGenerator, funcInfo, false);
  6364. Js::RegSlot indexLocation = pnodeTarget->sxBin.pnode2->location;
  6365. Js::RegSlot protoLocation = pnodeTarget->sxBin.pnode1->location;
  6366. EmitSuperMethodBegin(pnodeTarget, byteCodeGenerator, funcInfo);
  6367. EmitMethodElem(pnodeTarget, protoLocation, indexLocation, byteCodeGenerator);
  6368. funcInfo->ReleaseLoc(pnodeTarget->sxBin.pnode2); // don't release indexLocation until after we use it.
  6369. // Function calls on the 'super' object should maintain current 'this' pointer
  6370. *thisLocation = (pnodeTarget->sxBin.pnode1->nop == knopSuper) ? funcInfo->thisPointerRegister : pnodeTarget->sxBin.pnode1->location;
  6371. break;
  6372. }
  6373. case knopClassDecl:
  6374. {
  6375. Emit(pnodeTarget, byteCodeGenerator, funcInfo, false);
  6376. // We won't always have an assigned this register (e.g. class expression calls.) We need undefined in this case.
  6377. *thisLocation = funcInfo->thisPointerRegister == Js::Constants::NoRegister ? funcInfo->undefinedConstantRegister : funcInfo->thisPointerRegister;
  6378. break;
  6379. }
  6380. case knopSuper:
  6381. {
  6382. Emit(pnodeTarget, byteCodeGenerator, funcInfo, false, /*isConstructorCall*/ true); // reuse isConstructorCall ("new super()" is illegal)
  6383. // Super calls should always use the new.target register unless we don't have one.
  6384. // That could happen if we have an eval('super()') outside of a class constructor.
  6385. if (funcInfo->newTargetRegister != Js::Constants::NoRegister)
  6386. {
  6387. *thisLocation = funcInfo->newTargetRegister;
  6388. }
  6389. else
  6390. {
  6391. *thisLocation = funcInfo->thisPointerRegister;
  6392. }
  6393. break;
  6394. }
  6395. case knopName:
  6396. {
  6397. funcInfo->AcquireLoc(pnodeTarget);
  6398. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6399. // them from side-effects.
  6400. if (fSideEffectArgs)
  6401. {
  6402. SaveOpndValue(pnodeTarget, funcInfo);
  6403. }
  6404. byteCodeGenerator->EmitLoadInstance(pnodeTarget->sxPid.sym, pnodeTarget->sxPid.pid, thisLocation, callObjLocation, funcInfo);
  6405. if (*callObjLocation != Js::Constants::NoRegister)
  6406. {
  6407. // Load the call target as a property of the instance.
  6408. Js::PropertyId propertyId = pnodeTarget->sxPid.PropertyIdFromNameNode();
  6409. EmitMethodFld(pnodeTarget, *callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6410. break;
  6411. }
  6412. // FALL THROUGH to evaluate call target.
  6413. }
  6414. default:
  6415. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6416. // them from side-effects.
  6417. Emit(pnodeTarget, byteCodeGenerator, funcInfo, false);
  6418. *thisLocation = funcInfo->undefinedConstantRegister;
  6419. break;
  6420. }
  6421. // "This" pointer should have been assigned by the above.
  6422. Assert(*thisLocation != Js::Constants::NoRegister);
  6423. }
  6424. void EmitCallI(
  6425. ParseNode *pnode,
  6426. BOOL fEvaluateComponents,
  6427. BOOL fIsPut,
  6428. BOOL fIsEval,
  6429. BOOL fHasNewTarget,
  6430. uint32 actualArgCount,
  6431. ByteCodeGenerator *byteCodeGenerator,
  6432. FuncInfo *funcInfo,
  6433. Js::ProfileId callSiteId,
  6434. Js::AuxArray<uint32> *spreadIndices = nullptr)
  6435. {
  6436. // Emit a call where the target is in a register, because it's either a local name or an expression we've
  6437. // already evaluated.
  6438. ParseNode *pnodeTarget = pnode->sxBin.pnode1;
  6439. Js::OpCode op;
  6440. Js::CallFlags callFlags = Js::CallFlags::CallFlags_None;
  6441. uint spreadExtraAlloc = 0;
  6442. Js::ArgSlot actualArgSlotCount = (Js::ArgSlot) actualArgCount;
  6443. // check for integer overflow
  6444. if ((size_t)actualArgSlotCount != actualArgCount)
  6445. {
  6446. Js::Throw::OutOfMemory();
  6447. }
  6448. if (fIsPut)
  6449. {
  6450. if (pnode->sxCall.spreadArgCount > 0)
  6451. {
  6452. // TODO(tcare): We are disallowing spread with CallIPut for the moment. See DEVDIV2: 876387
  6453. // When CallIPut is migrated to the CallIExtended layout, this can be removed.
  6454. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAsgCall));
  6455. }
  6456. // Grab a tmp register for the call result.
  6457. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  6458. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallIFlags, tmpReg, pnodeTarget->location, actualArgSlotCount, callSiteId, Js::CallFlags::CallFlags_NewTarget);
  6459. funcInfo->ReleaseTmpRegister(tmpReg);
  6460. }
  6461. else
  6462. {
  6463. if (fEvaluateComponents)
  6464. {
  6465. // Release the call target operands we assigned above. If we didn't assign them here,
  6466. // we'll need them later, so we can't re-use them for the result of the call.
  6467. funcInfo->ReleaseLoc(pnodeTarget);
  6468. }
  6469. // Grab a register for the call result.
  6470. if (pnode->isUsed)
  6471. {
  6472. funcInfo->AcquireLoc(pnode);
  6473. }
  6474. if (fIsEval)
  6475. {
  6476. op = Js::OpCode::CallIExtendedFlags;
  6477. callFlags = Js::CallFlags::CallFlags_ExtraArg;
  6478. }
  6479. else
  6480. {
  6481. bool isSuperCall = pnodeTarget->nop == knopSuper;
  6482. if (isSuperCall)
  6483. {
  6484. callFlags = Js::CallFlags_New;
  6485. }
  6486. if (fHasNewTarget)
  6487. {
  6488. callFlags = (Js::CallFlags) (callFlags | Js::CallFlags::CallFlags_ExtraArg | Js::CallFlags::CallFlags_NewTarget);
  6489. }
  6490. if (pnode->sxCall.spreadArgCount > 0)
  6491. {
  6492. op = (isSuperCall || fHasNewTarget) ? Js::OpCode::CallIExtendedFlags : Js::OpCode::CallIExtended;
  6493. }
  6494. else
  6495. {
  6496. op = (isSuperCall || fHasNewTarget) ? Js::OpCode::CallIFlags : Js::OpCode::CallI;
  6497. }
  6498. }
  6499. if (op == Js::OpCode::CallI || op == Js::OpCode::CallIFlags)
  6500. {
  6501. byteCodeGenerator->Writer()->CallI(op, pnode->location, pnodeTarget->location, actualArgSlotCount, callSiteId, callFlags);
  6502. }
  6503. else
  6504. {
  6505. uint spreadIndicesSize = 0;
  6506. Js::CallIExtendedOptions options = Js::CallIExtended_None;
  6507. if (pnode->sxCall.spreadArgCount > 0)
  6508. {
  6509. Assert(spreadIndices != nullptr);
  6510. spreadExtraAlloc = spreadIndices->count * sizeof(uint32);
  6511. spreadIndicesSize = sizeof(*spreadIndices) + spreadExtraAlloc;
  6512. options = Js::CallIExtended_SpreadArgs;
  6513. }
  6514. byteCodeGenerator->Writer()->CallIExtended(op, pnode->location, pnodeTarget->location, actualArgSlotCount, options, spreadIndices, spreadIndicesSize, callSiteId, callFlags);
  6515. }
  6516. if (pnode->sxCall.spreadArgCount > 0)
  6517. {
  6518. Assert(spreadExtraAlloc != 0);
  6519. AdeletePlus(byteCodeGenerator->GetAllocator(), spreadExtraAlloc, spreadIndices);
  6520. }
  6521. }
  6522. }
  6523. void EmitCallInstrNoEvalComponents(
  6524. ParseNode *pnode,
  6525. BOOL fIsPut,
  6526. BOOL fIsEval,
  6527. Js::RegSlot thisLocation,
  6528. Js::RegSlot callObjLocation,
  6529. uint32 actualArgCount,
  6530. ByteCodeGenerator *byteCodeGenerator,
  6531. FuncInfo *funcInfo,
  6532. Js::ProfileId callSiteId,
  6533. Js::AuxArray<uint32> *spreadIndices = nullptr)
  6534. {
  6535. // Emit the call instruction. The call target is a reference at this point, and we evaluate
  6536. // it as part of doing the actual call.
  6537. // Note that we don't handle the (fEvaluateComponents == TRUE) case in this function.
  6538. // (This function is only called on the !fEvaluateComponents branch in EmitCall.)
  6539. ParseNode *pnodeTarget = pnode->sxBin.pnode1;
  6540. switch (pnodeTarget->nop)
  6541. {
  6542. case knopDot:
  6543. {
  6544. Assert(pnodeTarget->sxBin.pnode2->nop == knopName);
  6545. Js::PropertyId propertyId = pnodeTarget->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  6546. EmitMethodFld(pnodeTarget, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6547. EmitCallI(pnode, /*fEvaluateComponents*/ FALSE, fIsPut, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6548. }
  6549. break;
  6550. case knopIndex:
  6551. {
  6552. EmitMethodElem(pnodeTarget, pnodeTarget->sxBin.pnode1->location, pnodeTarget->sxBin.pnode2->location, byteCodeGenerator);
  6553. EmitCallI(pnode, /*fEvaluateComponents*/ FALSE, fIsPut, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6554. }
  6555. break;
  6556. case knopName:
  6557. {
  6558. if (callObjLocation != Js::Constants::NoRegister)
  6559. {
  6560. // We still have to get the property from its instance, so emit CallFld.
  6561. if (thisLocation != callObjLocation)
  6562. {
  6563. funcInfo->ReleaseTmpRegister(thisLocation);
  6564. }
  6565. funcInfo->ReleaseTmpRegister(callObjLocation);
  6566. Js::PropertyId propertyId = pnodeTarget->sxPid.PropertyIdFromNameNode();
  6567. EmitMethodFld(pnodeTarget, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6568. EmitCallI(pnode, /*fEvaluateComponents*/ FALSE, fIsPut, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6569. break;
  6570. }
  6571. }
  6572. // FALL THROUGH
  6573. default:
  6574. EmitCallI(pnode, /*fEvaluateComponents*/ FALSE, fIsPut, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6575. break;
  6576. }
  6577. }
  6578. void EmitCallInstr(
  6579. ParseNode *pnode,
  6580. BOOL fIsPut,
  6581. BOOL fIsEval,
  6582. BOOL fHasNewTarget,
  6583. Js::RegSlot thisLocation,
  6584. Js::RegSlot callObjLocation,
  6585. uint32 actualArgCount,
  6586. ByteCodeGenerator *byteCodeGenerator,
  6587. FuncInfo *funcInfo,
  6588. Js::ProfileId callSiteId,
  6589. Js::AuxArray<uint32> *spreadIndices = nullptr)
  6590. {
  6591. // Emit a call instruction. The call target has been fully evaluated already, so we always
  6592. // emit a CallI through the register that holds the target value.
  6593. // Note that we don't handle !fEvaluateComponents cases at this point.
  6594. // (This function is only called on the fEvaluateComponents branch in EmitCall.)
  6595. if (thisLocation != Js::Constants::NoRegister)
  6596. {
  6597. funcInfo->ReleaseTmpRegister(thisLocation);
  6598. }
  6599. if (callObjLocation != Js::Constants::NoRegister &&
  6600. callObjLocation != thisLocation)
  6601. {
  6602. funcInfo->ReleaseTmpRegister(callObjLocation);
  6603. }
  6604. EmitCallI(pnode, /*fEvaluateComponents*/ TRUE, fIsPut, fIsEval, fHasNewTarget, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6605. }
  6606. void EmitCall(
  6607. ParseNode* pnode,
  6608. Js::RegSlot rhsLocation,
  6609. ByteCodeGenerator* byteCodeGenerator,
  6610. FuncInfo* funcInfo,
  6611. BOOL fReturnValue,
  6612. BOOL fEvaluateComponents,
  6613. BOOL fHasNewTarget,
  6614. Js::RegSlot overrideThisLocation)
  6615. {
  6616. BOOL fIsPut = (rhsLocation != Js::Constants::NoRegister);
  6617. // If the call returns a float, we'll note this in the byte code.
  6618. Js::RegSlot thisLocation = Js::Constants::NoRegister;
  6619. Js::RegSlot callObjLocation = Js::Constants::NoRegister;
  6620. Js::RegSlot newTargetLocation = Js::Constants::NoRegister;
  6621. BOOL fSideEffectArgs = FALSE;
  6622. ParseNode *pnodeTarget = pnode->sxCall.pnodeTarget;
  6623. ParseNode *pnodeArgs = pnode->sxCall.pnodeArgs;
  6624. uint16 spreadArgCount = pnode->sxCall.spreadArgCount;
  6625. unsigned int argCount = CountArguments(pnode->sxCall.pnodeArgs, &fSideEffectArgs) + (unsigned int)fIsPut;
  6626. BOOL fIsEval = !fIsPut && pnode->sxCall.isEvalCall;
  6627. if (fIsEval)
  6628. {
  6629. Assert(!fHasNewTarget);
  6630. //
  6631. // "eval" takes the closure environment as an extra argument
  6632. // Pass the closure env only if some argument is passed
  6633. // For just eval(), don't pass the closure environment
  6634. //
  6635. if (argCount > 1)
  6636. {
  6637. // Check the module ID as well. If it's not the global (default) module,
  6638. // we need to pass the root to eval so it can do the right global lookups.
  6639. // (Passing the module root is the least disruptive way to get the module ID
  6640. // to the helper, given the current set of byte codes. Once we have a full set
  6641. // of byte code ops taking immediate opnds, passing the ID is more intuitive.)
  6642. Js::ModuleID moduleID = byteCodeGenerator->GetModuleID();
  6643. if (moduleID == kmodGlobal)
  6644. {
  6645. argCount++;
  6646. }
  6647. else
  6648. {
  6649. // Module ID must be passed
  6650. argCount += 2;
  6651. }
  6652. }
  6653. }
  6654. if (fHasNewTarget)
  6655. {
  6656. Assert(!fIsEval);
  6657. // When we need to pass new.target explicitly, it is passed as an extra argument.
  6658. // This is similar to how eval passes an extra argument for the frame display and is
  6659. // used to support cases where we need to pass both 'this' and new.target as part of
  6660. // a function call.
  6661. // OpCode::LdNewTarget knows how to look at the call flags and fetch this argument.
  6662. argCount++;
  6663. newTargetLocation = funcInfo->newTargetRegister;
  6664. Assert(newTargetLocation != Js::Constants::NoRegister);
  6665. }
  6666. Js::ArgSlot argSlotCount = (Js::ArgSlot)argCount;
  6667. if (argCount != (unsigned int)argSlotCount)
  6668. {
  6669. Js::Throw::OutOfMemory();
  6670. }
  6671. if (fReturnValue)
  6672. {
  6673. pnode->isUsed = true;
  6674. }
  6675. //
  6676. // Set up the call.
  6677. //
  6678. if (!fEvaluateComponents)
  6679. {
  6680. EmitCallTargetNoEvalComponents(pnodeTarget, fSideEffectArgs, &thisLocation, &callObjLocation, byteCodeGenerator, funcInfo);
  6681. }
  6682. else
  6683. {
  6684. EmitCallTarget(pnodeTarget, fSideEffectArgs, &thisLocation, &callObjLocation, byteCodeGenerator, funcInfo);
  6685. }
  6686. bool releaseThisLocation = true;
  6687. // If we are strictly overriding the this location, ignore what the call target set this location to.
  6688. if (overrideThisLocation != Js::Constants::NoRegister)
  6689. {
  6690. thisLocation = overrideThisLocation;
  6691. releaseThisLocation = false;
  6692. }
  6693. // Evaluate the arguments (nothing mode-specific here).
  6694. // Start call, allocate out param space
  6695. funcInfo->StartRecordingOutArgs(argSlotCount);
  6696. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  6697. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argSlotCount);
  6698. Js::AuxArray<uint32> *spreadIndices;
  6699. Js::ArgSlot actualArgCount = EmitArgList(pnodeArgs, rhsLocation, thisLocation, newTargetLocation, fIsEval, fEvaluateComponents, byteCodeGenerator, funcInfo, callSiteId, spreadArgCount, &spreadIndices);
  6700. Assert(argSlotCount == actualArgCount);
  6701. if (!fEvaluateComponents)
  6702. {
  6703. EmitCallInstrNoEvalComponents(pnode, fIsPut, fIsEval, thisLocation, callObjLocation, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6704. }
  6705. else
  6706. {
  6707. EmitCallInstr(pnode, fIsPut, fIsEval, fHasNewTarget, releaseThisLocation ? thisLocation : Js::Constants::NoRegister, callObjLocation, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6708. }
  6709. // End call, pop param space
  6710. funcInfo->EndRecordingOutArgs(argSlotCount);
  6711. }
  6712. void EmitInvoke(
  6713. Js::RegSlot location,
  6714. Js::RegSlot callObjLocation,
  6715. Js::PropertyId propertyId,
  6716. ByteCodeGenerator* byteCodeGenerator,
  6717. FuncInfo* funcInfo)
  6718. {
  6719. EmitMethodFld(false, false, location, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6720. funcInfo->StartRecordingOutArgs(1);
  6721. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  6722. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, 1);
  6723. EmitArgListStart(callObjLocation, byteCodeGenerator, funcInfo, callSiteId);
  6724. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallI, location, location, 1, callSiteId);
  6725. }
  6726. void EmitInvoke(
  6727. Js::RegSlot location,
  6728. Js::RegSlot callObjLocation,
  6729. Js::PropertyId propertyId,
  6730. ByteCodeGenerator* byteCodeGenerator,
  6731. FuncInfo* funcInfo,
  6732. Js::RegSlot arg1Location)
  6733. {
  6734. EmitMethodFld(false, false, location, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6735. funcInfo->StartRecordingOutArgs(2);
  6736. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  6737. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, 2);
  6738. EmitArgListStart(callObjLocation, byteCodeGenerator, funcInfo, callSiteId);
  6739. byteCodeGenerator->Writer()->ArgOut<true>(1, arg1Location, callSiteId);
  6740. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallI, location, location, 2, callSiteId);
  6741. }
  6742. void EmitComputedFunctionNameVar(ParseNode *nameNode, ParseNode *exprNode, ByteCodeGenerator *byteCodeGenerator)
  6743. {
  6744. AssertMsg(exprNode != nullptr, "callers of this function should pass in a valid expression Node");
  6745. if (nameNode == nullptr)
  6746. {
  6747. return;
  6748. }
  6749. if ((exprNode->nop == knopFncDecl && (exprNode->sxFnc.pnodeName == nullptr || exprNode->sxFnc.pnodeName->nop != knopVarDecl)))
  6750. {
  6751. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SetComputedNameVar, exprNode->location, nameNode->location);
  6752. }
  6753. }
  6754. void EmitMemberNode(ParseNode *memberNode, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, ParseNode* parentNode, bool useStore, bool* isObjectEmpty = nullptr)
  6755. {
  6756. ParseNode *nameNode = memberNode->sxBin.pnode1;
  6757. ParseNode *exprNode = memberNode->sxBin.pnode2;
  6758. bool isFncDecl = exprNode->nop == knopFncDecl;
  6759. bool isClassMember = isFncDecl && exprNode->sxFnc.IsClassMember();
  6760. // Moved SetComputedNameVar before LdFld of prototype because loading the prototype undefers the function TypeHandler
  6761. // which makes this bytecode too late to influence the function.name.
  6762. if (nameNode->nop == knopComputedName)
  6763. {
  6764. // Computed property name
  6765. // Transparently pass the name expr
  6766. // The Emit will replace this with a temp register if necessary to preserve the value.
  6767. nameNode->location = nameNode->sxUni.pnode1->location;
  6768. EmitBinaryOpnds(nameNode, exprNode, byteCodeGenerator, funcInfo);
  6769. if (isFncDecl && !exprNode->sxFnc.IsClassConstructor())
  6770. {
  6771. EmitComputedFunctionNameVar(nameNode, exprNode, byteCodeGenerator);
  6772. }
  6773. }
  6774. // Classes allocates a RegSlot as part of Instance Methods EmitClassInitializers,
  6775. // but if we don't have any members then we don't need to load the prototype.
  6776. Assert(isClassMember == (isObjectEmpty != nullptr));
  6777. if (isClassMember && *isObjectEmpty)
  6778. {
  6779. *isObjectEmpty = false;
  6780. int cacheId = funcInfo->FindOrAddInlineCacheId(parentNode->location, Js::PropertyIds::prototype, false, false);
  6781. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, objectLocation, parentNode->location, cacheId);
  6782. }
  6783. if (nameNode->nop == knopComputedName)
  6784. {
  6785. Assert(memberNode->nop == knopGetMember || memberNode->nop == knopSetMember || memberNode->nop == knopMember);
  6786. Js::OpCode setOp = memberNode->nop == knopGetMember ?
  6787. (isClassMember ? Js::OpCode::InitClassMemberGetComputedName : Js::OpCode::InitGetElemI) :
  6788. memberNode->nop == knopSetMember ?
  6789. (isClassMember ? Js::OpCode::InitClassMemberSetComputedName : Js::OpCode::InitSetElemI) :
  6790. (isClassMember ? Js::OpCode::InitClassMemberComputedName : Js::OpCode::InitComputedProperty);
  6791. byteCodeGenerator->Writer()->Element(setOp, exprNode->location, objectLocation, nameNode->location, true);
  6792. // Class and object members need a reference back to the class.
  6793. if (isFncDecl)
  6794. {
  6795. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SetHomeObj, exprNode->location, objectLocation);
  6796. }
  6797. funcInfo->ReleaseLoc(exprNode);
  6798. funcInfo->ReleaseLoc(nameNode);
  6799. return;
  6800. }
  6801. Js::OpCode stFldOpCode = (Js::OpCode)0;
  6802. if (useStore)
  6803. {
  6804. stFldOpCode = ByteCodeGenerator::GetStFldOpCode(funcInfo, false, false, false, isClassMember);
  6805. }
  6806. Emit(exprNode, byteCodeGenerator, funcInfo, false);
  6807. Js::PropertyId propertyId = nameNode->sxPid.PropertyIdFromNameNode();
  6808. if (Js::PropertyIds::name == propertyId
  6809. && exprNode->nop == knopFncDecl
  6810. && exprNode->sxFnc.IsStaticMember()
  6811. && parentNode != nullptr && parentNode->nop == knopClassDecl
  6812. && parentNode->sxClass.pnodeConstructor != nullptr)
  6813. {
  6814. Js::ParseableFunctionInfo* nameFunc = parentNode->sxClass.pnodeConstructor->sxFnc.funcInfo->byteCodeFunction->GetParseableFunctionInfo();
  6815. nameFunc->SetIsStaticNameFunction(true);
  6816. }
  6817. if (memberNode->nop == knopMember || memberNode->nop == knopMemberShort)
  6818. {
  6819. // The internal prototype should be set only if the production is of the form PropertyDefinition : PropertyName : AssignmentExpression
  6820. if (propertyId == Js::PropertyIds::__proto__ && memberNode->nop != knopMemberShort && (exprNode->nop != knopFncDecl || !exprNode->sxFnc.IsMethod()))
  6821. {
  6822. byteCodeGenerator->Writer()->Property(Js::OpCode::InitProto, exprNode->location, objectLocation,
  6823. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  6824. }
  6825. else
  6826. {
  6827. uint cacheId = funcInfo->FindOrAddInlineCacheId(objectLocation, propertyId, false, true);
  6828. Js::OpCode patchablePropertyOpCode;
  6829. if (useStore)
  6830. {
  6831. patchablePropertyOpCode = stFldOpCode;
  6832. }
  6833. else if (isClassMember)
  6834. {
  6835. patchablePropertyOpCode = Js::OpCode::InitClassMember;
  6836. }
  6837. else
  6838. {
  6839. patchablePropertyOpCode = Js::OpCode::InitFld;
  6840. }
  6841. byteCodeGenerator->Writer()->PatchableProperty(patchablePropertyOpCode, exprNode->location, objectLocation, cacheId);
  6842. }
  6843. }
  6844. else
  6845. {
  6846. Assert(memberNode->nop == knopGetMember || memberNode->nop == knopSetMember);
  6847. Js::OpCode setOp = memberNode->nop == knopGetMember ?
  6848. (isClassMember ? Js::OpCode::InitClassMemberGet : Js::OpCode::InitGetFld) :
  6849. (isClassMember ? Js::OpCode::InitClassMemberSet : Js::OpCode::InitSetFld);
  6850. byteCodeGenerator->Writer()->Property(setOp, exprNode->location, objectLocation, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  6851. }
  6852. // Class and object members need a reference back to the class.
  6853. if (isFncDecl)
  6854. {
  6855. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SetHomeObj, exprNode->location, objectLocation);
  6856. }
  6857. funcInfo->ReleaseLoc(exprNode);
  6858. if (propertyId == Js::PropertyIds::valueOf)
  6859. {
  6860. byteCodeGenerator->GetScriptContext()->optimizationOverrides.SetSideEffects(Js::SideEffects_ValueOf);
  6861. }
  6862. else if (propertyId == Js::PropertyIds::toString)
  6863. {
  6864. byteCodeGenerator->GetScriptContext()->optimizationOverrides.SetSideEffects(Js::SideEffects_ToString);
  6865. }
  6866. }
  6867. void EmitClassInitializers(ParseNode *memberList, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, ParseNode* parentNode, bool isObjectEmpty)
  6868. {
  6869. if (memberList != nullptr)
  6870. {
  6871. while (memberList->nop == knopList)
  6872. {
  6873. ParseNode *memberNode = memberList->sxBin.pnode1;
  6874. EmitMemberNode(memberNode, objectLocation, byteCodeGenerator, funcInfo, parentNode, /*useStore*/ false, &isObjectEmpty);
  6875. memberList = memberList->sxBin.pnode2;
  6876. }
  6877. EmitMemberNode(memberList, objectLocation, byteCodeGenerator, funcInfo, parentNode, /*useStore*/ false, &isObjectEmpty);
  6878. }
  6879. }
  6880. void EmitObjectInitializers(ParseNode *memberList, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  6881. {
  6882. ParseNode *pmemberList = memberList;
  6883. unsigned int argCount = 0;
  6884. uint32 value;
  6885. Js::PropertyId propertyId;
  6886. //
  6887. // 1. Add all non-int property ids to a dictionary propertyIds with value true
  6888. // 2. Get the count of propertyIds
  6889. // 3. Create a propertyId array of size count
  6890. // 4. Put the propIds in the auxiliary area
  6891. // 5. Get the objectLiteralCacheId
  6892. // 6. Generate propId inits with values
  6893. //
  6894. // Handle propertyId collision
  6895. typedef JsUtil::BaseHashSet<Js::PropertyId, ArenaAllocator, PowerOf2SizePolicy> PropertyIdSet;
  6896. PropertyIdSet* propertyIds = Anew(byteCodeGenerator->GetAllocator(), PropertyIdSet, byteCodeGenerator->GetAllocator(), 17);
  6897. bool hasComputedName = false;
  6898. if (memberList != nullptr)
  6899. {
  6900. while (memberList->nop == knopList)
  6901. {
  6902. if (memberList->sxBin.pnode1->sxBin.pnode1->nop == knopComputedName)
  6903. {
  6904. hasComputedName = true;
  6905. break;
  6906. }
  6907. propertyId = memberList->sxBin.pnode1->sxBin.pnode1->sxPid.PropertyIdFromNameNode();
  6908. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value))
  6909. {
  6910. propertyIds->Item(propertyId);
  6911. }
  6912. memberList = memberList->sxBin.pnode2;
  6913. }
  6914. if (memberList->sxBin.pnode1->nop != knopComputedName && !hasComputedName)
  6915. {
  6916. propertyId = memberList->sxBin.pnode1->sxPid.PropertyIdFromNameNode();
  6917. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value))
  6918. {
  6919. propertyIds->Item(propertyId);
  6920. }
  6921. }
  6922. }
  6923. argCount = propertyIds->Count();
  6924. memberList = pmemberList;
  6925. if ((memberList == nullptr) || (argCount == 0))
  6926. {
  6927. // Empty literal or numeric property only object literal
  6928. byteCodeGenerator->Writer()->Reg1(Js::OpCode::NewScObjectSimple, objectLocation);
  6929. }
  6930. else
  6931. {
  6932. Js::PropertyIdArray *propIds = AnewPlus(byteCodeGenerator->GetAllocator(), argCount * sizeof(Js::PropertyId), Js::PropertyIdArray, argCount);
  6933. if (propertyIds->ContainsKey(Js::PropertyIds::__proto__))
  6934. {
  6935. // Always record whether the initializer contains __proto__ no matter if current environment has it enabled
  6936. // or not, in case the bytecode is later run with __proto__ enabled.
  6937. propIds->has__proto__ = true;
  6938. }
  6939. unsigned int argIndex = 0;
  6940. while (memberList->nop == knopList)
  6941. {
  6942. if (memberList->sxBin.pnode1->sxBin.pnode1->nop == knopComputedName)
  6943. {
  6944. break;
  6945. }
  6946. propertyId = memberList->sxBin.pnode1->sxBin.pnode1->sxPid.PropertyIdFromNameNode();
  6947. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value) && propertyIds->Remove(propertyId))
  6948. {
  6949. propIds->elements[argIndex] = propertyId;
  6950. argIndex++;
  6951. }
  6952. memberList = memberList->sxBin.pnode2;
  6953. }
  6954. if (memberList->sxBin.pnode1->nop != knopComputedName && !hasComputedName)
  6955. {
  6956. propertyId = memberList->sxBin.pnode1->sxPid.PropertyIdFromNameNode();
  6957. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value) && propertyIds->Remove(propertyId))
  6958. {
  6959. propIds->elements[argIndex] = propertyId;
  6960. argIndex++;
  6961. }
  6962. }
  6963. uint32 literalObjectId = funcInfo->GetParsedFunctionBody()->NewObjectLiteral();
  6964. // Generate the opcode with propIds and cacheId
  6965. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::NewScObjectLiteral, objectLocation, propIds, sizeof(Js::PropertyIdArray) + argCount * sizeof(Js::PropertyId), literalObjectId);
  6966. Adelete(byteCodeGenerator->GetAllocator(), propertyIds);
  6967. AdeletePlus(byteCodeGenerator->GetAllocator(), argCount * sizeof(Js::PropertyId), propIds);
  6968. }
  6969. memberList = pmemberList;
  6970. bool useStore = false;
  6971. // Generate the actual assignment to those properties
  6972. if (memberList != nullptr)
  6973. {
  6974. while (memberList->nop == knopList)
  6975. {
  6976. ParseNode *memberNode = memberList->sxBin.pnode1;
  6977. if (memberNode->sxBin.pnode1->nop == knopComputedName)
  6978. {
  6979. useStore = true;
  6980. }
  6981. byteCodeGenerator->StartSubexpression(memberNode);
  6982. EmitMemberNode(memberNode, objectLocation, byteCodeGenerator, funcInfo, nullptr, useStore);
  6983. byteCodeGenerator->EndSubexpression(memberNode);
  6984. memberList = memberList->sxBin.pnode2;
  6985. }
  6986. byteCodeGenerator->StartSubexpression(memberList);
  6987. EmitMemberNode(memberList, objectLocation, byteCodeGenerator, funcInfo, nullptr, useStore);
  6988. byteCodeGenerator->EndSubexpression(memberList);
  6989. }
  6990. }
  6991. void EmitStringTemplate(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  6992. {
  6993. Assert(pnode->sxStrTemplate.pnodeStringLiterals);
  6994. // For a tagged string template, we will create the callsite constant object as part of the FunctionBody constants table.
  6995. // We only need to emit code for non-tagged string templates here.
  6996. if (!pnode->sxStrTemplate.isTaggedTemplate)
  6997. {
  6998. // If we have no substitutions and this is not a tagged template, we can emit just the single cooked string.
  6999. if (pnode->sxStrTemplate.pnodeSubstitutionExpressions == nullptr)
  7000. {
  7001. Assert(pnode->sxStrTemplate.pnodeStringLiterals->nop != knopList);
  7002. funcInfo->AcquireLoc(pnode);
  7003. Emit(pnode->sxStrTemplate.pnodeStringLiterals, byteCodeGenerator, funcInfo, false);
  7004. Assert(pnode->location != pnode->sxStrTemplate.pnodeStringLiterals->location);
  7005. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxStrTemplate.pnodeStringLiterals->location);
  7006. funcInfo->ReleaseLoc(pnode->sxStrTemplate.pnodeStringLiterals);
  7007. }
  7008. else
  7009. {
  7010. // If we have substitutions but no tag function, we can skip the callSite object construction (and also ignore raw strings).
  7011. funcInfo->AcquireLoc(pnode);
  7012. // First string must be a list node since we have substitutions.
  7013. AssertMsg(pnode->sxStrTemplate.pnodeStringLiterals->nop == knopList, "First string in the list must be a knopList node.");
  7014. ParseNode* stringNodeList = pnode->sxStrTemplate.pnodeStringLiterals;
  7015. // Emit the first string and load that into the pnode location.
  7016. Emit(stringNodeList->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  7017. Assert(pnode->location != stringNodeList->sxBin.pnode1->location);
  7018. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, stringNodeList->sxBin.pnode1->location);
  7019. funcInfo->ReleaseLoc(stringNodeList->sxBin.pnode1);
  7020. ParseNode* expressionNodeList = pnode->sxStrTemplate.pnodeSubstitutionExpressions;
  7021. ParseNode* stringNode;
  7022. ParseNode* expressionNode;
  7023. // Now append the substitution expressions and remaining string constants via normal add operator
  7024. // We will always have one more string constant than substitution expression
  7025. // `strcon1 ${expr1} strcon2 ${expr2} strcon3` = strcon1 + expr1 + strcon2 + expr2 + strcon3
  7026. //
  7027. // strcon1 --- step 1 (above)
  7028. // expr1 \__ step 2
  7029. // strcon2 /
  7030. // expr2 \__ step 3
  7031. // strcon3 /
  7032. while (stringNodeList->nop == knopList)
  7033. {
  7034. // If the current head of the expression list is a list, fetch the node and walk the list.
  7035. if (expressionNodeList->nop == knopList)
  7036. {
  7037. expressionNode = expressionNodeList->sxBin.pnode1;
  7038. expressionNodeList = expressionNodeList->sxBin.pnode2;
  7039. }
  7040. else
  7041. {
  7042. // This is the last element of the expression list.
  7043. expressionNode = expressionNodeList;
  7044. }
  7045. // Emit the expression and append it to the string we're building.
  7046. Emit(expressionNode, byteCodeGenerator, funcInfo, false);
  7047. Js::RegSlot toStringLocation = funcInfo->AcquireTmpRegister();
  7048. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Str, toStringLocation, expressionNode->location);
  7049. byteCodeGenerator->Writer()->Reg3(Js::OpCode::Add_A, pnode->location, pnode->location, toStringLocation);
  7050. funcInfo->ReleaseTmpRegister(toStringLocation);
  7051. funcInfo->ReleaseLoc(expressionNode);
  7052. // Move to the next string in the list - we already got ahead of the expressions in the first string literal above.
  7053. stringNodeList = stringNodeList->sxBin.pnode2;
  7054. // If the current head of the string literal list is also a list node, need to fetch the actual string literal node.
  7055. if (stringNodeList->nop == knopList)
  7056. {
  7057. stringNode = stringNodeList->sxBin.pnode1;
  7058. }
  7059. else
  7060. {
  7061. // This is the last element of the string literal list.
  7062. stringNode = stringNodeList;
  7063. }
  7064. // Emit the string node following the previous expression and append it to the string.
  7065. // This is either just some string in the list or it is the last string.
  7066. Emit(stringNode, byteCodeGenerator, funcInfo, false);
  7067. byteCodeGenerator->Writer()->Reg3(Js::OpCode::Add_A, pnode->location, pnode->location, stringNode->location);
  7068. funcInfo->ReleaseLoc(stringNode);
  7069. }
  7070. }
  7071. }
  7072. }
  7073. void SetNewArrayElements(ParseNode *pnode, Js::RegSlot arrayLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7074. {
  7075. ParseNode *args = pnode->sxUni.pnode1;
  7076. uint argCount = pnode->sxArrLit.count;
  7077. uint spreadCount = pnode->sxArrLit.spreadCount;
  7078. bool nativeArrays = CreateNativeArrays(byteCodeGenerator, funcInfo);
  7079. bool arrayIntOpt = nativeArrays && pnode->sxArrLit.arrayOfInts;
  7080. if (arrayIntOpt)
  7081. {
  7082. int extraAlloc = argCount * sizeof(int32);
  7083. Js::AuxArray<int> *ints = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<int32>, argCount);
  7084. EmitConstantArgsToIntArray(byteCodeGenerator, ints->elements, args, argCount);
  7085. Assert(!pnode->sxArrLit.hasMissingValues);
  7086. byteCodeGenerator->Writer()->Auxiliary(
  7087. Js::OpCode::NewScIntArray,
  7088. pnode->location,
  7089. ints,
  7090. sizeof(Js::AuxArray<int>) + extraAlloc,
  7091. argCount);
  7092. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, ints);
  7093. return;
  7094. }
  7095. bool arrayNumOpt = nativeArrays && pnode->sxArrLit.arrayOfNumbers;
  7096. if (arrayNumOpt)
  7097. {
  7098. int extraAlloc = argCount * sizeof(double);
  7099. Js::AuxArray<double> *doubles = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<double>, argCount);
  7100. EmitConstantArgsToFltArray(byteCodeGenerator, doubles->elements, args, argCount);
  7101. Assert(!pnode->sxArrLit.hasMissingValues);
  7102. byteCodeGenerator->Writer()->Auxiliary(
  7103. Js::OpCode::NewScFltArray,
  7104. pnode->location,
  7105. doubles,
  7106. sizeof(Js::AuxArray<double>) + extraAlloc,
  7107. argCount);
  7108. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, doubles);
  7109. return;
  7110. }
  7111. bool arrayLitOpt = pnode->sxArrLit.arrayOfTaggedInts && pnode->sxArrLit.count > 1;
  7112. Assert(!arrayLitOpt || !nativeArrays);
  7113. Js::RegSlot spreadArrLoc = arrayLocation;
  7114. Js::AuxArray<uint32> *spreadIndices = nullptr;
  7115. const uint extraAlloc = spreadCount * sizeof(uint32);
  7116. if (pnode->sxArrLit.spreadCount > 0)
  7117. {
  7118. arrayLocation = funcInfo->AcquireTmpRegister();
  7119. spreadIndices = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<uint32>, spreadCount);
  7120. }
  7121. byteCodeGenerator->Writer()->Reg1Unsigned1(
  7122. pnode->sxArrLit.hasMissingValues ? Js::OpCode::NewScArrayWithMissingValues : Js::OpCode::NewScArray,
  7123. arrayLocation,
  7124. argCount);
  7125. if (args != nullptr)
  7126. {
  7127. Js::OpCode opcode;
  7128. Js::RegSlot arrLoc;
  7129. if (argCount == 1 && !byteCodeGenerator->Writer()->DoProfileNewScArrayOp(Js::OpCode::NewScArray))
  7130. {
  7131. opcode = Js::OpCode::StArrItemC_CI4;
  7132. arrLoc = arrayLocation;
  7133. }
  7134. else if (arrayLitOpt)
  7135. {
  7136. opcode = Js::OpCode::StArrSegItem_A;
  7137. arrLoc = funcInfo->AcquireTmpRegister();
  7138. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdArrHead, arrLoc, arrayLocation);
  7139. }
  7140. else if (Js::JavascriptArray::HasInlineHeadSegment(argCount))
  7141. {
  7142. // The head segment will be allocated inline as an interior pointer. To keep the array alive, the set operation
  7143. // should be done relative to the array header to keep it alive (instead of the array segment).
  7144. opcode = Js::OpCode::StArrInlineItem_CI4;
  7145. arrLoc = arrayLocation;
  7146. }
  7147. else if (argCount <= Js::JavascriptArray::MaxInitialDenseLength)
  7148. {
  7149. opcode = Js::OpCode::StArrSegItem_CI4;
  7150. arrLoc = funcInfo->AcquireTmpRegister();
  7151. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdArrHead, arrLoc, arrayLocation);
  7152. }
  7153. else
  7154. {
  7155. opcode = Js::OpCode::StArrItemI_CI4;
  7156. arrLoc = arrayLocation;
  7157. }
  7158. if (arrayLitOpt)
  7159. {
  7160. Js::VarArray *vars = AnewPlus(byteCodeGenerator->GetAllocator(), argCount * sizeof(Js::Var), Js::VarArray, argCount);
  7161. EmitConstantArgsToVarArray(byteCodeGenerator, vars->elements, args, argCount);
  7162. // Generate the opcode with vars
  7163. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::StArrSegItem_A, arrLoc, vars, sizeof(Js::VarArray) + argCount * sizeof(Js::Var), argCount);
  7164. AdeletePlus(byteCodeGenerator->GetAllocator(), argCount * sizeof(Js::Var), vars);
  7165. }
  7166. else
  7167. {
  7168. uint i = 0;
  7169. unsigned spreadIndex = 0;
  7170. Js::RegSlot rhsLocation;
  7171. while (args->nop == knopList)
  7172. {
  7173. if (args->sxBin.pnode1->nop != knopEmpty)
  7174. {
  7175. Emit(args->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  7176. rhsLocation = args->sxBin.pnode1->location;
  7177. Js::RegSlot regVal = rhsLocation;
  7178. if (args->sxBin.pnode1->nop == knopEllipsis)
  7179. {
  7180. AnalysisAssert(spreadIndices);
  7181. regVal = funcInfo->AcquireTmpRegister();
  7182. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, rhsLocation);
  7183. spreadIndices->elements[spreadIndex++] = i;
  7184. }
  7185. byteCodeGenerator->Writer()->ElementUnsigned1(opcode, regVal, arrLoc, i);
  7186. if (args->sxBin.pnode1->nop == knopEllipsis)
  7187. {
  7188. funcInfo->ReleaseTmpRegister(regVal);
  7189. }
  7190. funcInfo->ReleaseLoc(args->sxBin.pnode1);
  7191. }
  7192. args = args->sxBin.pnode2;
  7193. i++;
  7194. }
  7195. if (args->nop != knopEmpty)
  7196. {
  7197. Emit(args, byteCodeGenerator, funcInfo, false);
  7198. rhsLocation = args->location;
  7199. Js::RegSlot regVal = rhsLocation;
  7200. if (args->nop == knopEllipsis)
  7201. {
  7202. regVal = funcInfo->AcquireTmpRegister();
  7203. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, rhsLocation);
  7204. AnalysisAssert(spreadIndices);
  7205. spreadIndices->elements[spreadIndex] = i;
  7206. }
  7207. byteCodeGenerator->Writer()->ElementUnsigned1(opcode, regVal, arrLoc, i);
  7208. if (args->nop == knopEllipsis)
  7209. {
  7210. funcInfo->ReleaseTmpRegister(regVal);
  7211. }
  7212. funcInfo->ReleaseLoc(args);
  7213. i++;
  7214. }
  7215. Assert(i <= argCount);
  7216. }
  7217. if (arrLoc != arrayLocation)
  7218. {
  7219. funcInfo->ReleaseTmpRegister(arrLoc);
  7220. }
  7221. }
  7222. if (pnode->sxArrLit.spreadCount > 0)
  7223. {
  7224. byteCodeGenerator->Writer()->Reg2Aux(Js::OpCode::SpreadArrayLiteral, spreadArrLoc, arrayLocation, spreadIndices, sizeof(Js::AuxArray<uint32>) + extraAlloc, extraAlloc);
  7225. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, spreadIndices);
  7226. funcInfo->ReleaseTmpRegister(arrayLocation);
  7227. }
  7228. }
  7229. // FIX: TODO: mixed-mode expressions (arithmetic expressions mixed with boolean expressions); current solution
  7230. // will not short-circuit in some cases and is not complete (for example: var i=(x==y))
  7231. // This uses Aho and Ullman style double-branch generation (p. 494 ASU); we will need to peephole optimize or replace
  7232. // with special case for single-branch style.
  7233. void EmitBooleanExpression(ParseNode *expr, Js::ByteCodeLabel trueLabel, Js::ByteCodeLabel falseLabel, ByteCodeGenerator *byteCodeGenerator,
  7234. FuncInfo *funcInfo)
  7235. {
  7236. switch (expr->nop)
  7237. {
  7238. case knopLogOr:
  7239. {
  7240. byteCodeGenerator->StartStatement(expr);
  7241. Js::ByteCodeLabel leftFalse = byteCodeGenerator->Writer()->DefineLabel();
  7242. EmitBooleanExpression(expr->sxBin.pnode1, trueLabel, leftFalse, byteCodeGenerator, funcInfo);
  7243. funcInfo->ReleaseLoc(expr->sxBin.pnode1);
  7244. byteCodeGenerator->Writer()->MarkLabel(leftFalse);
  7245. EmitBooleanExpression(expr->sxBin.pnode2, trueLabel, falseLabel, byteCodeGenerator, funcInfo);
  7246. funcInfo->ReleaseLoc(expr->sxBin.pnode2);
  7247. byteCodeGenerator->EndStatement(expr);
  7248. break;
  7249. }
  7250. case knopLogAnd:
  7251. {
  7252. byteCodeGenerator->StartStatement(expr);
  7253. Js::ByteCodeLabel leftTrue = byteCodeGenerator->Writer()->DefineLabel();
  7254. EmitBooleanExpression(expr->sxBin.pnode1, leftTrue, falseLabel, byteCodeGenerator, funcInfo);
  7255. funcInfo->ReleaseLoc(expr->sxBin.pnode1);
  7256. byteCodeGenerator->Writer()->MarkLabel(leftTrue);
  7257. EmitBooleanExpression(expr->sxBin.pnode2, trueLabel, falseLabel, byteCodeGenerator, funcInfo);
  7258. funcInfo->ReleaseLoc(expr->sxBin.pnode2);
  7259. byteCodeGenerator->EndStatement(expr);
  7260. break;
  7261. }
  7262. case knopLogNot:
  7263. byteCodeGenerator->StartStatement(expr);
  7264. EmitBooleanExpression(expr->sxUni.pnode1, falseLabel, trueLabel, byteCodeGenerator, funcInfo);
  7265. funcInfo->ReleaseLoc(expr->sxUni.pnode1);
  7266. byteCodeGenerator->EndStatement(expr);
  7267. break;
  7268. case knopEq:
  7269. case knopEqv:
  7270. case knopNEqv:
  7271. case knopNe:
  7272. case knopLt:
  7273. case knopLe:
  7274. case knopGe:
  7275. case knopGt:
  7276. byteCodeGenerator->StartStatement(expr);
  7277. EmitBinaryOpnds(expr->sxBin.pnode1, expr->sxBin.pnode2, byteCodeGenerator, funcInfo);
  7278. funcInfo->ReleaseLoc(expr->sxBin.pnode2);
  7279. funcInfo->ReleaseLoc(expr->sxBin.pnode1);
  7280. byteCodeGenerator->Writer()->BrReg2(nopToOp[expr->nop], trueLabel, expr->sxBin.pnode1->location,
  7281. expr->sxBin.pnode2->location);
  7282. byteCodeGenerator->Writer()->Br(falseLabel);
  7283. byteCodeGenerator->EndStatement(expr);
  7284. break;
  7285. case knopTrue:
  7286. byteCodeGenerator->StartStatement(expr);
  7287. byteCodeGenerator->Writer()->Br(trueLabel);
  7288. byteCodeGenerator->EndStatement(expr);
  7289. break;
  7290. case knopFalse:
  7291. byteCodeGenerator->StartStatement(expr);
  7292. byteCodeGenerator->Writer()->Br(falseLabel);
  7293. byteCodeGenerator->EndStatement(expr);
  7294. break;
  7295. default:
  7296. // Note: we usually release the temp assigned to a node after we Emit it.
  7297. // But in this case, EmitBooleanExpression is just a wrapper around a normal Emit call,
  7298. // and the caller of EmitBooleanExpression expects to be able to release this register.
  7299. // For diagnostics purposes, register the name and dot to the statement list.
  7300. if (expr->nop == knopName || expr->nop == knopDot)
  7301. {
  7302. byteCodeGenerator->StartStatement(expr);
  7303. Emit(expr, byteCodeGenerator, funcInfo, false);
  7304. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7305. byteCodeGenerator->Writer()->Br(falseLabel);
  7306. byteCodeGenerator->EndStatement(expr);
  7307. }
  7308. else
  7309. {
  7310. Emit(expr, byteCodeGenerator, funcInfo, false);
  7311. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7312. byteCodeGenerator->Writer()->Br(falseLabel);
  7313. }
  7314. break;
  7315. }
  7316. }
  7317. // used by while and for loops
  7318. void EmitLoop(
  7319. ParseNode *loopNode,
  7320. ParseNode *cond,
  7321. ParseNode *body,
  7322. ParseNode *incr,
  7323. ByteCodeGenerator *byteCodeGenerator,
  7324. FuncInfo *funcInfo,
  7325. BOOL fReturnValue,
  7326. BOOL doWhile = FALSE,
  7327. ParseNode *forLoopBlock = nullptr)
  7328. {
  7329. // Need to increment loop count whether we are going to profile or not for HasLoop()
  7330. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  7331. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  7332. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  7333. loopNode->sxLoop.loopId = loopId;
  7334. if (doWhile)
  7335. {
  7336. Emit(body, byteCodeGenerator, funcInfo, fReturnValue);
  7337. funcInfo->ReleaseLoc(body);
  7338. if (loopNode->emitLabels)
  7339. {
  7340. byteCodeGenerator->Writer()->MarkLabel(loopNode->sxStmt.continueLabel);
  7341. }
  7342. if (!ByteCodeGenerator::IsFalse(cond) ||
  7343. byteCodeGenerator->IsInDebugMode())
  7344. {
  7345. EmitBooleanExpression(cond, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo);
  7346. }
  7347. funcInfo->ReleaseLoc(cond);
  7348. }
  7349. else
  7350. {
  7351. if (cond)
  7352. {
  7353. if (!(cond->nop == knopInt &&
  7354. cond->sxInt.lw != 0))
  7355. {
  7356. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  7357. EmitBooleanExpression(cond, trueLabel, continuePastLoop, byteCodeGenerator, funcInfo);
  7358. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  7359. }
  7360. funcInfo->ReleaseLoc(cond);
  7361. }
  7362. Emit(body, byteCodeGenerator, funcInfo, fReturnValue);
  7363. funcInfo->ReleaseLoc(body);
  7364. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled() &&
  7365. forLoopBlock != nullptr)
  7366. {
  7367. CloneEmitBlock(forLoopBlock, byteCodeGenerator, funcInfo);
  7368. }
  7369. if (loopNode->emitLabels)
  7370. {
  7371. byteCodeGenerator->Writer()->MarkLabel(loopNode->sxStmt.continueLabel);
  7372. }
  7373. if (incr != nullptr)
  7374. {
  7375. Emit(incr, byteCodeGenerator, funcInfo, false);
  7376. funcInfo->ReleaseLoc(incr);
  7377. }
  7378. byteCodeGenerator->Writer()->Br(loopEntrance);
  7379. }
  7380. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  7381. if (loopNode->emitLabels)
  7382. {
  7383. byteCodeGenerator->Writer()->MarkLabel(loopNode->sxStmt.breakLabel);
  7384. }
  7385. byteCodeGenerator->Writer()->ExitLoop(loopId);
  7386. }
  7387. void ByteCodeGenerator::EmitInvertedLoop(ParseNode* outerLoop, ParseNode* invertedLoop, FuncInfo* funcInfo)
  7388. {
  7389. Js::ByteCodeLabel invertedLoopLabel = this->m_writer.DefineLabel();
  7390. Js::ByteCodeLabel afterInvertedLoop = this->m_writer.DefineLabel();
  7391. // emit branch around original
  7392. Emit(outerLoop->sxFor.pnodeInit, this, funcInfo, false);
  7393. funcInfo->ReleaseLoc(outerLoop->sxFor.pnodeInit);
  7394. this->m_writer.BrS(Js::OpCode::BrNotHasSideEffects, invertedLoopLabel, Js::SideEffects_Any);
  7395. // emit original
  7396. EmitLoop(outerLoop, outerLoop->sxFor.pnodeCond, outerLoop->sxFor.pnodeBody,
  7397. outerLoop->sxFor.pnodeIncr, this, funcInfo, false);
  7398. // clear temporary registers since inverted loop may share nodes with
  7399. // emitted original loop
  7400. VisitClearTmpRegs(outerLoop, this, funcInfo);
  7401. // emit branch around inverted
  7402. this->m_writer.Br(afterInvertedLoop);
  7403. this->m_writer.MarkLabel(invertedLoopLabel);
  7404. // Emit a zero trip test for the original outer-loop
  7405. Js::ByteCodeLabel zeroTrip = this->m_writer.DefineLabel();
  7406. ParseNode* testNode = this->GetParser()->CopyPnode(outerLoop->sxFor.pnodeCond);
  7407. EmitBooleanExpression(testNode, zeroTrip, afterInvertedLoop, this, funcInfo);
  7408. this->m_writer.MarkLabel(zeroTrip);
  7409. funcInfo->ReleaseLoc(testNode);
  7410. // emit inverted
  7411. Emit(invertedLoop->sxFor.pnodeInit, this, funcInfo, false);
  7412. funcInfo->ReleaseLoc(invertedLoop->sxFor.pnodeInit);
  7413. EmitLoop(invertedLoop, invertedLoop->sxFor.pnodeCond, invertedLoop->sxFor.pnodeBody,
  7414. invertedLoop->sxFor.pnodeIncr, this, funcInfo, false);
  7415. this->m_writer.MarkLabel(afterInvertedLoop);
  7416. }
  7417. void EmitGetIterator(Js::RegSlot iteratorLocation, Js::RegSlot iterableLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  7418. {
  7419. // get iterator object from the iterable
  7420. EmitInvoke(iteratorLocation, iterableLocation, Js::PropertyIds::_symbolIterator, byteCodeGenerator, funcInfo);
  7421. // throw TypeError if the result is not an object
  7422. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  7423. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, skipThrow, iteratorLocation);
  7424. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_NeedObject));
  7425. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  7426. }
  7427. void EmitIteratorNext(Js::RegSlot itemLocation, Js::RegSlot iteratorLocation, Js::RegSlot nextInputLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  7428. {
  7429. // invoke next() on the iterator
  7430. if (nextInputLocation == Js::Constants::NoRegister)
  7431. {
  7432. EmitInvoke(itemLocation, iteratorLocation, Js::PropertyIds::next, byteCodeGenerator, funcInfo);
  7433. }
  7434. else
  7435. {
  7436. EmitInvoke(itemLocation, iteratorLocation, Js::PropertyIds::next, byteCodeGenerator, funcInfo, nextInputLocation);
  7437. }
  7438. // throw TypeError if the result is not an object
  7439. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  7440. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, skipThrow, itemLocation);
  7441. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_NeedObject));
  7442. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  7443. }
  7444. void EmitIteratorComplete(Js::RegSlot doneLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  7445. {
  7446. // get the iterator result's "done" property
  7447. uint cacheId = funcInfo->FindOrAddInlineCacheId(iteratorResultLocation, Js::PropertyIds::done, false, false);
  7448. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, doneLocation, iteratorResultLocation, cacheId);
  7449. // Do not need to do ToBoolean explicitly with current uses of EmitIteratorComplete since BrTrue_A does this.
  7450. // Add a ToBoolean controlled by template flag if needed for new uses later on.
  7451. }
  7452. void EmitIteratorValue(Js::RegSlot valueLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  7453. {
  7454. // get the iterator result's "value" property
  7455. uint cacheId = funcInfo->FindOrAddInlineCacheId(iteratorResultLocation, Js::PropertyIds::value, false, false);
  7456. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, valueLocation, iteratorResultLocation, cacheId);
  7457. }
  7458. void EmitForInOrForOf(ParseNode *loopNode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue)
  7459. {
  7460. bool isForIn = (loopNode->nop == knopForIn);
  7461. Assert(isForIn || loopNode->nop == knopForOf);
  7462. BeginEmitBlock(loopNode->sxForInOrForOf.pnodeBlock, byteCodeGenerator, funcInfo);
  7463. byteCodeGenerator->StartStatement(loopNode);
  7464. funcInfo->AcquireLoc(loopNode);
  7465. // Record the branch bytecode offset.
  7466. // This is used for "ignore exception" and "set next stmt" scenarios. See ProbeContainer::GetNextUserStatementOffsetForAdvance:
  7467. // If there is a branch recorded between current offset and next stmt offset, we'll use offset of the branch recorded,
  7468. // otherwise use offset of next stmt.
  7469. // The idea here is that when we bail out after ignore exception, we need to bail out to the beginning of the ForIn,
  7470. // but currently ForIn stmt starts at the condition part, which is needed for correct handling of break point on ForIn
  7471. // (break every time on the loop back edge) and correct display of current statement under debugger.
  7472. // See WinBlue 231880 for details.
  7473. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_All);
  7474. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled() &&
  7475. loopNode->sxForInOrForOf.pnodeBlock->sxBlock.HasBlockScopedContent())
  7476. {
  7477. byteCodeGenerator->Writer()->RecordForInOrOfCollectionScope();
  7478. }
  7479. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  7480. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  7481. Js::ByteCodeLabel skipPastLoop = byteCodeGenerator->Writer()->DefineLabel();
  7482. if (loopNode->sxForInOrForOf.pnodeLval->nop == knopVarDecl)
  7483. {
  7484. EmitReference(loopNode->sxForInOrForOf.pnodeLval, byteCodeGenerator, funcInfo);
  7485. }
  7486. Emit(loopNode->sxForInOrForOf.pnodeObj, byteCodeGenerator, funcInfo, false); // evaluate collection expression
  7487. funcInfo->ReleaseLoc(loopNode->sxForInOrForOf.pnodeObj);
  7488. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  7489. {
  7490. EndEmitBlock(loopNode->sxForInOrForOf.pnodeBlock, byteCodeGenerator, funcInfo);
  7491. if (loopNode->sxForInOrForOf.pnodeBlock->sxBlock.scope != nullptr)
  7492. {
  7493. loopNode->sxForInOrForOf.pnodeBlock->sxBlock.scope->ForEachSymbol([](Symbol *sym) {
  7494. sym->SetIsTrackedForDebugger(false);
  7495. });
  7496. }
  7497. }
  7498. // Grab registers for the enumerator and for the current enumerated item.
  7499. // The enumerator register will be released after this call returns.
  7500. loopNode->sxForInOrForOf.itemLocation = funcInfo->AcquireTmpRegister();
  7501. if (isForIn)
  7502. {
  7503. // get enumerator from the collection
  7504. byteCodeGenerator->Writer()->Reg2(Js::OpCode::GetForInEnumerator, loopNode->location, loopNode->sxForInOrForOf.pnodeObj->location);
  7505. }
  7506. else
  7507. {
  7508. // We want call profile information on the @@iterator call, so instead of adding a GetForOfIterator bytecode op
  7509. // to do all the following work in a helper do it explicitly in bytecode so that the @@iterator call is exposed
  7510. // to the profiler and JIT.
  7511. // If collection is null or undefined, don't enter the loop.
  7512. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, skipPastLoop, loopNode->sxForInOrForOf.pnodeObj->location, funcInfo->nullConstantRegister);
  7513. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, skipPastLoop, loopNode->sxForInOrForOf.pnodeObj->location, funcInfo->undefinedConstantRegister);
  7514. // do a ToObject on the collection
  7515. Js::RegSlot tmpObj = funcInfo->AcquireTmpRegister();
  7516. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Obj, tmpObj, loopNode->sxForInOrForOf.pnodeObj->location);
  7517. EmitGetIterator(loopNode->location, tmpObj, byteCodeGenerator, funcInfo);
  7518. funcInfo->ReleaseTmpRegister(tmpObj);
  7519. }
  7520. byteCodeGenerator->EndStatement(loopNode);
  7521. // Need to increment loop count whether we are going into profile or not for HasLoop()
  7522. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  7523. loopNode->sxForInOrForOf.loopId = loopId;
  7524. byteCodeGenerator->StartStatement(loopNode->sxForInOrForOf.pnodeLval);
  7525. if (isForIn)
  7526. {
  7527. // branch past loop when GetCurrentAndMoveNext returns nullptr
  7528. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrOnEmpty, continuePastLoop, loopNode->sxForInOrForOf.itemLocation, loopNode->location);
  7529. }
  7530. else
  7531. {
  7532. EmitIteratorNext(loopNode->sxForInOrForOf.itemLocation, loopNode->location, Js::Constants::NoRegister, byteCodeGenerator, funcInfo);
  7533. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  7534. EmitIteratorComplete(doneLocation, loopNode->sxForInOrForOf.itemLocation, byteCodeGenerator, funcInfo);
  7535. // branch past loop if the result's done property is truthy
  7536. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, continuePastLoop, doneLocation);
  7537. funcInfo->ReleaseTmpRegister(doneLocation);
  7538. // otherwise put result's value property in itemLocation
  7539. EmitIteratorValue(loopNode->sxForInOrForOf.itemLocation, loopNode->sxForInOrForOf.itemLocation, byteCodeGenerator, funcInfo);
  7540. }
  7541. if (loopNode->sxForInOrForOf.pnodeLval->nop != knopVarDecl &&
  7542. loopNode->sxForInOrForOf.pnodeLval->nop != knopLetDecl)
  7543. {
  7544. EmitReference(loopNode->sxForInOrForOf.pnodeLval, byteCodeGenerator, funcInfo);
  7545. }
  7546. else
  7547. {
  7548. Symbol * sym = loopNode->sxForInOrForOf.pnodeLval->sxVar.sym;
  7549. sym->SetNeedDeclaration(false);
  7550. }
  7551. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  7552. {
  7553. BeginEmitBlock(loopNode->sxForInOrForOf.pnodeBlock, byteCodeGenerator, funcInfo);
  7554. }
  7555. EmitAssignment(nullptr, loopNode->sxForInOrForOf.pnodeLval, loopNode->sxForInOrForOf.itemLocation, byteCodeGenerator, funcInfo);
  7556. byteCodeGenerator->EndStatement(loopNode->sxForInOrForOf.pnodeLval);
  7557. funcInfo->ReleaseReference(loopNode->sxForInOrForOf.pnodeLval);
  7558. Emit(loopNode->sxForInOrForOf.pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  7559. funcInfo->ReleaseLoc(loopNode->sxForInOrForOf.pnodeBody);
  7560. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  7561. {
  7562. EndEmitBlock(loopNode->sxForInOrForOf.pnodeBlock, byteCodeGenerator, funcInfo);
  7563. }
  7564. funcInfo->ReleaseTmpRegister(loopNode->sxForInOrForOf.itemLocation);
  7565. if (loopNode->emitLabels)
  7566. {
  7567. byteCodeGenerator->Writer()->MarkLabel(loopNode->sxForInOrForOf.continueLabel);
  7568. }
  7569. byteCodeGenerator->Writer()->Br(loopEntrance);
  7570. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  7571. if (loopNode->emitLabels)
  7572. {
  7573. byteCodeGenerator->Writer()->MarkLabel(loopNode->sxForInOrForOf.breakLabel);
  7574. }
  7575. byteCodeGenerator->Writer()->ExitLoop(loopId);
  7576. if (isForIn)
  7577. {
  7578. byteCodeGenerator->Writer()->Reg1(Js::OpCode::ReleaseForInEnumerator, loopNode->location);
  7579. }
  7580. else
  7581. {
  7582. byteCodeGenerator->Writer()->MarkLabel(skipPastLoop);
  7583. }
  7584. if (!byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  7585. {
  7586. EndEmitBlock(loopNode->sxForInOrForOf.pnodeBlock, byteCodeGenerator, funcInfo);
  7587. }
  7588. }
  7589. void EmitArrayLiteral(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7590. {
  7591. funcInfo->AcquireLoc(pnode);
  7592. ParseNode *args = pnode->sxUni.pnode1;
  7593. if (args == nullptr)
  7594. {
  7595. byteCodeGenerator->Writer()->Reg1Unsigned1(
  7596. pnode->sxArrLit.hasMissingValues ? Js::OpCode::NewScArrayWithMissingValues : Js::OpCode::NewScArray,
  7597. pnode->location,
  7598. ByteCodeGenerator::DefaultArraySize);
  7599. }
  7600. else
  7601. {
  7602. SetNewArrayElements(pnode, pnode->location, byteCodeGenerator, funcInfo);
  7603. }
  7604. }
  7605. void EmitJumpCleanup(ParseNode *pnode, ParseNode *pnodeTarget, ByteCodeGenerator *byteCodeGenerator, FuncInfo * funcInfo)
  7606. {
  7607. for (; pnode != pnodeTarget; pnode = pnode->sxStmt.pnodeOuter)
  7608. {
  7609. switch (pnode->nop)
  7610. {
  7611. case knopTry:
  7612. case knopCatch:
  7613. case knopFinally:
  7614. // We insert OpCode::Leave when there is a 'return' inside try/catch/finally.
  7615. // This is for flow control and does not participate in identifying boundaries of try/catch blocks,
  7616. // thus we shouldn't call RecordCrossFrameEntryExitRecord() here.
  7617. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  7618. break;
  7619. #if ENABLE_PROFILE_INFO
  7620. case knopWhile:
  7621. case knopDoWhile:
  7622. case knopFor:
  7623. case knopForIn:
  7624. case knopForOf:
  7625. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(funcInfo->GetParsedFunctionBody()))
  7626. {
  7627. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::ProfiledLoopEnd, pnode->sxLoop.loopId);
  7628. }
  7629. #endif
  7630. }
  7631. }
  7632. }
  7633. void EmitBinaryOpnds(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7634. {
  7635. // If opnd2 can overwrite opnd1, make sure the value of opnd1 is stashed away.
  7636. if (MayHaveSideEffectOnNode(pnode1, pnode2))
  7637. {
  7638. SaveOpndValue(pnode1, funcInfo);
  7639. }
  7640. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  7641. if (pnode1->nop == knopComputedName && pnode2->nop == knopClassDecl &&
  7642. (pnode2->sxClass.pnodeConstructor == nullptr || pnode2->sxClass.pnodeConstructor->nop != knopVarDecl))
  7643. {
  7644. Emit(pnode2, byteCodeGenerator, funcInfo, false, false, pnode1);
  7645. }
  7646. else
  7647. {
  7648. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  7649. }
  7650. }
  7651. void EmitBinaryReference(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fLoadLhs)
  7652. {
  7653. // Make sure that the RHS of an assignment doesn't kill the opnd's of the expression on the LHS.
  7654. switch (pnode1->nop)
  7655. {
  7656. case knopName:
  7657. if (fLoadLhs && MayHaveSideEffectOnNode(pnode1, pnode2))
  7658. {
  7659. // Given x op y, y may kill x, so stash x.
  7660. // Note that this only matters if we're loading x prior to the op.
  7661. SaveOpndValue(pnode1, funcInfo);
  7662. }
  7663. break;
  7664. case knopDot:
  7665. if (fLoadLhs)
  7666. {
  7667. // We're loading the value of the LHS before the RHS, so make sure the LHS gets a register first.
  7668. funcInfo->AcquireLoc(pnode1);
  7669. }
  7670. if (MayHaveSideEffectOnNode(pnode1->sxBin.pnode1, pnode2))
  7671. {
  7672. // Given x.y op z, z may kill x, so stash x away.
  7673. SaveOpndValue(pnode1->sxBin.pnode1, funcInfo);
  7674. }
  7675. break;
  7676. case knopIndex:
  7677. if (fLoadLhs)
  7678. {
  7679. // We're loading the value of the LHS before the RHS, so make sure the LHS gets a register first.
  7680. funcInfo->AcquireLoc(pnode1);
  7681. }
  7682. if (MayHaveSideEffectOnNode(pnode1->sxBin.pnode1, pnode2) ||
  7683. MayHaveSideEffectOnNode(pnode1->sxBin.pnode1, pnode1->sxBin.pnode2))
  7684. {
  7685. // Given x[y] op z, y or z may kill x, so stash x away.
  7686. SaveOpndValue(pnode1->sxBin.pnode1, funcInfo);
  7687. }
  7688. if (MayHaveSideEffectOnNode(pnode1->sxBin.pnode2, pnode2))
  7689. {
  7690. // Given x[y] op z, z may kill y, so stash y away.
  7691. // But make sure that x gets a register before y.
  7692. funcInfo->AcquireLoc(pnode1->sxBin.pnode1);
  7693. SaveOpndValue(pnode1->sxBin.pnode2, funcInfo);
  7694. }
  7695. break;
  7696. }
  7697. if (fLoadLhs)
  7698. {
  7699. // Emit code to load the value of the LHS.
  7700. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  7701. }
  7702. else
  7703. {
  7704. // Emit code to evaluate the LHS opnds, but don't load the LHS's value.
  7705. EmitReference(pnode1, byteCodeGenerator, funcInfo);
  7706. }
  7707. // Evaluate the RHS.
  7708. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  7709. }
  7710. void EmitUseBeforeDeclarationRuntimeError(ByteCodeGenerator * byteCodeGenerator, Js::RegSlot location, bool fLoadUndef)
  7711. {
  7712. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_UseBeforeDeclaration));
  7713. // Load something into register in order to do not confuse IRBuilder. This value will never be used.
  7714. if (fLoadUndef)
  7715. {
  7716. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, location);
  7717. }
  7718. }
  7719. bool EmitUseBeforeDeclaration(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7720. {
  7721. Symbol *sym = nullptr;
  7722. bool fAcquireLoc = true;
  7723. if (pnode->nop == knopName)
  7724. {
  7725. sym = pnode->sxPid.sym;
  7726. }
  7727. else if (pnode->nop == knopVarDecl)
  7728. {
  7729. fAcquireLoc = false;
  7730. sym = pnode->sxVar.sym;
  7731. }
  7732. else if ((ParseNode::Grfnop(pnode->nop) & fnopAsg) != 0)
  7733. {
  7734. if ((ParseNode::Grfnop(pnode->nop) & fnopBin) != 0 && pnode->sxBin.pnode1->nop == knopName)
  7735. {
  7736. sym = pnode->sxBin.pnode1->sxPid.sym;
  7737. }
  7738. if ((ParseNode::Grfnop(pnode->nop) & fnopUni) != 0 && pnode->sxUni.pnode1->nop == knopName)
  7739. {
  7740. sym = pnode->sxUni.pnode1->sxPid.sym;
  7741. }
  7742. }
  7743. // Don't emit static use-before-declaration error in a closure or dynamic scope case. We detect such cases with dynamic checks,
  7744. // if necessary.
  7745. if (sym != nullptr && !sym->GetIsModuleExportStorage() && sym->GetNeedDeclaration() && byteCodeGenerator->GetCurrentScope()->HasStaticPathToAncestor(sym->GetScope()) && sym->GetScope()->GetFunc() == funcInfo)
  7746. {
  7747. if (fAcquireLoc)
  7748. {
  7749. funcInfo->AcquireLoc(pnode);
  7750. }
  7751. EmitUseBeforeDeclarationRuntimeError(byteCodeGenerator, pnode->location, fAcquireLoc);
  7752. return true;
  7753. }
  7754. return false;
  7755. }
  7756. void EmitBinary(Js::OpCode opcode, ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7757. {
  7758. byteCodeGenerator->StartStatement(pnode);
  7759. EmitBinaryOpnds(pnode->sxBin.pnode1, pnode->sxBin.pnode2, byteCodeGenerator, funcInfo);
  7760. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  7761. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  7762. funcInfo->AcquireLoc(pnode);
  7763. byteCodeGenerator->Writer()->Reg3(opcode,
  7764. pnode->location,
  7765. pnode->sxBin.pnode1->location,
  7766. pnode->sxBin.pnode2->location);
  7767. byteCodeGenerator->EndStatement(pnode);
  7768. }
  7769. bool CollectConcat(ParseNode *pnodeAdd, DListCounted<ParseNode *, ArenaAllocator>& concatOpnds, ArenaAllocator *arenaAllocator)
  7770. {
  7771. Assert(pnodeAdd->nop == knopAdd);
  7772. Assert(pnodeAdd->CanFlattenConcatExpr());
  7773. bool doConcatString = false;
  7774. DList<ParseNode*, ArenaAllocator> pnodeStack(arenaAllocator);
  7775. pnodeStack.Prepend(pnodeAdd->sxBin.pnode2);
  7776. ParseNode * pnode = pnodeAdd->sxBin.pnode1;
  7777. while (true)
  7778. {
  7779. if (!pnode->CanFlattenConcatExpr())
  7780. {
  7781. concatOpnds.Append(pnode);
  7782. }
  7783. else if (pnode->nop == knopStr)
  7784. {
  7785. concatOpnds.Append(pnode);
  7786. // Detect if there are any string larger then the append size limit.
  7787. // If there are, we can do concat; otherwise, still use add so we will not lose the AddLeftDead opportunities.
  7788. doConcatString = doConcatString || !Js::CompoundString::ShouldAppendChars(pnode->sxPid.pid->Cch());
  7789. }
  7790. else
  7791. {
  7792. Assert(pnode->nop == knopAdd);
  7793. pnodeStack.Prepend(pnode->sxBin.pnode2);
  7794. pnode = pnode->sxBin.pnode1;
  7795. continue;
  7796. }
  7797. if (pnodeStack.Empty())
  7798. {
  7799. break;
  7800. }
  7801. pnode = pnodeStack.Head();
  7802. pnodeStack.RemoveHead();
  7803. }
  7804. return doConcatString;
  7805. }
  7806. void EmitConcat3(ParseNode *pnode, ParseNode *pnode1, ParseNode *pnode2, ParseNode *pnode3, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7807. {
  7808. byteCodeGenerator->StartStatement(pnode);
  7809. if (MayHaveSideEffectOnNode(pnode1, pnode2) || MayHaveSideEffectOnNode(pnode1, pnode3))
  7810. {
  7811. SaveOpndValue(pnode1, funcInfo);
  7812. }
  7813. if (MayHaveSideEffectOnNode(pnode2, pnode3))
  7814. {
  7815. SaveOpndValue(pnode2, funcInfo);
  7816. }
  7817. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  7818. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  7819. Emit(pnode3, byteCodeGenerator, funcInfo, false);
  7820. funcInfo->ReleaseLoc(pnode3);
  7821. funcInfo->ReleaseLoc(pnode2);
  7822. funcInfo->ReleaseLoc(pnode1);
  7823. funcInfo->AcquireLoc(pnode);
  7824. byteCodeGenerator->Writer()->Reg4(Js::OpCode::Concat3,
  7825. pnode->location,
  7826. pnode1->location,
  7827. pnode2->location,
  7828. pnode3->location);
  7829. byteCodeGenerator->EndStatement(pnode);
  7830. }
  7831. void EmitNewConcatStrMulti(ParseNode *pnode, uint8 count, ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7832. {
  7833. EmitBinaryOpnds(pnode1, pnode2, byteCodeGenerator, funcInfo);
  7834. funcInfo->ReleaseLoc(pnode2);
  7835. funcInfo->ReleaseLoc(pnode1);
  7836. funcInfo->AcquireLoc(pnode);
  7837. byteCodeGenerator->Writer()->Reg3B1(Js::OpCode::NewConcatStrMulti,
  7838. pnode->location,
  7839. pnode1->location,
  7840. pnode2->location,
  7841. count);
  7842. }
  7843. void EmitAdd(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7844. {
  7845. Assert(pnode->nop == knopAdd);
  7846. if (pnode->CanFlattenConcatExpr())
  7847. {
  7848. // We should only have a string concat if the feature is on.
  7849. Assert(!PHASE_OFF1(Js::ByteCodeConcatExprOptPhase));
  7850. DListCounted<ParseNode*, ArenaAllocator> concatOpnds(byteCodeGenerator->GetAllocator());
  7851. bool doConcatString = CollectConcat(pnode, concatOpnds, byteCodeGenerator->GetAllocator());
  7852. if (doConcatString)
  7853. {
  7854. uint concatCount = concatOpnds.Count();
  7855. Assert(concatCount >= 2);
  7856. // Don't do concatN if the number is too high
  7857. // CONSIDER: although we could have done multiple ConcatNs
  7858. if (concatCount > 2 && concatCount <= UINT8_MAX)
  7859. {
  7860. #if DBG
  7861. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  7862. #endif
  7863. ParseNode * pnode1 = concatOpnds.Head();
  7864. concatOpnds.RemoveHead();
  7865. ParseNode * pnode2 = concatOpnds.Head();
  7866. concatOpnds.RemoveHead();
  7867. if (concatCount == 3)
  7868. {
  7869. OUTPUT_TRACE_DEBUGONLY(Js::ByteCodeConcatExprOptPhase, _u("%s(%s) offset:#%d : Concat3\n"),
  7870. funcInfo->GetParsedFunctionBody()->GetDisplayName(),
  7871. funcInfo->GetParsedFunctionBody()->GetDebugNumberSet(debugStringBuffer),
  7872. byteCodeGenerator->Writer()->ByteCodeDataSize());
  7873. EmitConcat3(pnode, pnode1, pnode2, concatOpnds.Head(), byteCodeGenerator, funcInfo);
  7874. return;
  7875. }
  7876. OUTPUT_TRACE_DEBUGONLY(Js::ByteCodeConcatExprOptPhase, _u("%s(%s) offset:#%d: ConcatMulti %d\n"),
  7877. funcInfo->GetParsedFunctionBody()->GetDisplayName(),
  7878. funcInfo->GetParsedFunctionBody()->GetDebugNumberSet(debugStringBuffer),
  7879. byteCodeGenerator->Writer()->ByteCodeDataSize(), concatCount);
  7880. byteCodeGenerator->StartStatement(pnode);
  7881. funcInfo->AcquireLoc(pnode);
  7882. // CONSIDER: this may cause the backend not able CSE repeating pattern within the concat.
  7883. EmitNewConcatStrMulti(pnode, (uint8)concatCount, pnode1, pnode2, byteCodeGenerator, funcInfo);
  7884. uint i = 2;
  7885. do
  7886. {
  7887. ParseNode * currNode = concatOpnds.Head();
  7888. concatOpnds.RemoveHead();
  7889. ParseNode * currNode2 = concatOpnds.Head();
  7890. concatOpnds.RemoveHead();
  7891. EmitBinaryOpnds(currNode, currNode2, byteCodeGenerator, funcInfo);
  7892. funcInfo->ReleaseLoc(currNode2);
  7893. funcInfo->ReleaseLoc(currNode);
  7894. byteCodeGenerator->Writer()->Reg3B1(
  7895. Js::OpCode::SetConcatStrMultiItem2, pnode->location, currNode->location, currNode2->location, (uint8)i);
  7896. i += 2;
  7897. }
  7898. while (concatOpnds.Count() > 1);
  7899. if (!concatOpnds.Empty())
  7900. {
  7901. ParseNode * currNode = concatOpnds.Head();
  7902. Emit(currNode, byteCodeGenerator, funcInfo, false);
  7903. funcInfo->ReleaseLoc(currNode);
  7904. byteCodeGenerator->Writer()->Reg2B1(
  7905. Js::OpCode::SetConcatStrMultiItem, pnode->location, currNode->location, (uint8)i);
  7906. i++;
  7907. }
  7908. Assert(concatCount == i);
  7909. byteCodeGenerator->EndStatement(pnode);
  7910. return;
  7911. }
  7912. }
  7913. // Since we collected all the node already, let's just emit them instead of doing it recursively.
  7914. byteCodeGenerator->StartStatement(pnode);
  7915. ParseNode * currNode = concatOpnds.Head();
  7916. concatOpnds.RemoveHead();
  7917. ParseNode * currNode2 = concatOpnds.Head();
  7918. concatOpnds.RemoveHead();
  7919. EmitBinaryOpnds(currNode, currNode2, byteCodeGenerator, funcInfo);
  7920. funcInfo->ReleaseLoc(currNode2);
  7921. funcInfo->ReleaseLoc(currNode);
  7922. Js::RegSlot dstReg = funcInfo->AcquireLoc(pnode);
  7923. byteCodeGenerator->Writer()->Reg3(
  7924. Js::OpCode::Add_A, dstReg, currNode->location, currNode2->location);
  7925. while (!concatOpnds.Empty())
  7926. {
  7927. currNode = concatOpnds.Head();
  7928. concatOpnds.RemoveHead();
  7929. Emit(currNode, byteCodeGenerator, funcInfo, false);
  7930. funcInfo->ReleaseLoc(currNode);
  7931. byteCodeGenerator->Writer()->Reg3(
  7932. Js::OpCode::Add_A, dstReg, dstReg, currNode->location);
  7933. }
  7934. byteCodeGenerator->EndStatement(pnode);
  7935. }
  7936. else
  7937. {
  7938. EmitBinary(Js::OpCode::Add_A, pnode, byteCodeGenerator, funcInfo);
  7939. }
  7940. }
  7941. void EmitSuperFieldPatch(FuncInfo* funcInfo, ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator)
  7942. {
  7943. ParseNodePtr propFuncNode = funcInfo->root;
  7944. if (byteCodeGenerator->GetFlags() & fscrEval)
  7945. {
  7946. // If we are inside an eval, ScopedLdSuper will take care of the patch.
  7947. return;
  7948. }
  7949. if (funcInfo->IsLambda())
  7950. {
  7951. FuncInfo *parent = byteCodeGenerator->FindEnclosingNonLambda();
  7952. propFuncNode = parent->root;
  7953. }
  7954. // No need to emit a LdFld for the constructor.
  7955. if (propFuncNode->sxFnc.IsClassConstructor())
  7956. {
  7957. return;
  7958. }
  7959. if (!propFuncNode->sxFnc.IsClassMember() || propFuncNode->sxFnc.pid == nullptr)
  7960. {
  7961. // Non-methods will fail lookup.
  7962. return;
  7963. }
  7964. if (propFuncNode->sxFnc.pid->GetPropertyId() == Js::Constants::NoProperty)
  7965. {
  7966. byteCodeGenerator->AssignPropertyId(propFuncNode->sxFnc.pid);
  7967. }
  7968. // Load the current method's property ID from super instead of using super directly.
  7969. Js::RegSlot superLoc = funcInfo->superRegister;
  7970. pnode->sxCall.pnodeTarget->location = Js::Constants::NoRegister;
  7971. Js::RegSlot superPropLoc = funcInfo->AcquireLoc(pnode->sxCall.pnodeTarget);
  7972. Js::PropertyId propertyId = propFuncNode->sxFnc.pid->GetPropertyId();
  7973. uint cacheId = funcInfo->FindOrAddInlineCacheId(superLoc, propertyId, true, false);
  7974. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdMethodFld, superPropLoc, superLoc, cacheId);
  7975. propFuncNode->sxFnc.pnodeName = nullptr;
  7976. }
  7977. struct ByteCodeGenerator::TryScopeRecord : public JsUtil::DoublyLinkedListElement<TryScopeRecord>
  7978. {
  7979. Js::OpCode op;
  7980. Js::ByteCodeLabel label;
  7981. Js::RegSlot reg1;
  7982. Js::RegSlot reg2;
  7983. TryScopeRecord(Js::OpCode op, Js::ByteCodeLabel label) : op(op), label(label), reg1(Js::Constants::NoRegister), reg2(Js::Constants::NoRegister) { }
  7984. TryScopeRecord(Js::OpCode op, Js::ByteCodeLabel label, Js::RegSlot r1, Js::RegSlot r2) : op(op), label(label), reg1(r1), reg2(r2) { }
  7985. };
  7986. void ByteCodeGenerator::EmitLeaveOpCodesBeforeYield()
  7987. {
  7988. for (TryScopeRecord* node = this->tryScopeRecordsList.Tail(); node != nullptr; node = node->Previous())
  7989. {
  7990. switch (node->op)
  7991. {
  7992. case Js::OpCode::TryFinallyWithYield:
  7993. this->Writer()->Empty(Js::OpCode::LeaveNull);
  7994. break;
  7995. case Js::OpCode::TryCatch:
  7996. case Js::OpCode::ResumeFinally:
  7997. case Js::OpCode::ResumeCatch:
  7998. this->Writer()->Empty(Js::OpCode::Leave);
  7999. break;
  8000. default:
  8001. AssertMsg(false, "Unexpected OpCode before Yield in the Try-Catch-Finally cache for generator!");
  8002. break;
  8003. }
  8004. }
  8005. }
  8006. void ByteCodeGenerator::EmitTryBlockHeadersAfterYield()
  8007. {
  8008. for (TryScopeRecord* node = this->tryScopeRecordsList.Head(); node != nullptr; node = node->Next())
  8009. {
  8010. switch (node->op)
  8011. {
  8012. case Js::OpCode::TryCatch:
  8013. this->Writer()->Br(node->op, node->label);
  8014. break;
  8015. case Js::OpCode::TryFinallyWithYield:
  8016. case Js::OpCode::ResumeFinally:
  8017. this->Writer()->BrReg2(node->op, node->label, node->reg1, node->reg2);
  8018. break;
  8019. case Js::OpCode::ResumeCatch:
  8020. this->Writer()->Empty(node->op);
  8021. break;
  8022. default:
  8023. AssertMsg(false, "Unexpected OpCode after yield in the Try-Catch-Finally cache for generator!");
  8024. break;
  8025. }
  8026. }
  8027. }
  8028. void EmitYield(Js::RegSlot inputLocation, Js::RegSlot resultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo,
  8029. Js::RegSlot yieldStarIterator = Js::Constants::NoRegister)
  8030. {
  8031. // If the bytecode emitted by this function is part of 'yield*', inputLocation is the object
  8032. // returned by the iterable's next/return/throw method. Otherwise, it is the yielded value.
  8033. if (yieldStarIterator == Js::Constants::NoRegister)
  8034. {
  8035. byteCodeGenerator->Writer()->Reg1(Js::OpCode::NewScObjectSimple, funcInfo->yieldRegister);
  8036. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->yieldRegister, Js::PropertyIds::value, false, true);
  8037. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::StFld, inputLocation, funcInfo->yieldRegister, cacheId);
  8038. cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->yieldRegister, Js::PropertyIds::done, false, true);
  8039. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::StFld, funcInfo->falseConstantRegister, funcInfo->yieldRegister, cacheId);
  8040. }
  8041. else
  8042. {
  8043. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, funcInfo->yieldRegister, inputLocation);
  8044. }
  8045. byteCodeGenerator->EmitLeaveOpCodesBeforeYield();
  8046. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Yield, funcInfo->yieldRegister, funcInfo->yieldRegister);
  8047. byteCodeGenerator->EmitTryBlockHeadersAfterYield();
  8048. if (yieldStarIterator == Js::Constants::NoRegister)
  8049. {
  8050. byteCodeGenerator->Writer()->Reg2(Js::OpCode::ResumeYield, resultLocation, funcInfo->yieldRegister);
  8051. }
  8052. else
  8053. {
  8054. byteCodeGenerator->Writer()->Reg3(Js::OpCode::ResumeYieldStar, resultLocation, funcInfo->yieldRegister, yieldStarIterator);
  8055. }
  8056. }
  8057. void EmitYieldStar(ParseNode* yieldStarNode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8058. {
  8059. funcInfo->AcquireLoc(yieldStarNode);
  8060. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  8061. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  8062. Js::RegSlot iteratorLocation = funcInfo->AcquireTmpRegister();
  8063. // Evaluate operand
  8064. Emit(yieldStarNode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  8065. funcInfo->ReleaseLoc(yieldStarNode->sxUni.pnode1);
  8066. EmitGetIterator(iteratorLocation, yieldStarNode->sxUni.pnode1->location, byteCodeGenerator, funcInfo);
  8067. // Call the iterator's next()
  8068. EmitIteratorNext(yieldStarNode->location, iteratorLocation, funcInfo->undefinedConstantRegister, byteCodeGenerator, funcInfo);
  8069. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8070. // since a yield* doesn't have a user defined body, we cannot return from this loop
  8071. // which means we don't need to support EmitJumpCleanup() and there do not need to
  8072. // remember the loopId like the loop statements do.
  8073. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  8074. EmitIteratorComplete(doneLocation, yieldStarNode->location, byteCodeGenerator, funcInfo);
  8075. // branch past the loop if the done property is truthy
  8076. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, continuePastLoop, doneLocation);
  8077. funcInfo->ReleaseTmpRegister(doneLocation);
  8078. EmitYield(yieldStarNode->location, yieldStarNode->location, byteCodeGenerator, funcInfo, iteratorLocation);
  8079. funcInfo->ReleaseTmpRegister(iteratorLocation);
  8080. byteCodeGenerator->Writer()->Br(loopEntrance);
  8081. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  8082. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8083. // Put the iterator result's value in yieldStarNode->location.
  8084. // It will be used as the result value of the yield* operator expression.
  8085. EmitIteratorValue(yieldStarNode->location, yieldStarNode->location, byteCodeGenerator, funcInfo);
  8086. }
  8087. void TrackIntConstantsOnGlobalUserObject(ByteCodeGenerator *byteCodeGenerator, bool isSymGlobalAndSingleAssignment, Js::PropertyId propertyId)
  8088. {
  8089. if (isSymGlobalAndSingleAssignment)
  8090. {
  8091. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalUserObject(propertyId);
  8092. }
  8093. }
  8094. void TrackIntConstantsOnGlobalObject(ByteCodeGenerator *byteCodeGenerator, bool isSymGlobalAndSingleAssignment, Js::PropertyId propertyId)
  8095. {
  8096. if (isSymGlobalAndSingleAssignment)
  8097. {
  8098. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalObject(propertyId);
  8099. }
  8100. }
  8101. void TrackIntConstantsOnGlobalObject(ByteCodeGenerator *byteCodeGenerator, Symbol *sym)
  8102. {
  8103. if (sym && sym->GetIsGlobal() && sym->IsAssignedOnce())
  8104. {
  8105. Js::PropertyId propertyId = sym->EnsurePosition(byteCodeGenerator);
  8106. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalObject(propertyId);
  8107. }
  8108. }
  8109. void TrackMemberNodesInObjectForIntConstants(ByteCodeGenerator *byteCodeGenerator, ParseNodePtr objNode)
  8110. {
  8111. Assert(objNode->nop == knopObject);
  8112. Assert(ParseNode::Grfnop(objNode->nop) & fnopUni);
  8113. ParseNodePtr memberList = objNode->sxUni.pnode1;
  8114. if (memberList != nullptr)
  8115. {
  8116. // Iterate through all the member nodes
  8117. while (memberList->nop == knopList)
  8118. {
  8119. ParseNodePtr memberNode = memberList->sxBin.pnode1;
  8120. ParseNodePtr memberNameNode = memberNode->sxBin.pnode1;
  8121. ParseNodePtr memberValNode = memberNode->sxBin.pnode2;
  8122. if (memberNameNode->nop != knopComputedName && memberValNode->nop == knopInt)
  8123. {
  8124. Js::PropertyId propertyId = memberNameNode->sxPid.PropertyIdFromNameNode();
  8125. TrackIntConstantsOnGlobalUserObject(byteCodeGenerator, true, propertyId);
  8126. }
  8127. memberList = memberList->sxBin.pnode2;
  8128. }
  8129. ParseNode *memberNameNode = memberList->sxBin.pnode1;
  8130. ParseNode *memberValNode = memberList->sxBin.pnode2;
  8131. if (memberNameNode->nop != knopComputedName && memberValNode->nop == knopInt)
  8132. {
  8133. Js::PropertyId propertyId = memberNameNode->sxPid.PropertyIdFromNameNode();
  8134. TrackIntConstantsOnGlobalUserObject(byteCodeGenerator, true, propertyId);
  8135. }
  8136. }
  8137. }
  8138. void TrackGlobalIntAssignmentsForknopDotProps(ParseNodePtr knopDotNode, ByteCodeGenerator * byteCodeGenerator)
  8139. {
  8140. Assert(knopDotNode->nop == knopDot);
  8141. ParseNodePtr objectNode = knopDotNode->sxBin.pnode1;
  8142. ParseNodePtr propertyNode = knopDotNode->sxBin.pnode2;
  8143. bool isSymGlobalAndSingleAssignment = false;
  8144. if (objectNode->nop == knopName)
  8145. {
  8146. Symbol * sym = objectNode->sxVar.sym;
  8147. isSymGlobalAndSingleAssignment = sym && sym->GetIsGlobal() && sym->IsAssignedOnce() && propertyNode->sxPid.pid->IsSingleAssignment();
  8148. Js::PropertyId propertyId = propertyNode->sxPid.PropertyIdFromNameNode();
  8149. TrackIntConstantsOnGlobalUserObject(byteCodeGenerator, isSymGlobalAndSingleAssignment, propertyId);
  8150. }
  8151. else if (objectNode->nop == knopThis)
  8152. {
  8153. // Assume knopThis always refer to GlobalObject
  8154. // Cases like "this.a = "
  8155. isSymGlobalAndSingleAssignment = propertyNode->sxPid.pid->IsSingleAssignment();
  8156. Js::PropertyId propertyId = propertyNode->sxPid.PropertyIdFromNameNode();
  8157. TrackIntConstantsOnGlobalObject(byteCodeGenerator, isSymGlobalAndSingleAssignment, propertyId);
  8158. }
  8159. }
  8160. void TrackGlobalIntAssignments(ParseNodePtr pnode, ByteCodeGenerator * byteCodeGenerator)
  8161. {
  8162. // Track the Global Int Constant properties' assignments here.
  8163. uint nodeType = ParseNode::Grfnop(pnode->nop);
  8164. if (nodeType & fnopAsg)
  8165. {
  8166. if (nodeType & fnopBin)
  8167. {
  8168. ParseNodePtr lhs = pnode->sxBin.pnode1;
  8169. ParseNodePtr rhs = pnode->sxBin.pnode2;
  8170. Assert(lhs && rhs);
  8171. // Don't track other than integers and objects with member nodes.
  8172. if (rhs->nop == knopObject && (ParseNode::Grfnop(rhs->nop) & fnopUni))
  8173. {
  8174. TrackMemberNodesInObjectForIntConstants(byteCodeGenerator, rhs);
  8175. }
  8176. else if (rhs->nop != knopInt &&
  8177. ((rhs->nop != knopLsh && rhs->nop != knopRsh) || (rhs->sxBin.pnode1->nop != knopInt || rhs->sxBin.pnode2->nop != knopInt)))
  8178. {
  8179. return;
  8180. }
  8181. if (lhs->nop == knopName)
  8182. {
  8183. // Handle "a = <Integer>" cases here
  8184. Symbol * sym = lhs->sxVar.sym;
  8185. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  8186. }
  8187. else if (lhs->nop == knopDot && lhs->sxBin.pnode2->nop == knopName)
  8188. {
  8189. // Cases like "obj.a = <Integer>"
  8190. TrackGlobalIntAssignmentsForknopDotProps(lhs, byteCodeGenerator);
  8191. }
  8192. }
  8193. else if (nodeType & fnopUni)
  8194. {
  8195. ParseNodePtr lhs = pnode->sxUni.pnode1;
  8196. if (lhs->nop == knopName)
  8197. {
  8198. // Cases like "a++"
  8199. Symbol * sym = lhs->sxVar.sym;
  8200. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  8201. }
  8202. else if (lhs->nop == knopDot && lhs->sxBin.pnode2->nop == knopName)
  8203. {
  8204. // Cases like "obj.a++"
  8205. TrackGlobalIntAssignmentsForknopDotProps(lhs, byteCodeGenerator);
  8206. }
  8207. }
  8208. }
  8209. }
  8210. void Emit(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue, bool isConstructorCall, ParseNode * bindPnode, bool isTopLevel)
  8211. {
  8212. if (pnode == nullptr)
  8213. {
  8214. return;
  8215. }
  8216. if (EmitUseBeforeDeclaration(pnode, byteCodeGenerator, funcInfo))
  8217. {
  8218. if (fReturnValue && IsExpressionStatement(pnode, byteCodeGenerator->GetScriptContext()))
  8219. {
  8220. // If this statement may produce the global function's return value, make sure we load something to the
  8221. // return register for the JIT.
  8222. // fReturnValue implies global function, which implies that "return" is a parse error.
  8223. Assert(funcInfo->IsGlobalFunction());
  8224. Assert(pnode->nop != knopReturn);
  8225. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, ByteCodeGenerator::ReturnRegister);
  8226. }
  8227. return;
  8228. }
  8229. ThreadContext::ProbeCurrentStackNoDispose(Js::Constants::MinStackByteCodeVisitor, byteCodeGenerator->GetScriptContext());
  8230. TrackGlobalIntAssignments(pnode, byteCodeGenerator);
  8231. // printNop(pnode->nop);
  8232. switch (pnode->nop)
  8233. {
  8234. case knopList:
  8235. EmitList(pnode, byteCodeGenerator, funcInfo);
  8236. break;
  8237. case knopInt:
  8238. // currently, these are loaded at the top
  8239. break;
  8240. // PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  8241. case knopFlt:
  8242. // currently, these are loaded at the top
  8243. break;
  8244. // PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  8245. case knopStr:
  8246. // TODO: protocol for combining string constants
  8247. break;
  8248. // PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  8249. case knopRegExp:
  8250. funcInfo->GetParsedFunctionBody()->SetLiteralRegex(pnode->sxPid.regexPatternIndex, pnode->sxPid.regexPattern);
  8251. byteCodeGenerator->Writer()->Reg1Unsigned1(Js::OpCode::NewRegEx, funcInfo->AcquireLoc(pnode), pnode->sxPid.regexPatternIndex);
  8252. break; // PTNODE(knopThis , "this" ,None ,None ,fnopLeaf)
  8253. case knopThis:
  8254. // enregistered
  8255. // Try to load 'this' from a scope slot if we are in a derived class constructor with scope slots. Otherwise, this is a nop.
  8256. byteCodeGenerator->EmitScopeSlotLoadThis(funcInfo, funcInfo->thisPointerRegister);
  8257. break;
  8258. // PTNODE(knopNewTarget , "new.target" ,None , None , fnopLeaf)
  8259. case knopNewTarget:
  8260. break;
  8261. // PTNODE(knopSuper , "super" ,None , None , fnopLeaf)
  8262. case knopSuper:
  8263. if (!funcInfo->IsClassMember())
  8264. {
  8265. FuncInfo* nonLambdaFunc = funcInfo;
  8266. if (funcInfo->IsLambda())
  8267. {
  8268. nonLambdaFunc = byteCodeGenerator->FindEnclosingNonLambda();
  8269. }
  8270. if (nonLambdaFunc->IsGlobalFunction())
  8271. {
  8272. if ((byteCodeGenerator->GetFlags() & fscrEval))
  8273. {
  8274. byteCodeGenerator->Writer()->Reg1(isConstructorCall ? Js::OpCode::ScopedLdSuperCtor : Js::OpCode::ScopedLdSuper, funcInfo->AcquireLoc(pnode));
  8275. }
  8276. else
  8277. {
  8278. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_BadSuperReference));
  8279. }
  8280. }
  8281. else
  8282. {
  8283. Js::ByteCodeLabel errLabel = byteCodeGenerator->Writer()->DefineLabel();
  8284. Js::ByteCodeLabel skipLabel = byteCodeGenerator->Writer()->DefineLabel();
  8285. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrEq_A, errLabel, funcInfo->superRegister, funcInfo->undefinedConstantRegister);
  8286. byteCodeGenerator->Writer()->Br(Js::OpCode::Br, skipLabel);
  8287. byteCodeGenerator->Writer()->MarkLabel(errLabel);
  8288. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_BadSuperReference));
  8289. byteCodeGenerator->Writer()->MarkLabel(skipLabel);
  8290. }
  8291. }
  8292. break;
  8293. // PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  8294. case knopNull:
  8295. // enregistered
  8296. break;
  8297. // PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  8298. case knopFalse:
  8299. // enregistered
  8300. break;
  8301. // PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  8302. case knopTrue:
  8303. // enregistered
  8304. break;
  8305. // PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  8306. case knopEmpty:
  8307. break;
  8308. // Unary operators.
  8309. // PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  8310. case knopNot:
  8311. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8312. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  8313. funcInfo->ReleaseLoc(pnode->sxUni.pnode1);
  8314. byteCodeGenerator->Writer()->Reg2(
  8315. Js::OpCode::Not_A, funcInfo->AcquireLoc(pnode), pnode->sxUni.pnode1->location);
  8316. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8317. break;
  8318. // PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  8319. case knopNeg:
  8320. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8321. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  8322. funcInfo->ReleaseLoc(pnode->sxUni.pnode1);
  8323. funcInfo->AcquireLoc(pnode);
  8324. byteCodeGenerator->Writer()->Reg2(
  8325. Js::OpCode::Neg_A, pnode->location, pnode->sxUni.pnode1->location);
  8326. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8327. break;
  8328. // PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  8329. case knopPos:
  8330. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8331. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  8332. funcInfo->ReleaseLoc(pnode->sxUni.pnode1);
  8333. byteCodeGenerator->Writer()->Reg2(
  8334. Js::OpCode::Conv_Num, funcInfo->AcquireLoc(pnode), pnode->sxUni.pnode1->location);
  8335. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8336. break;
  8337. // PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  8338. case knopLogNot:
  8339. {
  8340. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8341. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  8342. // For boolean expressions that compute a result, we have to burn a register for the result
  8343. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  8344. // full-on renaming in the back end.
  8345. funcInfo->AcquireLoc(pnode);
  8346. if (pnode->sxUni.pnode1->nop == knopInt)
  8347. {
  8348. long value = pnode->sxUni.pnode1->sxInt.lw;
  8349. Js::OpCode op = value ? Js::OpCode::LdFalse : Js::OpCode::LdTrue;
  8350. byteCodeGenerator->Writer()->Reg1(op, pnode->location);
  8351. }
  8352. else
  8353. {
  8354. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  8355. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, pnode->location);
  8356. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, doneLabel, pnode->sxUni.pnode1->location);
  8357. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, pnode->location);
  8358. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  8359. }
  8360. funcInfo->ReleaseLoc(pnode->sxUni.pnode1);
  8361. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8362. break;
  8363. }
  8364. // PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  8365. case knopEllipsis:
  8366. {
  8367. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  8368. // Transparently pass the location of the array.
  8369. pnode->location = pnode->sxUni.pnode1->location;
  8370. break;
  8371. }
  8372. // PTNODE(knopIncPost , "post++" ,Inc ,Uni ,fnopUni|fnopAsg)
  8373. case knopIncPost:
  8374. case knopDecPost:
  8375. // FALL THROUGH to the faster pre-inc/dec case if the result of the expression is not needed.
  8376. if (pnode->isUsed || fReturnValue)
  8377. {
  8378. byteCodeGenerator->StartStatement(pnode);
  8379. Js::OpCode op = Js::OpCode::Add_A;
  8380. if (pnode->nop == knopDecPost)
  8381. {
  8382. op = Js::OpCode::Sub_A;
  8383. }
  8384. // Grab a register for the expression result.
  8385. funcInfo->AcquireLoc(pnode);
  8386. // Load the initial value, convert it (this is the expression result), and increment it.
  8387. EmitLoad(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo);
  8388. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Num, pnode->location, pnode->sxUni.pnode1->location);
  8389. Js::RegSlot incDecResult = pnode->sxUni.pnode1->location;
  8390. if (funcInfo->RegIsConst(incDecResult))
  8391. {
  8392. // Avoid letting the add/sub overwrite a constant reg, as this may actually change the
  8393. // contents of the constant table.
  8394. incDecResult = funcInfo->AcquireTmpRegister();
  8395. }
  8396. Js::RegSlot oneReg = funcInfo->constantToRegister.LookupWithKey(1, Js::Constants::NoRegister);
  8397. Assert(oneReg != Js::Constants::NoRegister);
  8398. byteCodeGenerator->Writer()->Reg3(op, incDecResult, pnode->location, oneReg);
  8399. // Store the incremented value.
  8400. EmitAssignment(nullptr, pnode->sxUni.pnode1, incDecResult, byteCodeGenerator, funcInfo);
  8401. // Release the incremented value and the l-value.
  8402. if (incDecResult != pnode->sxUni.pnode1->location)
  8403. {
  8404. funcInfo->ReleaseTmpRegister(incDecResult);
  8405. }
  8406. funcInfo->ReleaseLoad(pnode->sxUni.pnode1);
  8407. byteCodeGenerator->EndStatement(pnode);
  8408. break;
  8409. }
  8410. else
  8411. {
  8412. pnode->nop = (pnode->nop == knopIncPost) ? knopIncPre : knopDecPre;
  8413. }
  8414. // FALL THROUGH to the fast pre-inc/dec case if the result of the expression is not needed.
  8415. // PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  8416. case knopIncPre:
  8417. case knopDecPre:
  8418. {
  8419. byteCodeGenerator->StartStatement(pnode);
  8420. Js::OpCode op = Js::OpCode::Incr_A;
  8421. if (pnode->nop == knopDecPre)
  8422. {
  8423. op = Js::OpCode::Decr_A;
  8424. }
  8425. // Assign a register for the result only if the result is used or the operand can't be assigned to
  8426. // (i.e., is a constant).
  8427. if (pnode->isUsed || fReturnValue)
  8428. {
  8429. funcInfo->AcquireLoc(pnode);
  8430. // Load the initial value and increment it (this is the expression result).
  8431. EmitLoad(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo);
  8432. byteCodeGenerator->Writer()->Reg2(op, pnode->location, pnode->sxUni.pnode1->location);
  8433. // Store the incremented value and release the l-value.
  8434. EmitAssignment(nullptr, pnode->sxUni.pnode1, pnode->location, byteCodeGenerator, funcInfo);
  8435. funcInfo->ReleaseLoad(pnode->sxUni.pnode1);
  8436. }
  8437. else
  8438. {
  8439. // Load the initial value and increment it (this is the expression result).
  8440. EmitLoad(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo);
  8441. Js::RegSlot incDecResult = pnode->sxUni.pnode1->location;
  8442. if (funcInfo->RegIsConst(incDecResult))
  8443. {
  8444. // Avoid letting the add/sub overwrite a constant reg, as this may actually change the
  8445. // contents of the constant table.
  8446. incDecResult = funcInfo->AcquireTmpRegister();
  8447. }
  8448. byteCodeGenerator->Writer()->Reg2(op, incDecResult, pnode->sxUni.pnode1->location);
  8449. // Store the incremented value and release the l-value.
  8450. EmitAssignment(nullptr, pnode->sxUni.pnode1, incDecResult, byteCodeGenerator, funcInfo);
  8451. if (incDecResult != pnode->sxUni.pnode1->location)
  8452. {
  8453. funcInfo->ReleaseTmpRegister(incDecResult);
  8454. }
  8455. funcInfo->ReleaseLoad(pnode->sxUni.pnode1);
  8456. }
  8457. byteCodeGenerator->EndStatement(pnode);
  8458. break;
  8459. }
  8460. // PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  8461. case knopTypeof:
  8462. {
  8463. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8464. ParseNode* pnodeOpnd = pnode->sxUni.pnode1;
  8465. switch (pnodeOpnd->nop)
  8466. {
  8467. case knopDot:
  8468. {
  8469. Emit(pnodeOpnd->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  8470. Js::PropertyId propertyId = pnodeOpnd->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  8471. Assert(pnodeOpnd->sxBin.pnode2->nop == knopName);
  8472. funcInfo->ReleaseLoc(pnodeOpnd->sxBin.pnode1);
  8473. funcInfo->AcquireLoc(pnode);
  8474. byteCodeGenerator->EmitTypeOfFld(funcInfo, propertyId, pnode->location, pnodeOpnd->sxBin.pnode1->location, Js::OpCode::LdFldForTypeOf);
  8475. break;
  8476. }
  8477. case knopIndex:
  8478. {
  8479. EmitBinaryOpnds(pnodeOpnd->sxBin.pnode1, pnodeOpnd->sxBin.pnode2, byteCodeGenerator, funcInfo);
  8480. funcInfo->ReleaseLoc(pnodeOpnd->sxBin.pnode2);
  8481. funcInfo->ReleaseLoc(pnodeOpnd->sxBin.pnode1);
  8482. funcInfo->AcquireLoc(pnode);
  8483. byteCodeGenerator->Writer()->Element(Js::OpCode::TypeofElem, pnode->location, pnodeOpnd->sxBin.pnode1->location, pnodeOpnd->sxBin.pnode2->location);
  8484. break;
  8485. }
  8486. case knopName:
  8487. {
  8488. funcInfo->AcquireLoc(pnode);
  8489. byteCodeGenerator->EmitPropTypeof(pnode->location, pnodeOpnd->sxPid.sym, pnodeOpnd->sxPid.pid, funcInfo);
  8490. break;
  8491. }
  8492. default:
  8493. Emit(pnodeOpnd, byteCodeGenerator, funcInfo, false);
  8494. funcInfo->ReleaseLoc(pnodeOpnd);
  8495. byteCodeGenerator->Writer()->Reg2(
  8496. Js::OpCode::Typeof, funcInfo->AcquireLoc(pnode), pnodeOpnd->location);
  8497. break;
  8498. }
  8499. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8500. break;
  8501. }
  8502. // PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  8503. case knopVoid:
  8504. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  8505. funcInfo->ReleaseLoc(pnode->sxUni.pnode1);
  8506. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, funcInfo->AcquireLoc(pnode));
  8507. break;
  8508. // PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  8509. case knopArray:
  8510. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8511. EmitArrayLiteral(pnode, byteCodeGenerator, funcInfo);
  8512. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8513. break;
  8514. // PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  8515. case knopObject:
  8516. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8517. funcInfo->AcquireLoc(pnode);
  8518. EmitObjectInitializers(pnode->sxUni.pnode1, pnode->location, byteCodeGenerator, funcInfo);
  8519. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8520. break;
  8521. // PTNODE(knopComputedName, "[name]" ,None ,Uni ,fnopUni)
  8522. case knopComputedName:
  8523. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  8524. if (pnode->location == Js::Constants::NoRegister)
  8525. {
  8526. // The name is some expression with no home location. We can just re-use the register.
  8527. pnode->location = pnode->sxUni.pnode1->location;
  8528. }
  8529. else if (pnode->location != pnode->sxUni.pnode1->location)
  8530. {
  8531. // The name had to be protected from side-effects of the RHS.
  8532. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxUni.pnode1->location);
  8533. }
  8534. break;
  8535. // Binary and Ternary Operators
  8536. case knopAdd:
  8537. EmitAdd(pnode, byteCodeGenerator, funcInfo);
  8538. break;
  8539. case knopSub:
  8540. case knopMul:
  8541. case knopExpo:
  8542. case knopDiv:
  8543. case knopMod:
  8544. case knopOr:
  8545. case knopXor:
  8546. case knopAnd:
  8547. case knopLsh:
  8548. case knopRsh:
  8549. case knopRs2:
  8550. case knopIn:
  8551. EmitBinary(nopToOp[pnode->nop], pnode, byteCodeGenerator, funcInfo);
  8552. break;
  8553. case knopInstOf:
  8554. {
  8555. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8556. EmitBinaryOpnds(pnode->sxBin.pnode1, pnode->sxBin.pnode2, byteCodeGenerator, funcInfo);
  8557. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  8558. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  8559. funcInfo->AcquireLoc(pnode);
  8560. uint cacheId = funcInfo->NewIsInstInlineCache();
  8561. byteCodeGenerator->Writer()->Reg3C(nopToOp[pnode->nop], pnode->location, pnode->sxBin.pnode1->location,
  8562. pnode->sxBin.pnode2->location, cacheId);
  8563. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8564. }
  8565. break;
  8566. case knopEq:
  8567. case knopEqv:
  8568. case knopNEqv:
  8569. case knopNe:
  8570. case knopLt:
  8571. case knopLe:
  8572. case knopGe:
  8573. case knopGt:
  8574. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8575. EmitBinaryOpnds(pnode->sxBin.pnode1, pnode->sxBin.pnode2, byteCodeGenerator, funcInfo);
  8576. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  8577. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  8578. funcInfo->AcquireLoc(pnode);
  8579. byteCodeGenerator->Writer()->Reg3(nopToCMOp[pnode->nop], pnode->location, pnode->sxBin.pnode1->location,
  8580. pnode->sxBin.pnode2->location);
  8581. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8582. break;
  8583. case knopNew:
  8584. {
  8585. Js::ArgSlot argCount = pnode->sxCall.argCount;
  8586. argCount++; // include "this"
  8587. BOOL fSideEffectArgs = FALSE;
  8588. unsigned int tmpCount = CountArguments(pnode->sxCall.pnodeArgs, &fSideEffectArgs);
  8589. Assert(argCount == tmpCount);
  8590. if (argCount != (Js::ArgSlot)argCount)
  8591. {
  8592. Js::Throw::OutOfMemory();
  8593. }
  8594. byteCodeGenerator->StartStatement(pnode);
  8595. // Start call, allocate out param space
  8596. funcInfo->StartRecordingOutArgs(argCount);
  8597. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  8598. // them from side-effects.
  8599. if (fSideEffectArgs)
  8600. {
  8601. SaveOpndValue(pnode->sxCall.pnodeTarget, funcInfo);
  8602. }
  8603. if (pnode->sxCall.pnodeTarget->nop == knopSuper)
  8604. {
  8605. EmitSuperFieldPatch(funcInfo, pnode, byteCodeGenerator);
  8606. }
  8607. Emit(pnode->sxCall.pnodeTarget, byteCodeGenerator, funcInfo, false, true);
  8608. if (pnode->sxCall.pnodeArgs == nullptr)
  8609. {
  8610. funcInfo->ReleaseLoc(pnode->sxCall.pnodeTarget);
  8611. Js::OpCode op = (CreateNativeArrays(byteCodeGenerator, funcInfo)
  8612. && CallTargetIsArray(pnode->sxCall.pnodeTarget))
  8613. ? Js::OpCode::NewScObjArray : Js::OpCode::NewScObject;
  8614. Assert(argCount == 1);
  8615. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(op);
  8616. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argCount);
  8617. byteCodeGenerator->Writer()->CallI(op, funcInfo->AcquireLoc(pnode),
  8618. pnode->sxCall.pnodeTarget->location, argCount, callSiteId);
  8619. }
  8620. else
  8621. {
  8622. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argCount);
  8623. uint32 actualArgCount = 0;
  8624. if (IsCallOfConstants(pnode))
  8625. {
  8626. funcInfo->ReleaseLoc(pnode->sxCall.pnodeTarget);
  8627. actualArgCount = EmitNewObjectOfConstants(pnode, byteCodeGenerator, funcInfo, argCount);
  8628. }
  8629. else
  8630. {
  8631. Js::OpCode op;
  8632. if ((CreateNativeArrays(byteCodeGenerator, funcInfo) && CallTargetIsArray(pnode->sxCall.pnodeTarget)))
  8633. {
  8634. op = pnode->sxCall.spreadArgCount > 0 ? Js::OpCode::NewScObjArraySpread : Js::OpCode::NewScObjArray;
  8635. }
  8636. else
  8637. {
  8638. op = pnode->sxCall.spreadArgCount > 0 ? Js::OpCode::NewScObjectSpread : Js::OpCode::NewScObject;
  8639. }
  8640. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(op);
  8641. Js::AuxArray<uint32> *spreadIndices = nullptr;
  8642. actualArgCount = EmitArgList(pnode->sxCall.pnodeArgs, Js::Constants::NoRegister, Js::Constants::NoRegister, Js::Constants::NoRegister,
  8643. false, true, byteCodeGenerator, funcInfo, callSiteId, pnode->sxCall.spreadArgCount, &spreadIndices);
  8644. funcInfo->ReleaseLoc(pnode->sxCall.pnodeTarget);
  8645. if (pnode->sxCall.spreadArgCount > 0)
  8646. {
  8647. Assert(spreadIndices != nullptr);
  8648. uint spreadExtraAlloc = spreadIndices->count * sizeof(uint32);
  8649. uint spreadIndicesSize = sizeof(*spreadIndices) + spreadExtraAlloc;
  8650. byteCodeGenerator->Writer()->CallIExtended(op, funcInfo->AcquireLoc(pnode), pnode->sxCall.pnodeTarget->location,
  8651. (uint16)actualArgCount, Js::CallIExtended_SpreadArgs,
  8652. spreadIndices, spreadIndicesSize, callSiteId);
  8653. }
  8654. else
  8655. {
  8656. byteCodeGenerator->Writer()->CallI(op, funcInfo->AcquireLoc(pnode), pnode->sxCall.pnodeTarget->location,
  8657. (uint16)actualArgCount, callSiteId);
  8658. }
  8659. }
  8660. Assert(argCount == actualArgCount);
  8661. }
  8662. // End call, pop param space
  8663. funcInfo->EndRecordingOutArgs(argCount);
  8664. byteCodeGenerator->EndStatement(pnode);
  8665. break;
  8666. }
  8667. case knopDelete:
  8668. {
  8669. ParseNode *pexpr = pnode->sxUni.pnode1;
  8670. byteCodeGenerator->StartStatement(pnode);
  8671. switch (pexpr->nop)
  8672. {
  8673. case knopName:
  8674. {
  8675. funcInfo->AcquireLoc(pnode);
  8676. byteCodeGenerator->EmitPropDelete(pnode->location, pexpr->sxPid.sym, pexpr->sxPid.pid, funcInfo);
  8677. break;
  8678. }
  8679. case knopDot:
  8680. {
  8681. Emit(pexpr->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  8682. Js::PropertyId propertyId = pexpr->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  8683. funcInfo->ReleaseLoc(pexpr->sxBin.pnode1);
  8684. funcInfo->AcquireLoc(pnode);
  8685. byteCodeGenerator->Writer()->Property(Js::OpCode::DeleteFld, pnode->location, pexpr->sxBin.pnode1->location,
  8686. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  8687. break;
  8688. }
  8689. case knopIndex:
  8690. {
  8691. EmitBinaryOpnds(pexpr->sxBin.pnode1, pexpr->sxBin.pnode2, byteCodeGenerator, funcInfo);
  8692. funcInfo->ReleaseLoc(pexpr->sxBin.pnode2);
  8693. funcInfo->ReleaseLoc(pexpr->sxBin.pnode1);
  8694. funcInfo->AcquireLoc(pnode);
  8695. byteCodeGenerator->Writer()->Element(Js::OpCode::DeleteElemI_A, pnode->location, pexpr->sxBin.pnode1->location, pexpr->sxBin.pnode2->location);
  8696. break;
  8697. }
  8698. case knopThis:
  8699. {
  8700. funcInfo->AcquireLoc(pnode);
  8701. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, pnode->location);
  8702. break;
  8703. }
  8704. default:
  8705. {
  8706. Emit(pexpr, byteCodeGenerator, funcInfo, false);
  8707. funcInfo->ReleaseLoc(pexpr);
  8708. byteCodeGenerator->Writer()->Reg2(
  8709. Js::OpCode::Delete_A, funcInfo->AcquireLoc(pnode), pexpr->location);
  8710. break;
  8711. }
  8712. }
  8713. byteCodeGenerator->EndStatement(pnode);
  8714. break;
  8715. }
  8716. case knopCall:
  8717. {
  8718. byteCodeGenerator->StartStatement(pnode);
  8719. if (pnode->sxCall.pnodeTarget->nop == knopSuper)
  8720. {
  8721. byteCodeGenerator->EmitSuperCall(funcInfo, pnode, fReturnValue);
  8722. }
  8723. else
  8724. {
  8725. if (pnode->sxCall.isApplyCall && funcInfo->GetApplyEnclosesArgs())
  8726. {
  8727. // TODO[ianhall]: Can we remove the ApplyCall bytecode gen time optimization?
  8728. EmitApplyCall(pnode, Js::Constants::NoRegister, byteCodeGenerator, funcInfo, fReturnValue, true);
  8729. }
  8730. else
  8731. {
  8732. EmitCall(pnode, Js::Constants::NoRegister, byteCodeGenerator, funcInfo, fReturnValue, /*fEvaluateComponents*/ true, /*fHasNewTarget*/ false);
  8733. }
  8734. }
  8735. byteCodeGenerator->EndStatement(pnode);
  8736. break;
  8737. }
  8738. case knopIndex:
  8739. {
  8740. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8741. EmitBinaryOpnds(pnode->sxBin.pnode1, pnode->sxBin.pnode2, byteCodeGenerator, funcInfo);
  8742. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  8743. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  8744. funcInfo->AcquireLoc(pnode);
  8745. Js::RegSlot callObjLocation = pnode->sxBin.pnode1->location;
  8746. Js::RegSlot protoLocation = callObjLocation;
  8747. EmitSuperMethodBegin(pnode, byteCodeGenerator, funcInfo);
  8748. byteCodeGenerator->Writer()->Element(
  8749. Js::OpCode::LdElemI_A, pnode->location, protoLocation, pnode->sxBin.pnode2->location);
  8750. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8751. break;
  8752. }
  8753. // this is MemberExpression as rvalue
  8754. case knopDot:
  8755. {
  8756. Emit(pnode->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  8757. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  8758. funcInfo->AcquireLoc(pnode);
  8759. Js::PropertyId propertyId = pnode->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  8760. Js::RegSlot callObjLocation = pnode->sxBin.pnode1->location;
  8761. Js::RegSlot protoLocation = callObjLocation;
  8762. EmitSuperMethodBegin(pnode, byteCodeGenerator, funcInfo);
  8763. if (propertyId == Js::PropertyIds::length)
  8764. {
  8765. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdLen_A, pnode->location, protoLocation);
  8766. }
  8767. else
  8768. {
  8769. uint cacheId = funcInfo->FindOrAddInlineCacheId(callObjLocation, propertyId, false, false);
  8770. if (pnode->IsCallApplyTargetLoad())
  8771. {
  8772. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFldForCallApplyTarget, pnode->location, protoLocation, cacheId);
  8773. }
  8774. else
  8775. {
  8776. if (pnode->sxBin.pnode1->nop == knopSuper)
  8777. {
  8778. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(Js::OpCode::LdSuperFld, pnode->location, protoLocation, funcInfo->thisPointerRegister, cacheId, isConstructorCall);
  8779. }
  8780. else
  8781. {
  8782. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, pnode->location, callObjLocation, cacheId, isConstructorCall);
  8783. }
  8784. }
  8785. }
  8786. break;
  8787. }
  8788. // PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  8789. case knopAsg:
  8790. {
  8791. ParseNode *lhs = pnode->sxBin.pnode1;
  8792. ParseNode *rhs = pnode->sxBin.pnode2;
  8793. byteCodeGenerator->StartStatement(pnode);
  8794. if (pnode->isUsed || fReturnValue)
  8795. {
  8796. // If the assignment result is used, grab a register to hold it and pass it to EmitAssignment,
  8797. // which will copy the assigned value there.
  8798. funcInfo->AcquireLoc(pnode);
  8799. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, false);
  8800. EmitAssignment(pnode, lhs, rhs->location, byteCodeGenerator, funcInfo);
  8801. }
  8802. else
  8803. {
  8804. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, false);
  8805. EmitAssignment(nullptr, lhs, rhs->location, byteCodeGenerator, funcInfo);
  8806. }
  8807. funcInfo->ReleaseLoc(rhs);
  8808. if (!(byteCodeGenerator->IsES6DestructuringEnabled() && (lhs->IsPattern())))
  8809. {
  8810. funcInfo->ReleaseReference(lhs);
  8811. }
  8812. byteCodeGenerator->EndStatement(pnode);
  8813. break;
  8814. }
  8815. case knopName:
  8816. funcInfo->AcquireLoc(pnode);
  8817. byteCodeGenerator->EmitPropLoad(pnode->location, pnode->sxPid.sym, pnode->sxPid.pid, funcInfo);
  8818. break;
  8819. case knopComma:
  8820. {
  8821. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8822. // The parser marks binary opnd pnodes as used, but value of the first opnd of a comma is not used.
  8823. // Easier to correct this here than to check every binary op in the parser.
  8824. ParseNode *pnode1 = pnode->sxBin.pnode1;
  8825. pnode1->isUsed = false;
  8826. if (pnode1->nop == knopComma)
  8827. {
  8828. // Spot fix for giant comma expressions that send us into OOS if we use a simple recursive
  8829. // algorithm. Instead of recursing on comma LHS's, iterate over them, pushing the RHS's onto
  8830. // a stack. (This suggests a model for removing recursion from Emit altogether...)
  8831. ArenaAllocator *alloc = byteCodeGenerator->GetAllocator();
  8832. SList<ParseNode *> rhsStack(alloc);
  8833. do
  8834. {
  8835. rhsStack.Push(pnode1->sxBin.pnode2);
  8836. pnode1 = pnode1->sxBin.pnode1;
  8837. pnode1->isUsed = false;
  8838. }
  8839. while (pnode1->nop == knopComma);
  8840. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  8841. if (funcInfo->IsTmpReg(pnode1->location))
  8842. {
  8843. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Unused, pnode1->location);
  8844. }
  8845. while (!rhsStack.Empty())
  8846. {
  8847. ParseNode *pnodeRhs = rhsStack.Pop();
  8848. pnodeRhs->isUsed = false;
  8849. Emit(pnodeRhs, byteCodeGenerator, funcInfo, false);
  8850. if (funcInfo->IsTmpReg(pnodeRhs->location))
  8851. {
  8852. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Unused, pnodeRhs->location);
  8853. }
  8854. funcInfo->ReleaseLoc(pnodeRhs);
  8855. }
  8856. }
  8857. else
  8858. {
  8859. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  8860. if (funcInfo->IsTmpReg(pnode1->location))
  8861. {
  8862. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Unused, pnode1->location);
  8863. }
  8864. }
  8865. funcInfo->ReleaseLoc(pnode1);
  8866. pnode->sxBin.pnode2->isUsed = pnode->isUsed || fReturnValue;
  8867. Emit(pnode->sxBin.pnode2, byteCodeGenerator, funcInfo, false);
  8868. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  8869. funcInfo->AcquireLoc(pnode);
  8870. if (pnode->sxBin.pnode2->isUsed && pnode->location != pnode->sxBin.pnode2->location)
  8871. {
  8872. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxBin.pnode2->location);
  8873. }
  8874. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8875. }
  8876. break;
  8877. // The binary logical ops && and || resolve to the value of the left-hand expression if its
  8878. // boolean value short-circuits the operation, and to the value of the right-hand expression
  8879. // otherwise. (In other words, the "truth" of the right-hand expression is never tested.)
  8880. // PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  8881. case knopLogOr:
  8882. {
  8883. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8884. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  8885. // For boolean expressions that compute a result, we have to burn a register for the result
  8886. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  8887. // full-on renaming in the back end.
  8888. funcInfo->AcquireLoc(pnode);
  8889. Emit(pnode->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  8890. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxBin.pnode1->location);
  8891. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, doneLabel, pnode->sxBin.pnode1->location);
  8892. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  8893. Emit(pnode->sxBin.pnode2, byteCodeGenerator, funcInfo, false);
  8894. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxBin.pnode2->location);
  8895. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  8896. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  8897. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8898. break;
  8899. }
  8900. // PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  8901. case knopLogAnd:
  8902. {
  8903. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8904. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  8905. // For boolean expressions that compute a result, we have to burn a register for the result
  8906. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  8907. // full-on renaming in the back end.
  8908. funcInfo->AcquireLoc(pnode);
  8909. Emit(pnode->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  8910. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxBin.pnode1->location);
  8911. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, doneLabel, pnode->sxBin.pnode1->location);
  8912. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  8913. Emit(pnode->sxBin.pnode2, byteCodeGenerator, funcInfo, false);
  8914. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxBin.pnode2->location);
  8915. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  8916. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  8917. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8918. break;
  8919. }
  8920. // PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  8921. case knopQmark:
  8922. {
  8923. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  8924. Js::ByteCodeLabel falseLabel = byteCodeGenerator->Writer()->DefineLabel();
  8925. Js::ByteCodeLabel skipLabel = byteCodeGenerator->Writer()->DefineLabel();
  8926. EmitBooleanExpression(pnode->sxTri.pnode1, trueLabel, falseLabel, byteCodeGenerator, funcInfo);
  8927. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  8928. funcInfo->ReleaseLoc(pnode->sxTri.pnode1);
  8929. // For boolean expressions that compute a result, we have to burn a register for the result
  8930. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  8931. // full-on renaming in the back end.
  8932. funcInfo->AcquireLoc(pnode);
  8933. Emit(pnode->sxTri.pnode2, byteCodeGenerator, funcInfo, false);
  8934. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxTri.pnode2->location);
  8935. funcInfo->ReleaseLoc(pnode->sxTri.pnode2);
  8936. // Record the branch bytecode offset
  8937. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_FromCurrentToNext);
  8938. byteCodeGenerator->Writer()->Br(skipLabel);
  8939. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  8940. Emit(pnode->sxTri.pnode3, byteCodeGenerator, funcInfo, false);
  8941. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxTri.pnode3->location);
  8942. funcInfo->ReleaseLoc(pnode->sxTri.pnode3);
  8943. byteCodeGenerator->Writer()->MarkLabel(skipLabel);
  8944. break;
  8945. }
  8946. case knopAsgAdd:
  8947. case knopAsgSub:
  8948. case knopAsgMul:
  8949. case knopAsgDiv:
  8950. case knopAsgExpo:
  8951. case knopAsgMod:
  8952. case knopAsgAnd:
  8953. case knopAsgXor:
  8954. case knopAsgOr:
  8955. case knopAsgLsh:
  8956. case knopAsgRsh:
  8957. case knopAsgRs2:
  8958. byteCodeGenerator->StartStatement(pnode);
  8959. // Assign a register for the result only if the result is used or the LHS can't be assigned to
  8960. // (i.e., is a constant).
  8961. if (pnode->isUsed || fReturnValue || funcInfo->RegIsConst(pnode->sxBin.pnode1->location))
  8962. {
  8963. // If the assign-op result is used, grab a register to hold it.
  8964. funcInfo->AcquireLoc(pnode);
  8965. // Grab a register for the initial value and load it.
  8966. EmitBinaryReference(pnode->sxBin.pnode1, pnode->sxBin.pnode2, byteCodeGenerator, funcInfo, true);
  8967. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  8968. // Do the arithmetic, store the result, and release the l-value.
  8969. byteCodeGenerator->Writer()->Reg3(nopToOp[pnode->nop], pnode->location, pnode->sxBin.pnode1->location,
  8970. pnode->sxBin.pnode2->location);
  8971. EmitAssignment(pnode, pnode->sxBin.pnode1, pnode->location, byteCodeGenerator, funcInfo);
  8972. }
  8973. else
  8974. {
  8975. // Grab a register for the initial value and load it.
  8976. EmitBinaryReference(pnode->sxBin.pnode1, pnode->sxBin.pnode2, byteCodeGenerator, funcInfo, true);
  8977. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  8978. // Do the arithmetic, store the result, and release the l-value.
  8979. byteCodeGenerator->Writer()->Reg3(nopToOp[pnode->nop], pnode->sxBin.pnode1->location, pnode->sxBin.pnode1->location,
  8980. pnode->sxBin.pnode2->location);
  8981. EmitAssignment(nullptr, pnode->sxBin.pnode1, pnode->sxBin.pnode1->location, byteCodeGenerator, funcInfo);
  8982. }
  8983. funcInfo->ReleaseLoad(pnode->sxBin.pnode1);
  8984. byteCodeGenerator->EndStatement(pnode);
  8985. break;
  8986. // General nodes.
  8987. // PTNODE(knopTempRef , "temp ref" ,None ,Uni ,fnopUni)
  8988. case knopTempRef:
  8989. // TODO: check whether mov is necessary
  8990. funcInfo->AcquireLoc(pnode);
  8991. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxUni.pnode1->location);
  8992. break;
  8993. // PTNODE(knopTemp , "temp" ,None ,None ,fnopLeaf)
  8994. case knopTemp:
  8995. // Emit initialization code
  8996. if (pnode->sxVar.pnodeInit != nullptr)
  8997. {
  8998. byteCodeGenerator->StartStatement(pnode);
  8999. Emit(pnode->sxVar.pnodeInit, byteCodeGenerator, funcInfo, false);
  9000. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxVar.pnodeInit->location);
  9001. funcInfo->ReleaseLoc(pnode->sxVar.pnodeInit);
  9002. byteCodeGenerator->EndStatement(pnode);
  9003. }
  9004. break;
  9005. // PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  9006. case knopVarDecl:
  9007. {
  9008. // Emit initialization code
  9009. ParseNodePtr initNode = pnode->sxVar.pnodeInit;
  9010. if (initNode != nullptr)
  9011. {
  9012. byteCodeGenerator->StartStatement(pnode);
  9013. Emit(pnode->sxVar.pnodeInit, byteCodeGenerator, funcInfo, false);
  9014. EmitAssignment(nullptr, pnode, pnode->sxVar.pnodeInit->location, byteCodeGenerator, funcInfo);
  9015. funcInfo->ReleaseLoc(pnode->sxVar.pnodeInit);
  9016. byteCodeGenerator->EndStatement(pnode);
  9017. Symbol *sym = pnode->sxVar.sym;
  9018. if (pnode->sxVar.pnodeInit->nop == knopObject && (ParseNode::Grfnop(pnode->sxVar.pnodeInit->nop) & fnopUni))
  9019. {
  9020. TrackMemberNodesInObjectForIntConstants(byteCodeGenerator, pnode->sxVar.pnodeInit);
  9021. }
  9022. else if (initNode->nop == knopInt)
  9023. {
  9024. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  9025. }
  9026. }
  9027. break;
  9028. }
  9029. case knopConstDecl:
  9030. {
  9031. ParseNodePtr initNode = pnode->sxVar.pnodeInit;
  9032. Symbol * sym = pnode->sxVar.sym;
  9033. byteCodeGenerator->StartStatement(pnode);
  9034. if (initNode)
  9035. {
  9036. Emit(initNode, byteCodeGenerator, funcInfo, false);
  9037. byteCodeGenerator->EmitPropStore(initNode->location, sym, nullptr, funcInfo, false, true);
  9038. funcInfo->ReleaseLoc(pnode->sxVar.pnodeInit);
  9039. if (initNode->nop == knopInt)
  9040. {
  9041. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  9042. }
  9043. }
  9044. byteCodeGenerator->EndStatement(pnode);
  9045. // Set NeedDeclaration to false AFTER emitting the initializer, otherwise we won't have "Use Before Declaration"
  9046. // errors reported in the initializer for code like this:
  9047. // { const a = a; }
  9048. sym->SetNeedDeclaration(false);
  9049. break;
  9050. }
  9051. case knopLetDecl:
  9052. {
  9053. ParseNodePtr initNode = pnode->sxVar.pnodeInit;
  9054. byteCodeGenerator->StartStatement(pnode);
  9055. Symbol * sym = pnode->sxVar.sym;
  9056. Js::RegSlot rhsLocation;
  9057. if (pnode->sxVar.pnodeInit != nullptr)
  9058. {
  9059. Emit(pnode->sxVar.pnodeInit, byteCodeGenerator, funcInfo, false);
  9060. rhsLocation = pnode->sxVar.pnodeInit->location;
  9061. if (initNode->nop == knopInt)
  9062. {
  9063. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  9064. }
  9065. }
  9066. else
  9067. {
  9068. rhsLocation = funcInfo->AcquireTmpRegister();
  9069. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, rhsLocation);
  9070. }
  9071. // Set NeedDeclaration to false AFTER emitting the initializer, otherwise we won't have "Use Before Declaration"
  9072. // errors reported in the initializer for code like this:
  9073. // { let a = a; }
  9074. sym->SetNeedDeclaration(false);
  9075. byteCodeGenerator->EmitPropStore(rhsLocation, sym, nullptr, funcInfo, true, false);
  9076. funcInfo->ReleaseTmpRegister(rhsLocation);
  9077. byteCodeGenerator->EndStatement(pnode);
  9078. break;
  9079. }
  9080. // PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  9081. case knopFncDecl:
  9082. // The "function declarations" were emitted in DefineFunctions()
  9083. if (!pnode->sxFnc.IsDeclaration())
  9084. {
  9085. byteCodeGenerator->DefineOneFunction(pnode, funcInfo, false);
  9086. }
  9087. break;
  9088. // PTNODE(knopClassDecl, "class" ,None ,None ,fnopLeaf)
  9089. case knopClassDecl:
  9090. {
  9091. funcInfo->AcquireLoc(pnode);
  9092. // Extends
  9093. if (pnode->sxClass.pnodeExtends)
  9094. {
  9095. // We can't do StartStatement/EndStatement for pnodeExtends here because the load locations may differ between
  9096. // defer and nondefer parse modes.
  9097. Emit(pnode->sxClass.pnodeExtends, byteCodeGenerator, funcInfo, false);
  9098. }
  9099. Assert(pnode->sxClass.pnodeConstructor);
  9100. pnode->sxClass.pnodeConstructor->location = pnode->location;
  9101. BeginEmitBlock(pnode->sxClass.pnodeBlock, byteCodeGenerator, funcInfo);
  9102. // Constructor
  9103. Emit(pnode->sxClass.pnodeConstructor, byteCodeGenerator, funcInfo, false);
  9104. EmitComputedFunctionNameVar(bindPnode, pnode->sxClass.pnodeConstructor, byteCodeGenerator);
  9105. if (pnode->sxClass.pnodeExtends)
  9106. {
  9107. byteCodeGenerator->StartStatement(pnode->sxClass.pnodeExtends);
  9108. byteCodeGenerator->Writer()->InitClass(pnode->location, pnode->sxClass.pnodeExtends->location);
  9109. byteCodeGenerator->EndStatement(pnode->sxClass.pnodeExtends);
  9110. }
  9111. else
  9112. {
  9113. byteCodeGenerator->Writer()->InitClass(pnode->location);
  9114. }
  9115. Js::RegSlot protoLoc = funcInfo->AcquireTmpRegister(); //register set if we have Instance Methods
  9116. int cacheId = funcInfo->FindOrAddInlineCacheId(pnode->location, Js::PropertyIds::prototype, false, false);
  9117. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, protoLoc, pnode->location, cacheId);
  9118. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SetHomeObj, pnode->location, protoLoc);
  9119. // Static Methods
  9120. EmitClassInitializers(pnode->sxClass.pnodeStaticMembers, pnode->location, byteCodeGenerator, funcInfo, pnode, /*isObjectEmpty*/ false);
  9121. // Instance Methods
  9122. EmitClassInitializers(pnode->sxClass.pnodeMembers, protoLoc, byteCodeGenerator, funcInfo, pnode, /*isObjectEmpty*/ true);
  9123. funcInfo->ReleaseTmpRegister(protoLoc);
  9124. // Emit name binding.
  9125. if (pnode->sxClass.pnodeName)
  9126. {
  9127. Symbol * sym = pnode->sxClass.pnodeName->sxVar.sym;
  9128. sym->SetNeedDeclaration(false);
  9129. byteCodeGenerator->EmitPropStore(pnode->location, sym, nullptr, funcInfo, false, true);
  9130. }
  9131. EndEmitBlock(pnode->sxClass.pnodeBlock, byteCodeGenerator, funcInfo);
  9132. if (pnode->sxClass.pnodeExtends)
  9133. {
  9134. funcInfo->ReleaseLoc(pnode->sxClass.pnodeExtends);
  9135. }
  9136. if (pnode->sxClass.pnodeDeclName)
  9137. {
  9138. Symbol * sym = pnode->sxClass.pnodeDeclName->sxVar.sym;
  9139. sym->SetNeedDeclaration(false);
  9140. byteCodeGenerator->EmitPropStore(pnode->location, sym, nullptr, funcInfo, true, false);
  9141. }
  9142. if (pnode->sxClass.IsDefaultModuleExport())
  9143. {
  9144. byteCodeGenerator->EmitAssignmentToDefaultModuleExport(pnode, funcInfo);
  9145. }
  9146. break;
  9147. }
  9148. case knopStrTemplate:
  9149. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9150. EmitStringTemplate(pnode, byteCodeGenerator, funcInfo);
  9151. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9152. break;
  9153. case knopEndCode:
  9154. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_All);
  9155. // load undefined for the fallthrough case:
  9156. if (!funcInfo->IsGlobalFunction())
  9157. {
  9158. if (funcInfo->IsClassConstructor())
  9159. {
  9160. // For class constructors, we need to explicitly load 'this' into the return register.
  9161. byteCodeGenerator->EmitClassConstructorEndCode(funcInfo);
  9162. }
  9163. else
  9164. {
  9165. // In the global function, implicit return values are copied to the return register, and if
  9166. // necessary the return register is initialized at the top. Don't clobber the value here.
  9167. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, ByteCodeGenerator::ReturnRegister);
  9168. }
  9169. }
  9170. // Label for non-fall-through return
  9171. byteCodeGenerator->Writer()->MarkLabel(funcInfo->singleExit);
  9172. if (funcInfo->GetHasCachedScope())
  9173. {
  9174. byteCodeGenerator->Writer()->AuxNoReg(
  9175. Js::OpCode::CommitScope,
  9176. funcInfo->localPropIdOffset,
  9177. sizeof(Js::PropertyIdArray) + ((funcInfo->GetBodyScope()->GetScopeSlotCount() + 3) * sizeof(Js::PropertyId)));
  9178. }
  9179. byteCodeGenerator->StartStatement(pnode);
  9180. byteCodeGenerator->Writer()->Empty(Js::OpCode::Ret);
  9181. byteCodeGenerator->EndStatement(pnode);
  9182. break;
  9183. // PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  9184. case knopDebugger:
  9185. byteCodeGenerator->StartStatement(pnode);
  9186. byteCodeGenerator->Writer()->Empty(Js::OpCode::Break);
  9187. byteCodeGenerator->EndStatement(pnode);
  9188. break;
  9189. // PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  9190. case knopFor:
  9191. if (pnode->sxFor.pnodeInverted != nullptr)
  9192. {
  9193. byteCodeGenerator->EmitInvertedLoop(pnode, pnode->sxFor.pnodeInverted, funcInfo);
  9194. }
  9195. else
  9196. {
  9197. BeginEmitBlock(pnode->sxFor.pnodeBlock, byteCodeGenerator, funcInfo);
  9198. Emit(pnode->sxFor.pnodeInit, byteCodeGenerator, funcInfo, false);
  9199. funcInfo->ReleaseLoc(pnode->sxFor.pnodeInit);
  9200. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  9201. {
  9202. CloneEmitBlock(pnode->sxFor.pnodeBlock, byteCodeGenerator, funcInfo);
  9203. }
  9204. EmitLoop(pnode,
  9205. pnode->sxFor.pnodeCond,
  9206. pnode->sxFor.pnodeBody,
  9207. pnode->sxFor.pnodeIncr,
  9208. byteCodeGenerator,
  9209. funcInfo,
  9210. fReturnValue,
  9211. FALSE,
  9212. pnode->sxFor.pnodeBlock);
  9213. EndEmitBlock(pnode->sxFor.pnodeBlock, byteCodeGenerator, funcInfo);
  9214. }
  9215. break;
  9216. // PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  9217. case knopIf:
  9218. {
  9219. byteCodeGenerator->StartStatement(pnode);
  9220. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  9221. Js::ByteCodeLabel falseLabel = byteCodeGenerator->Writer()->DefineLabel();
  9222. EmitBooleanExpression(pnode->sxIf.pnodeCond, trueLabel, falseLabel, byteCodeGenerator, funcInfo);
  9223. funcInfo->ReleaseLoc(pnode->sxIf.pnodeCond);
  9224. byteCodeGenerator->EndStatement(pnode);
  9225. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  9226. Emit(pnode->sxIf.pnodeTrue, byteCodeGenerator, funcInfo, fReturnValue);
  9227. funcInfo->ReleaseLoc(pnode->sxIf.pnodeTrue);
  9228. if (pnode->sxIf.pnodeFalse != nullptr)
  9229. {
  9230. // has else clause
  9231. Js::ByteCodeLabel skipLabel = byteCodeGenerator->Writer()->DefineLabel();
  9232. // Record the branch bytecode offset
  9233. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_FromCurrentToNext);
  9234. // then clause skips else clause
  9235. byteCodeGenerator->Writer()->Br(skipLabel);
  9236. // generate code for else clause
  9237. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  9238. Emit(pnode->sxIf.pnodeFalse, byteCodeGenerator, funcInfo, fReturnValue);
  9239. funcInfo->ReleaseLoc(pnode->sxIf.pnodeFalse);
  9240. byteCodeGenerator->Writer()->MarkLabel(skipLabel);
  9241. }
  9242. else
  9243. {
  9244. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  9245. }
  9246. if (pnode->emitLabels)
  9247. {
  9248. byteCodeGenerator->Writer()->MarkLabel(pnode->sxStmt.breakLabel);
  9249. }
  9250. break;
  9251. }
  9252. case knopWhile:
  9253. EmitLoop(pnode,
  9254. pnode->sxWhile.pnodeCond,
  9255. pnode->sxWhile.pnodeBody,
  9256. nullptr,
  9257. byteCodeGenerator,
  9258. funcInfo,
  9259. fReturnValue);
  9260. break;
  9261. // PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  9262. case knopDoWhile:
  9263. EmitLoop(pnode,
  9264. pnode->sxWhile.pnodeCond,
  9265. pnode->sxWhile.pnodeBody,
  9266. nullptr,
  9267. byteCodeGenerator,
  9268. funcInfo,
  9269. fReturnValue,
  9270. true);
  9271. break;
  9272. // PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  9273. case knopForIn:
  9274. EmitForInOrForOf(pnode, byteCodeGenerator, funcInfo, fReturnValue);
  9275. break;
  9276. case knopForOf:
  9277. EmitForInOrForOf(pnode, byteCodeGenerator, funcInfo, fReturnValue);
  9278. break;
  9279. // PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  9280. case knopReturn:
  9281. byteCodeGenerator->StartStatement(pnode);
  9282. if (pnode->sxReturn.pnodeExpr != nullptr)
  9283. {
  9284. if (pnode->sxReturn.pnodeExpr->location == Js::Constants::NoRegister)
  9285. {
  9286. // No need to burn a register for the return value. If we need a temp, use R0 directly.
  9287. pnode->sxReturn.pnodeExpr->location = ByteCodeGenerator::ReturnRegister;
  9288. }
  9289. Emit(pnode->sxReturn.pnodeExpr, byteCodeGenerator, funcInfo, fReturnValue);
  9290. if (pnode->sxReturn.pnodeExpr->location != ByteCodeGenerator::ReturnRegister)
  9291. {
  9292. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, pnode->sxReturn.pnodeExpr->location);
  9293. }
  9294. funcInfo->GetParsedFunctionBody()->SetHasNoExplicitReturnValue(false);
  9295. }
  9296. else
  9297. {
  9298. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, ByteCodeGenerator::ReturnRegister);
  9299. }
  9300. if (funcInfo->IsClassConstructor())
  9301. {
  9302. // return expr; // becomes like below:
  9303. //
  9304. // if (IsObject(expr)) {
  9305. // return expr;
  9306. // } else if (IsBaseClassConstructor) {
  9307. // return this;
  9308. // } else if (!IsUndefined(expr)) {
  9309. // throw TypeError;
  9310. // }
  9311. Js::ByteCodeLabel returnExprLabel = byteCodeGenerator->Writer()->DefineLabel();
  9312. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, returnExprLabel, ByteCodeGenerator::ReturnRegister);
  9313. if (funcInfo->IsBaseClassConstructor())
  9314. {
  9315. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, funcInfo->thisPointerRegister);
  9316. }
  9317. else
  9318. {
  9319. Js::ByteCodeLabel returnThisLabel = byteCodeGenerator->Writer()->DefineLabel();
  9320. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, returnThisLabel, ByteCodeGenerator::ReturnRegister, funcInfo->undefinedConstantRegister);
  9321. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ClassDerivedConstructorInvalidReturnType));
  9322. byteCodeGenerator->Writer()->MarkLabel(returnThisLabel);
  9323. byteCodeGenerator->EmitClassConstructorEndCode(funcInfo);
  9324. }
  9325. byteCodeGenerator->Writer()->MarkLabel(returnExprLabel);
  9326. }
  9327. if (pnode->sxStmt.grfnop & fnopCleanup)
  9328. {
  9329. EmitJumpCleanup(pnode, nullptr, byteCodeGenerator, funcInfo);
  9330. }
  9331. byteCodeGenerator->Writer()->Br(funcInfo->singleExit);
  9332. byteCodeGenerator->EndStatement(pnode);
  9333. break;
  9334. case knopLabel:
  9335. break;
  9336. // PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  9337. case knopBlock:
  9338. if (pnode->sxBlock.pnodeStmt != nullptr)
  9339. {
  9340. EmitBlock(pnode, byteCodeGenerator, funcInfo, fReturnValue);
  9341. if (pnode->emitLabels)
  9342. {
  9343. byteCodeGenerator->Writer()->MarkLabel(pnode->sxStmt.breakLabel);
  9344. }
  9345. }
  9346. break;
  9347. // PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  9348. case knopWith:
  9349. {
  9350. Assert(pnode->sxWith.pnodeObj != nullptr);
  9351. byteCodeGenerator->StartStatement(pnode);
  9352. // Copy the with object to a temp register (the location assigned to pnode) so that if the with object
  9353. // is overwritten in the body, the lookups are not affected.
  9354. funcInfo->AcquireLoc(pnode);
  9355. Emit(pnode->sxWith.pnodeObj, byteCodeGenerator, funcInfo, false);
  9356. Js::RegSlot regVal = (byteCodeGenerator->GetScriptContext()->GetConfig()->IsES6UnscopablesEnabled()) ? funcInfo->AcquireTmpRegister() : pnode->location;
  9357. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Obj, regVal, pnode->sxWith.pnodeObj->location);
  9358. if (byteCodeGenerator->GetScriptContext()->GetConfig()->IsES6UnscopablesEnabled())
  9359. {
  9360. byteCodeGenerator->Writer()->Reg2(Js::OpCode::NewWithObject, pnode->location, regVal);
  9361. }
  9362. byteCodeGenerator->EndStatement(pnode);
  9363. #ifdef PERF_HINT
  9364. if (PHASE_TRACE1(Js::PerfHintPhase))
  9365. {
  9366. WritePerfHint(PerfHints::HasWithBlock, funcInfo->byteCodeFunction->GetFunctionBody(), byteCodeGenerator->Writer()->GetCurrentOffset() - 1);
  9367. }
  9368. #endif
  9369. if (pnode->sxWith.pnodeBody != nullptr)
  9370. {
  9371. Scope *scope = pnode->sxWith.scope;
  9372. scope->SetLocation(pnode->location);
  9373. byteCodeGenerator->PushScope(scope);
  9374. Js::DebuggerScope *debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnode, Js::DiagExtraScopesType::DiagWithScope, regVal);
  9375. if (byteCodeGenerator->ShouldTrackDebuggerMetadata())
  9376. {
  9377. byteCodeGenerator->Writer()->AddPropertyToDebuggerScope(debuggerScope, regVal, Js::Constants::NoProperty, /*shouldConsumeRegister*/ true, Js::DebuggerScopePropertyFlags_WithObject);
  9378. }
  9379. Emit(pnode->sxWith.pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  9380. funcInfo->ReleaseLoc(pnode->sxWith.pnodeBody);
  9381. byteCodeGenerator->PopScope();
  9382. byteCodeGenerator->RecordEndScopeObject(pnode);
  9383. }
  9384. if (pnode->emitLabels)
  9385. {
  9386. byteCodeGenerator->Writer()->MarkLabel(pnode->sxStmt.breakLabel);
  9387. }
  9388. if (byteCodeGenerator->GetScriptContext()->GetConfig()->IsES6UnscopablesEnabled())
  9389. {
  9390. funcInfo->ReleaseTmpRegister(regVal);
  9391. }
  9392. funcInfo->ReleaseLoc(pnode->sxWith.pnodeObj);
  9393. break;
  9394. }
  9395. // PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  9396. case knopBreak:
  9397. Assert(pnode->sxJump.pnodeTarget->emitLabels);
  9398. byteCodeGenerator->StartStatement(pnode);
  9399. if (pnode->sxStmt.grfnop & fnopCleanup)
  9400. {
  9401. EmitJumpCleanup(pnode, pnode->sxJump.pnodeTarget, byteCodeGenerator, funcInfo);
  9402. }
  9403. byteCodeGenerator->Writer()->Br(pnode->sxJump.pnodeTarget->sxStmt.breakLabel);
  9404. if (pnode->emitLabels)
  9405. {
  9406. byteCodeGenerator->Writer()->MarkLabel(pnode->sxStmt.breakLabel);
  9407. }
  9408. byteCodeGenerator->EndStatement(pnode);
  9409. break;
  9410. case knopContinue:
  9411. Assert(pnode->sxJump.pnodeTarget->emitLabels);
  9412. byteCodeGenerator->StartStatement(pnode);
  9413. if (pnode->sxStmt.grfnop & fnopCleanup)
  9414. {
  9415. EmitJumpCleanup(pnode, pnode->sxJump.pnodeTarget, byteCodeGenerator, funcInfo);
  9416. }
  9417. byteCodeGenerator->Writer()->Br(pnode->sxJump.pnodeTarget->sxStmt.continueLabel);
  9418. byteCodeGenerator->EndStatement(pnode);
  9419. break;
  9420. // PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  9421. case knopSwitch:
  9422. {
  9423. BOOL fHasDefault = false;
  9424. Assert(pnode->sxSwitch.pnodeVal != nullptr);
  9425. byteCodeGenerator->StartStatement(pnode);
  9426. Emit(pnode->sxSwitch.pnodeVal, byteCodeGenerator, funcInfo, false);
  9427. Js::RegSlot regVal = funcInfo->AcquireTmpRegister();
  9428. byteCodeGenerator->Writer()->Reg2(Js::OpCode::BeginSwitch, regVal, pnode->sxSwitch.pnodeVal->location);
  9429. BeginEmitBlock(pnode->sxSwitch.pnodeBlock, byteCodeGenerator, funcInfo);
  9430. byteCodeGenerator->EndStatement(pnode);
  9431. // TODO: if all cases are compile-time constants, emit a switch statement in the byte
  9432. // code so the BE can optimize it.
  9433. ParseNode *pnodeCase;
  9434. for (pnodeCase = pnode->sxSwitch.pnodeCases; pnodeCase; pnodeCase = pnodeCase->sxCase.pnodeNext)
  9435. {
  9436. // Jump to the first case body if this one doesn't match. Make sure any side-effects of the case
  9437. // expression take place regardless.
  9438. pnodeCase->sxCase.labelCase = byteCodeGenerator->Writer()->DefineLabel();
  9439. if (pnodeCase == pnode->sxSwitch.pnodeDefault)
  9440. {
  9441. fHasDefault = true;
  9442. continue;
  9443. }
  9444. Emit(pnodeCase->sxCase.pnodeExpr, byteCodeGenerator, funcInfo, false);
  9445. byteCodeGenerator->Writer()->BrReg2(
  9446. Js::OpCode::Case, pnodeCase->sxCase.labelCase, regVal, pnodeCase->sxCase.pnodeExpr->location);
  9447. funcInfo->ReleaseLoc(pnodeCase->sxCase.pnodeExpr);
  9448. }
  9449. // No explicit case value matches. Jump to the default arm (if any) or break out altogether.
  9450. if (fHasDefault)
  9451. {
  9452. byteCodeGenerator->Writer()->Br(Js::OpCode::EndSwitch, pnode->sxSwitch.pnodeDefault->sxCase.labelCase);
  9453. }
  9454. else
  9455. {
  9456. if (!pnode->emitLabels)
  9457. {
  9458. pnode->sxStmt.breakLabel = byteCodeGenerator->Writer()->DefineLabel();
  9459. }
  9460. byteCodeGenerator->Writer()->Br(Js::OpCode::EndSwitch, pnode->sxStmt.breakLabel);
  9461. }
  9462. // Now emit the case arms to which we jump on matching a case value.
  9463. for (pnodeCase = pnode->sxSwitch.pnodeCases; pnodeCase; pnodeCase = pnodeCase->sxCase.pnodeNext)
  9464. {
  9465. byteCodeGenerator->Writer()->MarkLabel(pnodeCase->sxCase.labelCase);
  9466. Emit(pnodeCase->sxCase.pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  9467. funcInfo->ReleaseLoc(pnodeCase->sxCase.pnodeBody);
  9468. }
  9469. EndEmitBlock(pnode->sxSwitch.pnodeBlock, byteCodeGenerator, funcInfo);
  9470. funcInfo->ReleaseTmpRegister(regVal);
  9471. funcInfo->ReleaseLoc(pnode->sxSwitch.pnodeVal);
  9472. if (!fHasDefault || pnode->emitLabels)
  9473. {
  9474. byteCodeGenerator->Writer()->MarkLabel(pnode->sxStmt.breakLabel);
  9475. }
  9476. break;
  9477. }
  9478. case knopTryCatch:
  9479. {
  9480. Js::ByteCodeLabel catchLabel = (Js::ByteCodeLabel) - 1;
  9481. ParseNode *pnodeTry = pnode->sxTryCatch.pnodeTry;
  9482. Assert(pnodeTry);
  9483. ParseNode *pnodeCatch = pnode->sxTryCatch.pnodeCatch;
  9484. Assert(pnodeCatch);
  9485. catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  9486. // Note: try uses OpCode::Leave which causes a return to parent interpreter thunk,
  9487. // same for catch block. Thus record cross interpreter frame entry/exit records for them.
  9488. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  9489. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  9490. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryCatch, catchLabel);
  9491. if (funcInfo->byteCodeFunction->IsGenerator())
  9492. {
  9493. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  9494. }
  9495. Emit(pnodeTry->sxTry.pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  9496. funcInfo->ReleaseLoc(pnodeTry->sxTry.pnodeBody);
  9497. if (funcInfo->byteCodeFunction->IsGenerator())
  9498. {
  9499. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  9500. }
  9501. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  9502. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  9503. byteCodeGenerator->Writer()->Br(pnode->sxStmt.breakLabel);
  9504. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  9505. Assert(pnodeCatch->sxCatch.pnodeParam);
  9506. ParseNode *pnodeObj = pnodeCatch->sxCatch.pnodeParam;
  9507. Js::RegSlot location;
  9508. bool acquiredTempLocation = false;
  9509. Js::DebuggerScope *debuggerScope = nullptr;
  9510. Js::DebuggerScopePropertyFlags debuggerPropertyFlags = Js::DebuggerScopePropertyFlags_CatchObject;
  9511. bool isPattern = pnodeObj->nop == knopParamPattern;
  9512. if (isPattern)
  9513. {
  9514. location = pnodeObj->sxParamPattern.location;
  9515. }
  9516. else
  9517. {
  9518. location = pnodeObj->sxPid.sym->GetLocation();
  9519. }
  9520. if (location == Js::Constants::NoRegister)
  9521. {
  9522. location = funcInfo->AcquireLoc(pnodeObj);
  9523. acquiredTempLocation = true;
  9524. }
  9525. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, location);
  9526. Scope *scope = pnodeCatch->sxCatch.scope;
  9527. if (isPattern || scope->GetMustInstantiate())
  9528. {
  9529. byteCodeGenerator->PushScope(scope);
  9530. }
  9531. if (scope->GetMustInstantiate())
  9532. {
  9533. Assert(scope->GetLocation() == Js::Constants::NoRegister);
  9534. if (scope->GetIsObject())
  9535. {
  9536. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnode, Js::DiagCatchScopeInObject, funcInfo->InnerScopeToRegSlot(scope));
  9537. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::NewPseudoScope, scope->GetInnerScopeIndex());
  9538. }
  9539. else
  9540. {
  9541. int index = Js::DebuggerScope::InvalidScopeIndex;
  9542. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnode, Js::DiagCatchScopeInSlot, funcInfo->InnerScopeToRegSlot(scope), &index);
  9543. byteCodeGenerator->Writer()->Num3(Js::OpCode::NewInnerScopeSlots, scope->GetInnerScopeIndex(), scope->GetScopeSlotCount() + Js::ScopeSlots::FirstSlotIndex, index);
  9544. }
  9545. }
  9546. else
  9547. {
  9548. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnode, Js::DiagCatchScopeDirect, location);
  9549. }
  9550. auto ParamTrackAndInitialization = [&](Symbol *sym, bool initializeParam, Js::RegSlot location)
  9551. {
  9552. if (sym->IsInSlot(funcInfo))
  9553. {
  9554. Assert(scope->GetMustInstantiate());
  9555. if (scope->GetIsObject())
  9556. {
  9557. Js::OpCode op = (sym->GetDecl()->nop == knopLetDecl) ? Js::OpCode::InitUndeclLetFld :
  9558. byteCodeGenerator->GetInitFldOp(scope, scope->GetLocation(), funcInfo, false);
  9559. Js::PropertyId propertyId = sym->EnsurePosition(byteCodeGenerator);
  9560. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
  9561. byteCodeGenerator->Writer()->ElementPIndexed(op, location, scope->GetInnerScopeIndex(), cacheId);
  9562. byteCodeGenerator->TrackActivationObjectPropertyForDebugger(debuggerScope, sym, debuggerPropertyFlags);
  9563. }
  9564. else
  9565. {
  9566. byteCodeGenerator->TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(byteCodeGenerator), debuggerPropertyFlags);
  9567. if (initializeParam)
  9568. {
  9569. byteCodeGenerator->EmitLocalPropInit(location, sym, funcInfo);
  9570. }
  9571. else
  9572. {
  9573. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  9574. byteCodeGenerator->Writer()->Reg1(Js::OpCode::InitUndecl, tmpReg);
  9575. byteCodeGenerator->EmitLocalPropInit(tmpReg, sym, funcInfo);
  9576. funcInfo->ReleaseTmpRegister(tmpReg);
  9577. }
  9578. }
  9579. }
  9580. else
  9581. {
  9582. byteCodeGenerator->TrackRegisterPropertyForDebugger(debuggerScope, sym, funcInfo, debuggerPropertyFlags);
  9583. if (initializeParam)
  9584. {
  9585. byteCodeGenerator->EmitLocalPropInit(location, sym, funcInfo);
  9586. }
  9587. else
  9588. {
  9589. byteCodeGenerator->Writer()->Reg1(Js::OpCode::InitUndecl, location);
  9590. }
  9591. }
  9592. };
  9593. if (isPattern)
  9594. {
  9595. Parser::MapBindIdentifier(pnodeObj->sxParamPattern.pnode1, [&](ParseNodePtr item)
  9596. {
  9597. ParamTrackAndInitialization(item->sxVar.sym, false /*initializeParam*/, item->sxVar.sym->GetLocation());
  9598. });
  9599. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  9600. // Now emitting bytecode for destructuring pattern
  9601. byteCodeGenerator->StartStatement(pnodeCatch);
  9602. ParseNodePtr pnode1 = pnodeObj->sxParamPattern.pnode1;
  9603. Assert(pnode1->IsPattern());
  9604. EmitAssignment(nullptr, pnode1, location, byteCodeGenerator, funcInfo);
  9605. byteCodeGenerator->EndStatement(pnodeCatch);
  9606. }
  9607. else
  9608. {
  9609. ParamTrackAndInitialization(pnodeObj->sxPid.sym, true /*initializeParam*/, location);
  9610. if (scope->GetMustInstantiate())
  9611. {
  9612. pnodeObj->sxPid.sym->SetIsGlobalCatch(true);
  9613. }
  9614. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  9615. // Allow a debugger to stop on the 'catch (e)'
  9616. byteCodeGenerator->StartStatement(pnodeCatch);
  9617. byteCodeGenerator->Writer()->Empty(Js::OpCode::Nop);
  9618. byteCodeGenerator->EndStatement(pnodeCatch);
  9619. }
  9620. ByteCodeGenerator::TryScopeRecord tryRecForCatch(Js::OpCode::ResumeCatch, catchLabel);
  9621. if (funcInfo->byteCodeFunction->IsGenerator())
  9622. {
  9623. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForCatch);
  9624. }
  9625. Emit(pnodeCatch->sxCatch.pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  9626. if (funcInfo->byteCodeFunction->IsGenerator())
  9627. {
  9628. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  9629. }
  9630. if (scope->GetMustInstantiate() || isPattern)
  9631. {
  9632. byteCodeGenerator->PopScope();
  9633. }
  9634. byteCodeGenerator->RecordEndScopeObject(pnode);
  9635. funcInfo->ReleaseLoc(pnodeCatch->sxCatch.pnodeBody);
  9636. if (acquiredTempLocation)
  9637. {
  9638. funcInfo->ReleaseLoc(pnodeObj);
  9639. }
  9640. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  9641. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  9642. byteCodeGenerator->Writer()->MarkLabel(pnode->sxStmt.breakLabel);
  9643. break;
  9644. }
  9645. case knopTryFinally:
  9646. {
  9647. Js::ByteCodeLabel finallyLabel = (Js::ByteCodeLabel) - 1;
  9648. ParseNode *pnodeTry = pnode->sxTryFinally.pnodeTry;
  9649. Assert(pnodeTry);
  9650. ParseNode *pnodeFinally = pnode->sxTryFinally.pnodeFinally;
  9651. Assert(pnodeFinally);
  9652. // If we yield from the finally block after an exception, we have to store the exception object for the future next call.
  9653. // When we yield from the Try-Finally the offset to the end of the Try block is needed for the branch instruction.
  9654. Js::RegSlot regException = Js::Constants::NoRegister;
  9655. Js::RegSlot regOffset = Js::Constants::NoRegister;
  9656. finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  9657. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  9658. // [CONSIDER][aneeshd] Ideally the TryFinallyWithYield opcode needs to be used only if there is a yield expression.
  9659. // For now, if the function is generator we are using the TryFinallyWithYield.
  9660. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryFinallyWithYield, finallyLabel);
  9661. if (funcInfo->byteCodeFunction->IsGenerator())
  9662. {
  9663. regException = funcInfo->AcquireTmpRegister();
  9664. regOffset = funcInfo->AcquireTmpRegister();
  9665. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  9666. tryRecForTry.reg1 = regException;
  9667. tryRecForTry.reg2 = regOffset;
  9668. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  9669. }
  9670. else
  9671. {
  9672. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  9673. }
  9674. Emit(pnodeTry->sxTry.pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  9675. funcInfo->ReleaseLoc(pnodeTry->sxTry.pnodeBody);
  9676. if (funcInfo->byteCodeFunction->IsGenerator())
  9677. {
  9678. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  9679. }
  9680. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  9681. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  9682. // Note: although we don't use OpCode::Leave for finally block,
  9683. // OpCode::LeaveNull causes a return to parent interpreter thunk.
  9684. // This has to be on offset prior to offset of 1st statement of finally.
  9685. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  9686. byteCodeGenerator->Writer()->Br(pnode->sxStmt.breakLabel);
  9687. byteCodeGenerator->Writer()->MarkLabel(finallyLabel);
  9688. ByteCodeGenerator::TryScopeRecord tryRecForFinally(Js::OpCode::ResumeFinally, finallyLabel, regException, regOffset);
  9689. if (funcInfo->byteCodeFunction->IsGenerator())
  9690. {
  9691. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForFinally);
  9692. }
  9693. Emit(pnodeFinally->sxFinally.pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  9694. funcInfo->ReleaseLoc(pnodeFinally->sxFinally.pnodeBody);
  9695. if (funcInfo->byteCodeFunction->IsGenerator())
  9696. {
  9697. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  9698. funcInfo->ReleaseTmpRegister(regOffset);
  9699. funcInfo->ReleaseTmpRegister(regException);
  9700. }
  9701. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  9702. byteCodeGenerator->Writer()->Empty(Js::OpCode::LeaveNull);
  9703. byteCodeGenerator->Writer()->MarkLabel(pnode->sxStmt.breakLabel);
  9704. break;
  9705. }
  9706. case knopThrow:
  9707. byteCodeGenerator->StartStatement(pnode);
  9708. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  9709. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Throw, pnode->sxUni.pnode1->location);
  9710. funcInfo->ReleaseLoc(pnode->sxUni.pnode1);
  9711. byteCodeGenerator->EndStatement(pnode);
  9712. break;
  9713. case knopYieldLeaf:
  9714. byteCodeGenerator->StartStatement(pnode);
  9715. funcInfo->AcquireLoc(pnode);
  9716. EmitYield(funcInfo->undefinedConstantRegister, pnode->location, byteCodeGenerator, funcInfo);
  9717. byteCodeGenerator->EndStatement(pnode);
  9718. break;
  9719. case knopAwait:
  9720. case knopYield:
  9721. byteCodeGenerator->StartStatement(pnode);
  9722. funcInfo->AcquireLoc(pnode);
  9723. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  9724. EmitYield(pnode->sxUni.pnode1->location, pnode->location, byteCodeGenerator, funcInfo);
  9725. funcInfo->ReleaseLoc(pnode->sxUni.pnode1);
  9726. byteCodeGenerator->EndStatement(pnode);
  9727. break;
  9728. case knopYieldStar:
  9729. byteCodeGenerator->StartStatement(pnode);
  9730. EmitYieldStar(pnode, byteCodeGenerator, funcInfo);
  9731. byteCodeGenerator->EndStatement(pnode);
  9732. break;
  9733. case knopAsyncSpawn:
  9734. EmitBinary(Js::OpCode::AsyncSpawn, pnode, byteCodeGenerator, funcInfo);
  9735. break;
  9736. case knopExportDefault:
  9737. Emit(pnode->sxExportDefault.pnodeExpr, byteCodeGenerator, funcInfo, false);
  9738. byteCodeGenerator->EmitAssignmentToDefaultModuleExport(pnode->sxExportDefault.pnodeExpr, funcInfo);
  9739. funcInfo->ReleaseLoc(pnode->sxExportDefault.pnodeExpr);
  9740. pnode = pnode->sxExportDefault.pnodeExpr;
  9741. break;
  9742. default:
  9743. AssertMsg(0, "emit unhandled pnode op");
  9744. break;
  9745. }
  9746. if (fReturnValue && IsExpressionStatement(pnode, byteCodeGenerator->GetScriptContext()))
  9747. {
  9748. // If this statement may produce the global function's return value, copy its result to the return register.
  9749. // fReturnValue implies global function, which implies that "return" is a parse error.
  9750. Assert(funcInfo->IsGlobalFunction());
  9751. Assert(pnode->nop != knopReturn);
  9752. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, pnode->location);
  9753. }
  9754. }