ByteCodeEmitter.cpp 413 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722
  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. BOOL MayHaveSideEffectOnNode(ParseNode *pnode, ParseNode *pnodeSE)
  21. {
  22. // Try to determine whether pnodeSE may kill the named var represented by pnode.
  23. if (pnode->nop == knopComputedName)
  24. {
  25. pnode = pnode->sxUni.pnode1;
  26. }
  27. if (pnode->nop != knopName)
  28. {
  29. // Only investigating named vars here.
  30. return false;
  31. }
  32. uint fnop = ParseNode::Grfnop(pnodeSE->nop);
  33. if (fnop & fnopLeaf)
  34. {
  35. // pnodeSE is a leaf and can't kill anything.
  36. return false;
  37. }
  38. if (fnop & fnopAsg)
  39. {
  40. // pnodeSE is an assignment (=, ++, +=, etc.)
  41. // Trying to examine the LHS of pnodeSE caused small perf regressions,
  42. // maybe because of code layout or some other subtle effect.
  43. return true;
  44. }
  45. if (fnop & fnopUni)
  46. {
  47. // pnodeSE is a unary op, so recurse to the source (if present - e.g., [] may have no opnd).
  48. if (pnodeSE->nop == knopTempRef)
  49. {
  50. return false;
  51. }
  52. else
  53. {
  54. return pnodeSE->sxUni.pnode1 && MayHaveSideEffectOnNode(pnode, pnodeSE->sxUni.pnode1);
  55. }
  56. }
  57. else if (fnop & fnopBin)
  58. {
  59. // pnodeSE is a binary (or ternary) op, so recurse to the sources (if present).
  60. if (pnodeSE->nop == knopQmark)
  61. {
  62. return MayHaveSideEffectOnNode(pnode, pnodeSE->sxTri.pnode1) ||
  63. MayHaveSideEffectOnNode(pnode, pnodeSE->sxTri.pnode2) ||
  64. MayHaveSideEffectOnNode(pnode, pnodeSE->sxTri.pnode3);
  65. }
  66. else if (pnodeSE->nop == knopCall || pnodeSE->nop == knopNew)
  67. {
  68. return MayHaveSideEffectOnNode(pnode, pnodeSE->sxCall.pnodeTarget) ||
  69. (pnodeSE->sxCall.pnodeArgs && MayHaveSideEffectOnNode(pnode, pnodeSE->sxCall.pnodeArgs));
  70. }
  71. else
  72. {
  73. return MayHaveSideEffectOnNode(pnode, pnodeSE->sxBin.pnode1) ||
  74. (pnodeSE->sxBin.pnode2 && MayHaveSideEffectOnNode(pnode, pnodeSE->sxBin.pnode2));
  75. }
  76. }
  77. else if (pnodeSE->nop == knopList)
  78. {
  79. return true;
  80. }
  81. return false;
  82. }
  83. bool IsCallOfConstants(ParseNode *pnode);
  84. bool BlockHasOwnScope(ParseNode* pnodeBlock, ByteCodeGenerator *byteCodeGenerator);
  85. bool CreateNativeArrays(ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  86. bool IsArguments(ParseNode *pnode)
  87. {
  88. for (;;)
  89. {
  90. switch (pnode->nop)
  91. {
  92. case knopName:
  93. return pnode->sxPid.sym && pnode->sxPid.sym->GetIsArguments();
  94. case knopCall:
  95. case knopNew:
  96. if (IsArguments(pnode->sxCall.pnodeTarget))
  97. {
  98. return true;
  99. }
  100. if (pnode->sxCall.pnodeArgs)
  101. {
  102. ParseNode *pnodeArg = pnode->sxCall.pnodeArgs;
  103. while (pnodeArg->nop == knopList)
  104. {
  105. if (IsArguments(pnodeArg->sxBin.pnode1))
  106. return true;
  107. pnodeArg = pnodeArg->sxBin.pnode2;
  108. }
  109. pnode = pnodeArg;
  110. break;
  111. }
  112. return false;
  113. case knopArray:
  114. if (pnode->sxArrLit.arrayOfNumbers || pnode->sxArrLit.count == 0)
  115. {
  116. return false;
  117. }
  118. pnode = pnode->sxUni.pnode1;
  119. break;
  120. case knopQmark:
  121. if (IsArguments(pnode->sxTri.pnode1) || IsArguments(pnode->sxTri.pnode2))
  122. {
  123. return true;
  124. }
  125. pnode = pnode->sxTri.pnode3;
  126. break;
  127. //
  128. // Cases where we don't check for "arguments" yet.
  129. // Assume that they might have it. Disable the optimization is such scenarios
  130. //
  131. case knopList:
  132. case knopObject:
  133. case knopVarDecl:
  134. case knopConstDecl:
  135. case knopLetDecl:
  136. case knopFncDecl:
  137. case knopClassDecl:
  138. case knopFor:
  139. case knopIf:
  140. case knopDoWhile:
  141. case knopWhile:
  142. case knopForIn:
  143. case knopForOf:
  144. case knopReturn:
  145. case knopBlock:
  146. case knopBreak:
  147. case knopContinue:
  148. case knopLabel:
  149. case knopTypeof:
  150. case knopThrow:
  151. case knopWith:
  152. case knopFinally:
  153. case knopTry:
  154. case knopTryCatch:
  155. case knopTryFinally:
  156. return true;
  157. default:
  158. {
  159. uint flags = ParseNode::Grfnop(pnode->nop);
  160. if (flags&fnopUni)
  161. {
  162. Assert(pnode->sxUni.pnode1);
  163. pnode = pnode->sxUni.pnode1;
  164. break;
  165. }
  166. else if (flags&fnopBin)
  167. {
  168. Assert(pnode->sxBin.pnode1 && pnode->sxBin.pnode2);
  169. if (IsArguments(pnode->sxBin.pnode1))
  170. {
  171. return true;
  172. }
  173. pnode = pnode->sxBin.pnode2;
  174. break;
  175. }
  176. return false;
  177. }
  178. }
  179. }
  180. }
  181. bool ApplyEnclosesArgs(ParseNode* fncDecl, ByteCodeGenerator* byteCodeGenerator);
  182. void Emit(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue, bool isConstructorCall = false, ParseNode *bindPnode = nullptr);
  183. void EmitComputedFunctionNameVar(ParseNode *nameNode, ParseNode *exprNode, ByteCodeGenerator *byteCodeGenerator);
  184. void EmitBinaryOpnds(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  185. bool IsExpressionStatement(ParseNode* stmt, const Js::ScriptContext *const scriptContext);
  186. void EmitInvoke(Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  187. void EmitInvoke(Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot arg1Location);
  188. static const Js::OpCode nopToOp[knopLim] =
  189. {
  190. #define OP(x) Br##x##_A
  191. #define PTNODE(nop,sn,pc,nk,grfnop,json) Js::OpCode::pc,
  192. #include "ptlist.h"
  193. };
  194. static const Js::OpCode nopToCMOp[knopLim] =
  195. {
  196. #define OP(x) Cm##x##_A
  197. #define PTNODE(nop,sn,pc,nk,grfnop,json) Js::OpCode::pc,
  198. #include "ptlist.h"
  199. };
  200. Js::OpCode ByteCodeGenerator::ToChkUndeclOp(Js::OpCode op) const
  201. {
  202. switch(op)
  203. {
  204. case Js::OpCode::StLocalSlot:
  205. return Js::OpCode::StLocalSlotChkUndecl;
  206. case Js::OpCode::StInnerSlot:
  207. return Js::OpCode::StInnerSlotChkUndecl;
  208. case Js::OpCode::StEnvSlot:
  209. return Js::OpCode::StEnvSlotChkUndecl;
  210. case Js::OpCode::StObjSlot:
  211. return Js::OpCode::StObjSlotChkUndecl;
  212. case Js::OpCode::StLocalObjSlot:
  213. return Js::OpCode::StLocalObjSlotChkUndecl;
  214. case Js::OpCode::StInnerObjSlot:
  215. return Js::OpCode::StInnerObjSlotChkUndecl;
  216. case Js::OpCode::StEnvObjSlot:
  217. return Js::OpCode::StEnvObjSlotChkUndecl;
  218. default:
  219. AssertMsg(false, "Unknown opcode for chk undecl mapping");
  220. return Js::OpCode::InvalidOpCode;
  221. }
  222. }
  223. // Tracks a register slot let/const property for the passed in debugger block/catch scope.
  224. // debuggerScope - The scope to add the variable to.
  225. // symbol - The symbol that represents the register property.
  226. // funcInfo - The function info used to store the property into the tracked debugger register slot list.
  227. // flags - The flags to assign to the property.
  228. // isFunctionDeclaration - Whether or not the register is a function declaration, which requires that its byte code offset be updated immediately.
  229. void ByteCodeGenerator::TrackRegisterPropertyForDebugger(
  230. Js::DebuggerScope *debuggerScope,
  231. Symbol *symbol,
  232. FuncInfo *funcInfo,
  233. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  234. bool isFunctionDeclaration /*= false*/)
  235. {
  236. Assert(debuggerScope);
  237. Assert(symbol);
  238. Assert(funcInfo);
  239. Js::RegSlot location = symbol->GetLocation();
  240. Js::DebuggerScope *correctDebuggerScope = debuggerScope;
  241. if (debuggerScope->scopeType != Js::DiagExtraScopesType::DiagBlockScopeDirect && debuggerScope->scopeType != Js::DiagExtraScopesType::DiagCatchScopeDirect)
  242. {
  243. // We have to get the appropriate scope and add property over there.
  244. // Make sure the scope is created whether we're in debug mode or not, because we
  245. // need the empty scopes present during reparsing for debug mode.
  246. correctDebuggerScope = debuggerScope->GetSiblingScope(location, Writer()->GetFunctionWrite());
  247. }
  248. if (this->ShouldTrackDebuggerMetadata() && !symbol->GetIsTrackedForDebugger())
  249. {
  250. // Only track the property if we're in debug mode since it's only needed by the debugger.
  251. Js::PropertyId propertyId = symbol->EnsurePosition(this);
  252. this->Writer()->AddPropertyToDebuggerScope(
  253. correctDebuggerScope,
  254. location,
  255. propertyId,
  256. /*shouldConsumeRegister*/ true,
  257. flags,
  258. isFunctionDeclaration);
  259. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  260. byteCodeFunction->InsertSymbolToRegSlotList(location, propertyId, funcInfo->varRegsCount);
  261. symbol->SetIsTrackedForDebugger(true);
  262. }
  263. }
  264. void ByteCodeGenerator::TrackActivationObjectPropertyForDebugger(
  265. Js::DebuggerScope *debuggerScope,
  266. Symbol *symbol,
  267. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  268. bool isFunctionDeclaration /*= false*/)
  269. {
  270. Assert(debuggerScope);
  271. Assert(symbol);
  272. // Only need to track activation object properties in debug mode.
  273. if (ShouldTrackDebuggerMetadata() && !symbol->GetIsTrackedForDebugger())
  274. {
  275. Js::RegSlot location = symbol->GetLocation();
  276. Js::PropertyId propertyId = symbol->EnsurePosition(this);
  277. this->Writer()->AddPropertyToDebuggerScope(
  278. debuggerScope,
  279. location,
  280. propertyId,
  281. /*shouldConsumeRegister*/ false,
  282. flags,
  283. isFunctionDeclaration);
  284. symbol->SetIsTrackedForDebugger(true);
  285. }
  286. }
  287. void ByteCodeGenerator::TrackSlotArrayPropertyForDebugger(
  288. Js::DebuggerScope *debuggerScope,
  289. Symbol* symbol,
  290. Js::PropertyId propertyId,
  291. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  292. bool isFunctionDeclaration /*= false*/)
  293. {
  294. // Note: Slot array properties are tracked even in non-debug mode in order to support slot array serialization
  295. // of let/const variables between non-debug and debug mode (for example, when a slot array var escapes and is retrieved
  296. // after a debugger attach or for WWA apps). They are also needed for heap enumeration.
  297. Assert(debuggerScope);
  298. Assert(symbol);
  299. if (!symbol->GetIsTrackedForDebugger())
  300. {
  301. Js::RegSlot location = symbol->GetScopeSlot();
  302. Assert(location != Js::Constants::NoRegister);
  303. Assert(propertyId != Js::Constants::NoProperty);
  304. this->Writer()->AddPropertyToDebuggerScope(
  305. debuggerScope,
  306. location,
  307. propertyId,
  308. /*shouldConsumeRegister*/ false,
  309. flags,
  310. isFunctionDeclaration);
  311. symbol->SetIsTrackedForDebugger(true);
  312. }
  313. }
  314. // Tracks a function declaration inside a block scope for the debugger metadata's current scope (let binding).
  315. void ByteCodeGenerator::TrackFunctionDeclarationPropertyForDebugger(Symbol *functionDeclarationSymbol, FuncInfo *funcInfoParent)
  316. {
  317. Assert(functionDeclarationSymbol);
  318. Assert(funcInfoParent);
  319. AssertMsg(functionDeclarationSymbol->GetIsBlockVar(), "We should only track inner function let bindings for the debugger.");
  320. // Note: we don't have to check symbol->GetIsTrackedForDebugger, as we are not doing actual work here,
  321. // which is done in other Track* functions that we call.
  322. if (functionDeclarationSymbol->IsInSlot(funcInfoParent))
  323. {
  324. if (functionDeclarationSymbol->GetScope()->GetIsObject())
  325. {
  326. this->TrackActivationObjectPropertyForDebugger(
  327. this->Writer()->GetCurrentDebuggerScope(),
  328. functionDeclarationSymbol,
  329. Js::DebuggerScopePropertyFlags_None,
  330. true /*isFunctionDeclaration*/);
  331. }
  332. else
  333. {
  334. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  335. // Note that slot array inner function bindings are tracked even in non-debug mode in order
  336. // to keep the lifetime of the closure binding that could escape around for heap enumeration.
  337. functionDeclarationSymbol->EnsureScopeSlot(funcInfoParent);
  338. functionDeclarationSymbol->EnsurePosition(this);
  339. this->TrackSlotArrayPropertyForDebugger(
  340. this->Writer()->GetCurrentDebuggerScope(),
  341. functionDeclarationSymbol,
  342. functionDeclarationSymbol->GetPosition(),
  343. Js::DebuggerScopePropertyFlags_None,
  344. true /*isFunctionDeclaration*/);
  345. }
  346. }
  347. else
  348. {
  349. this->TrackRegisterPropertyForDebugger(
  350. this->Writer()->GetCurrentDebuggerScope(),
  351. functionDeclarationSymbol,
  352. funcInfoParent,
  353. Js::DebuggerScopePropertyFlags_None,
  354. true /*isFunctionDeclaration*/);
  355. }
  356. }
  357. // Updates the byte code offset of the property with the passed in location and ID.
  358. // Used to track let/const variables that are in the dead zone debugger side.
  359. // location - The activation object, scope slot index, or register location for the property.
  360. // propertyId - The ID of the property to update.
  361. // shouldConsumeRegister - Whether or not the a register should be consumed (used for reg slot locations).
  362. void ByteCodeGenerator::UpdateDebuggerPropertyInitializationOffset(Js::RegSlot location, Js::PropertyId propertyId, bool shouldConsumeRegister)
  363. {
  364. Assert(this->Writer());
  365. Js::DebuggerScope* currentDebuggerScope = this->Writer()->GetCurrentDebuggerScope();
  366. Assert(currentDebuggerScope);
  367. if (currentDebuggerScope != nullptr)
  368. {
  369. this->Writer()->UpdateDebuggerPropertyInitializationOffset(
  370. currentDebuggerScope,
  371. location,
  372. propertyId,
  373. shouldConsumeRegister);
  374. }
  375. }
  376. void ByteCodeGenerator::LoadHeapArguments(FuncInfo *funcInfo)
  377. {
  378. if (funcInfo->GetHasCachedScope())
  379. {
  380. this->LoadCachedHeapArguments(funcInfo);
  381. }
  382. else
  383. {
  384. this->LoadUncachedHeapArguments(funcInfo);
  385. }
  386. }
  387. void GetFormalArgsArray(ByteCodeGenerator *byteCodeGenerator, FuncInfo * funcInfo, Js::PropertyIdArray *propIds)
  388. {
  389. Assert(funcInfo);
  390. Assert(propIds);
  391. Assert(byteCodeGenerator);
  392. bool hadDuplicates = false;
  393. Js::ArgSlot i = 0;
  394. auto processArg = [&](ParseNode *pnode)
  395. {
  396. if (pnode->IsVarLetOrConst())
  397. {
  398. Assert(i < propIds->count);
  399. Symbol *sym = pnode->sxVar.sym;
  400. Assert(sym);
  401. Js::PropertyId symPos = sym->EnsurePosition(byteCodeGenerator);
  402. //
  403. // Check if the function has any same name parameters
  404. // For the same name param, only the last one will be passed the correct propertyid
  405. // For remaining dup param names, pass Constants::NoProperty
  406. //
  407. for (Js::ArgSlot j = 0; j < i; j++)
  408. {
  409. if (propIds->elements[j] == symPos)
  410. {
  411. // Found a dup parameter name
  412. propIds->elements[j] = Js::Constants::NoProperty;
  413. hadDuplicates = true;
  414. break;
  415. }
  416. }
  417. propIds->elements[i] = symPos;
  418. }
  419. else
  420. {
  421. propIds->elements[i] = Js::Constants::NoProperty;
  422. }
  423. ++i;
  424. };
  425. MapFormals(funcInfo->root, processArg);
  426. propIds->hadDuplicates = hadDuplicates;
  427. }
  428. void ByteCodeGenerator::LoadUncachedHeapArguments(FuncInfo *funcInfo)
  429. {
  430. Assert(funcInfo->GetHasHeapArguments());
  431. Scope *scope = funcInfo->GetBodyScope();
  432. Assert(scope);
  433. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  434. Assert(argSym && argSym->GetIsArguments());
  435. Js::RegSlot argumentsLoc = argSym->GetLocation();
  436. Js::RegSlot propIdsLoc = funcInfo->nullConstantRegister;
  437. Js::OpCode opcode = funcInfo->root->sxFnc.IsSimpleParameterList() ? Js::OpCode::LdHeapArguments : Js::OpCode::LdLetHeapArguments;
  438. bool hasRest = funcInfo->root->sxFnc.pnodeRest != nullptr;
  439. uint count = funcInfo->inArgsCount + (hasRest ? 1 : 0) - 1;
  440. if (count == 0)
  441. {
  442. // If no formals to function (only "this"), then no need to create the scope object.
  443. // Leave both the arguments location and the propertyIds location as null.
  444. Assert(funcInfo->root->sxFnc.pnodeArgs == nullptr && !hasRest);
  445. }
  446. else if (!NeedScopeObjectForArguments(funcInfo, funcInfo->root))
  447. {
  448. // We may not need a scope object for arguments, e.g. strict mode with no eval.
  449. }
  450. else if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  451. {
  452. // Pass the frame object and ID array to the runtime, and put the resulting Arguments object
  453. // at the expected location.
  454. propIdsLoc = argumentsLoc;
  455. Js::PropertyIdArray *propIds = AnewPlus(GetAllocator(), count * sizeof(Js::PropertyId), Js::PropertyIdArray, count);
  456. GetFormalArgsArray(this, funcInfo, propIds);
  457. // Generate the opcode with propIds
  458. Writer()->Auxiliary(
  459. Js::OpCode::LdPropIds,
  460. propIdsLoc,
  461. propIds,
  462. sizeof(Js::PropertyIdArray) + count * sizeof(Js::PropertyId),
  463. count);
  464. AdeletePlus(GetAllocator(), count * sizeof(Js::PropertyId), propIds);
  465. }
  466. this->m_writer.Reg2(opcode, argumentsLoc, propIdsLoc);
  467. EmitLocalPropInit(argSym->GetLocation(), argSym, funcInfo);
  468. }
  469. void ByteCodeGenerator::LoadCachedHeapArguments(FuncInfo *funcInfo)
  470. {
  471. Assert(funcInfo->GetHasHeapArguments());
  472. Scope *scope = funcInfo->GetBodyScope();
  473. Assert(scope);
  474. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  475. Assert(argSym && argSym->GetIsArguments());
  476. Js::RegSlot argumentsLoc = argSym->GetLocation();
  477. Js::OpCode op = funcInfo->root->sxFnc.IsSimpleParameterList() ? Js::OpCode::LdHeapArgsCached : Js::OpCode::LdLetHeapArgsCached;
  478. this->m_writer.Reg1(op, argumentsLoc);
  479. EmitLocalPropInit(argumentsLoc, argSym, funcInfo);
  480. }
  481. Js::JavascriptArray* ByteCodeGenerator::BuildArrayFromStringList(ParseNode* stringNodeList, uint arrayLength, Js::ScriptContext* scriptContext)
  482. {
  483. Assert(stringNodeList);
  484. uint index = 0;
  485. Js::Var str;
  486. IdentPtr pid;
  487. Js::JavascriptArray* pArr = scriptContext->GetLibrary()->CreateArray(arrayLength);
  488. while (stringNodeList->nop == knopList)
  489. {
  490. Assert(stringNodeList->sxBin.pnode1->nop == knopStr);
  491. pid = stringNodeList->sxBin.pnode1->sxPid.pid;
  492. str = Js::JavascriptString::NewCopyBuffer(pid->Psz(), pid->Cch(), scriptContext);
  493. pArr->SetItemWithAttributes(index, str, PropertyEnumerable);
  494. stringNodeList = stringNodeList->sxBin.pnode2;
  495. index++;
  496. }
  497. Assert(stringNodeList->nop == knopStr);
  498. pid = stringNodeList->sxPid.pid;
  499. str = Js::JavascriptString::NewCopyBuffer(pid->Psz(), pid->Cch(), scriptContext);
  500. pArr->SetItemWithAttributes(index, str, PropertyEnumerable);
  501. return pArr;
  502. }
  503. // For now, this just assigns field ids for the current script.
  504. // Later, we will combine this information with the global field id map.
  505. // This temporary code will not work if a global member is accessed both with and without a LHS.
  506. void ByteCodeGenerator::AssignPropertyIds(Js::ParseableFunctionInfo* functionInfo)
  507. {
  508. globalScope->ForEachSymbol([this, functionInfo](Symbol * sym)
  509. {
  510. this->AssignPropertyId(sym, functionInfo);
  511. });
  512. }
  513. void ByteCodeGenerator::InitBlockScopedContent(ParseNode *pnodeBlock, Js::DebuggerScope* debuggerScope, FuncInfo *funcInfo)
  514. {
  515. Assert(pnodeBlock->nop == knopBlock);
  516. auto genBlockInit = [this, debuggerScope, funcInfo](ParseNode *pnode)
  517. {
  518. // Only check if the scope is valid when let/const vars are in the scope. If there are no let/const vars,
  519. // the debugger scope will not be created.
  520. AssertMsg(debuggerScope, "Missing a case of scope tracking in BeginEmitBlock.");
  521. FuncInfo *funcInfo = this->TopFuncInfo();
  522. Symbol *sym = pnode->sxVar.sym;
  523. Scope *scope = sym->GetScope();
  524. if (sym->GetIsGlobal())
  525. {
  526. Js::PropertyId propertyId = sym->EnsurePosition(this);
  527. if (this->flags & fscrEval)
  528. {
  529. AssertMsg(this->IsConsoleScopeEval(), "Let/Consts cannot be in global scope outside of console eval");
  530. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ? Js::OpCode::InitUndeclConsoleConstFld : Js::OpCode::InitUndeclConsoleLetFld;
  531. this->m_writer.ElementScopedU(op, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  532. }
  533. else
  534. {
  535. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  536. Js::OpCode::InitUndeclRootConstFld : Js::OpCode::InitUndeclRootLetFld;
  537. this->m_writer.ElementRootU(op, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  538. }
  539. }
  540. else if (sym->IsInSlot(funcInfo))
  541. {
  542. if (scope->GetIsObject())
  543. {
  544. Js::RegSlot scopeLocation = scope->GetLocation();
  545. Js::PropertyId propertyId = sym->EnsurePosition(this);
  546. if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  547. {
  548. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  549. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  550. Js::OpCode::InitUndeclLocalConstFld : Js::OpCode::InitUndeclLocalLetFld;
  551. this->m_writer.ElementP(op, ByteCodeGenerator::ReturnRegister, cacheId);
  552. }
  553. else
  554. {
  555. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
  556. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  557. Js::OpCode::InitUndeclConstFld : Js::OpCode::InitUndeclLetFld;
  558. this->m_writer.ElementPIndexed(op, ByteCodeGenerator::ReturnRegister, scope->GetInnerScopeIndex(), cacheId);
  559. }
  560. TrackActivationObjectPropertyForDebugger(debuggerScope, sym, pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  561. }
  562. else if (CONFIG_FLAG(TDZ))
  563. {
  564. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  565. this->m_writer.Reg1(Js::OpCode::InitUndecl, tmpReg);
  566. this->EmitLocalPropInit(tmpReg, sym, funcInfo);
  567. funcInfo->ReleaseTmpRegister(tmpReg);
  568. // Slot array properties are tracked in non-debug mode as well because they need to stay
  569. // around for heap enumeration and escaping during attach/detach.
  570. TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(this), pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  571. }
  572. }
  573. else
  574. {
  575. if (sym->GetDecl()->sxVar.isSwitchStmtDecl && CONFIG_FLAG(TDZ))
  576. {
  577. // let/const declared in a switch is the only case of a variable that must be checked for
  578. // use-before-declaration dynamically within its own function.
  579. this->m_writer.Reg1(Js::OpCode::InitUndecl, sym->GetLocation());
  580. }
  581. // Syms that begin in register may be delay-captured. In debugger mode, such syms
  582. // will live only in slots, so tell the debugger to find them there.
  583. if (sym->NeedsSlotAlloc(funcInfo))
  584. {
  585. TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(this), pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  586. }
  587. else
  588. {
  589. TrackRegisterPropertyForDebugger(debuggerScope, sym, funcInfo, pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  590. }
  591. }
  592. };
  593. IterateBlockScopedVariables(pnodeBlock, genBlockInit);
  594. }
  595. // Records the start of a debugger scope if the passed in node has any let/const variables (or is not a block node).
  596. // If it has no let/const variables, nullptr will be returned as no scope will be created.
  597. Js::DebuggerScope* ByteCodeGenerator::RecordStartScopeObject(ParseNode *pnodeBlock, Js::DiagExtraScopesType scopeType, Js::RegSlot scopeLocation /*= Js::Constants::NoRegister*/, int* index /*= nullptr*/)
  598. {
  599. Assert(pnodeBlock);
  600. if (pnodeBlock->nop == knopBlock && !pnodeBlock->sxBlock.HasBlockScopedContent())
  601. {
  602. // In order to reduce allocations now that we track debugger scopes in non-debug mode,
  603. // don't add a block to the chain if it has no let/const variables at all.
  604. return nullptr;
  605. }
  606. return this->Writer()->RecordStartScopeObject(scopeType, scopeLocation, index);
  607. }
  608. // Records the end of the current scope, but only if the current block has block scoped content.
  609. // Otherwise, a scope would not have been added (see ByteCodeGenerator::RecordStartScopeObject()).
  610. void ByteCodeGenerator::RecordEndScopeObject(ParseNode *pnodeBlock)
  611. {
  612. Assert(pnodeBlock);
  613. if (pnodeBlock->nop == knopBlock && !pnodeBlock->sxBlock.HasBlockScopedContent())
  614. {
  615. return;
  616. }
  617. this->Writer()->RecordEndScopeObject();
  618. }
  619. void BeginEmitBlock(ParseNode *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  620. {
  621. Js::DebuggerScope* debuggerScope = nullptr;
  622. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  623. {
  624. Scope *scope = pnodeBlock->sxBlock.scope;
  625. byteCodeGenerator->PushScope(scope);
  626. Js::RegSlot scopeLocation = scope->GetLocation();
  627. if (scope->GetMustInstantiate())
  628. {
  629. Assert(scopeLocation == Js::Constants::NoRegister);
  630. scopeLocation = funcInfo->FirstInnerScopeReg() + scope->GetInnerScopeIndex();
  631. if (scope->GetIsObject())
  632. {
  633. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInObject, scopeLocation);
  634. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::NewBlockScope, scope->GetInnerScopeIndex());
  635. }
  636. else
  637. {
  638. int scopeIndex = Js::DebuggerScope::InvalidScopeIndex;
  639. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInSlot, scopeLocation, &scopeIndex);
  640. // TODO: Handle heap enumeration
  641. int scopeSlotCount = scope->GetScopeSlotCount();
  642. byteCodeGenerator->Writer()->Num3(Js::OpCode::NewInnerScopeSlots, scope->GetInnerScopeIndex(), scopeSlotCount + Js::ScopeSlots::FirstSlotIndex, scopeIndex);
  643. }
  644. }
  645. else
  646. {
  647. // In the direct register access case, there is no block scope emitted but we can still track
  648. // the start and end offset of the block. The location registers for let/const variables will still be
  649. // captured along with this range in InitBlockScopedContent().
  650. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeDirect);
  651. }
  652. bool const isGlobalEvalBlockScope = scope->IsGlobalEvalBlockScope();
  653. Js::RegSlot frameDisplayLoc = Js::Constants::NoRegister;
  654. Js::RegSlot tmpInnerEnvReg = Js::Constants::NoRegister;
  655. ParseNodePtr pnodeScope;
  656. for (pnodeScope = pnodeBlock->sxBlock.pnodeScopes; pnodeScope;)
  657. {
  658. switch (pnodeScope->nop)
  659. {
  660. case knopFncDecl:
  661. if (pnodeScope->sxFnc.IsDeclaration())
  662. {
  663. // The frameDisplayLoc register's lifetime has to be controlled by this function. We can't let
  664. // it be released by DefineOneFunction, because further iterations of this loop can allocate
  665. // temps, and we can't let frameDisplayLoc be re-purposed until this loop completes.
  666. // So we'll supply a temp that we allocate and release here.
  667. if (frameDisplayLoc == Js::Constants::NoRegister)
  668. {
  669. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  670. {
  671. frameDisplayLoc = funcInfo->frameDisplayRegister;
  672. }
  673. else
  674. {
  675. frameDisplayLoc = funcInfo->GetEnvRegister();
  676. }
  677. tmpInnerEnvReg = funcInfo->AcquireTmpRegister();
  678. frameDisplayLoc = byteCodeGenerator->PrependLocalScopes(frameDisplayLoc, tmpInnerEnvReg, funcInfo);
  679. }
  680. byteCodeGenerator->DefineOneFunction(pnodeScope, funcInfo, true, frameDisplayLoc);
  681. }
  682. // If this is the global eval block scope, the function is actually assigned to the global
  683. // so we don't need to keep the registers.
  684. if (isGlobalEvalBlockScope)
  685. {
  686. funcInfo->ReleaseLoc(pnodeScope);
  687. pnodeScope->location = Js::Constants::NoRegister;
  688. }
  689. pnodeScope = pnodeScope->sxFnc.pnodeNext;
  690. break;
  691. case knopBlock:
  692. pnodeScope = pnodeScope->sxBlock.pnodeNext;
  693. break;
  694. case knopCatch:
  695. pnodeScope = pnodeScope->sxCatch.pnodeNext;
  696. break;
  697. case knopWith:
  698. pnodeScope = pnodeScope->sxWith.pnodeNext;
  699. break;
  700. }
  701. }
  702. if (tmpInnerEnvReg != Js::Constants::NoRegister)
  703. {
  704. funcInfo->ReleaseTmpRegister(tmpInnerEnvReg);
  705. }
  706. if (pnodeBlock->sxBlock.scope->IsGlobalEvalBlockScope() && funcInfo->thisScopeSlot != Js::Constants::NoRegister)
  707. {
  708. Scope* scope = funcInfo->GetGlobalEvalBlockScope();
  709. byteCodeGenerator->EmitInitCapturedThis(funcInfo, scope);
  710. }
  711. }
  712. else
  713. {
  714. Scope *scope = pnodeBlock->sxBlock.scope;
  715. if (scope)
  716. {
  717. if (scope->GetMustInstantiate())
  718. {
  719. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInObject);
  720. }
  721. else
  722. {
  723. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeDirect);
  724. }
  725. }
  726. else
  727. {
  728. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInSlot);
  729. }
  730. }
  731. byteCodeGenerator->InitBlockScopedContent(pnodeBlock, debuggerScope, funcInfo);
  732. }
  733. void EndEmitBlock(ParseNode *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  734. {
  735. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  736. {
  737. Scope *scope = pnodeBlock->sxBlock.scope;
  738. Assert(scope);
  739. Assert(scope == byteCodeGenerator->GetCurrentScope());
  740. byteCodeGenerator->PopScope();
  741. }
  742. byteCodeGenerator->RecordEndScopeObject(pnodeBlock);
  743. }
  744. void CloneEmitBlock(ParseNode *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  745. {
  746. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  747. {
  748. // Only let variables have observable behavior when there are per iteration
  749. // bindings. const variables do not since they are immutable. Therefore,
  750. // (and the spec agrees), only create new scope clones if the loop variable
  751. // is a let declaration.
  752. bool isConst = false;
  753. pnodeBlock->sxBlock.scope->ForEachSymbolUntil([&isConst](Symbol * const sym) {
  754. // Exploit the fact that a for loop sxBlock can only have let and const
  755. // declarations, and can only have one or the other, regardless of how
  756. // many syms there might be. Thus only check the first sym.
  757. isConst = sym->GetDecl()->nop == knopConstDecl;
  758. return true;
  759. });
  760. if (!isConst)
  761. {
  762. Scope *scope = pnodeBlock->sxBlock.scope;
  763. Assert(scope == byteCodeGenerator->GetCurrentScope());
  764. if (scope->GetMustInstantiate())
  765. {
  766. Js::OpCode op = scope->GetIsObject() ? Js::OpCode::CloneBlockScope : Js::OpCode::CloneInnerScopeSlots;
  767. byteCodeGenerator->Writer()->Unsigned1(op, scope->GetInnerScopeIndex());
  768. }
  769. }
  770. }
  771. }
  772. void EmitBlock(ParseNode *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue)
  773. {
  774. Assert(pnodeBlock->nop == knopBlock);
  775. ParseNode *pnode = pnodeBlock->sxBlock.pnodeStmt;
  776. if (pnode == nullptr)
  777. {
  778. return;
  779. }
  780. BeginEmitBlock(pnodeBlock, byteCodeGenerator, funcInfo);
  781. ParseNode *pnodeLastValStmt = pnodeBlock->sxBlock.pnodeLastValStmt;
  782. while (pnode->nop == knopList)
  783. {
  784. ParseNode* stmt = pnode->sxBin.pnode1;
  785. if (stmt == pnodeLastValStmt)
  786. {
  787. // This is the last guaranteed return value, so any potential return values have to be
  788. // copied to the return register from this point forward.
  789. pnodeLastValStmt = nullptr;
  790. }
  791. byteCodeGenerator->EmitTopLevelStatement(stmt, funcInfo, fReturnValue && (pnodeLastValStmt == nullptr));
  792. pnode = pnode->sxBin.pnode2;
  793. }
  794. if (pnode == pnodeLastValStmt)
  795. {
  796. pnodeLastValStmt = nullptr;
  797. }
  798. byteCodeGenerator->EmitTopLevelStatement(pnode, funcInfo, fReturnValue && (pnodeLastValStmt == nullptr));
  799. EndEmitBlock(pnodeBlock, byteCodeGenerator, funcInfo);
  800. }
  801. void ClearTmpRegs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* emitFunc)
  802. {
  803. if (emitFunc->IsTmpReg(pnode->location))
  804. {
  805. pnode->location = Js::Constants::NoRegister;
  806. }
  807. }
  808. void ByteCodeGenerator::EmitTopLevelStatement(ParseNode *stmt, FuncInfo *funcInfo, BOOL fReturnValue)
  809. {
  810. if (stmt->nop == knopFncDecl && stmt->sxFnc.IsDeclaration())
  811. {
  812. // Function declarations (not function-declaration RHS's) are already fully processed.
  813. // Skip them here so the temp registers don't get messed up.
  814. return;
  815. }
  816. if (stmt->nop == knopName || stmt->nop == knopDot)
  817. {
  818. // Generating span for top level names are mostly useful in debugging mode, because user can debug it even though no side-effect expected.
  819. // But the name can have runtime error, e.g., foo.bar; // where foo is not defined.
  820. // At this time we need to throw proper line number and offset. so recording on all modes will be useful.
  821. StartStatement(stmt);
  822. Writer()->Empty(Js::OpCode::Nop);
  823. EndStatement(stmt);
  824. }
  825. Emit(stmt, this, funcInfo, fReturnValue);
  826. if (funcInfo->IsTmpReg(stmt->location))
  827. {
  828. if (!stmt->isUsed && !fReturnValue)
  829. {
  830. m_writer.Reg1(Js::OpCode::Unused, stmt->location);
  831. }
  832. funcInfo->ReleaseLoc(stmt);
  833. }
  834. }
  835. // ByteCodeGenerator::DefineFunctions
  836. //
  837. // Emit byte code for scope-wide function definitions before any calls in the scope, regardless of lexical
  838. // order. Note that stores to the closure array are not emitted until we see the knopFncDecl in the tree
  839. // to make sure that sources of the stores have been defined.
  840. void ByteCodeGenerator::DefineFunctions(FuncInfo *funcInfoParent)
  841. {
  842. // DefineCachedFunctions doesn't depend on whether the user vars are declared or not, so
  843. // we'll just overload this variable to mean that the functions getting called again and we don't need to do anything
  844. if (funcInfoParent->GetHasCachedScope())
  845. {
  846. this->DefineCachedFunctions(funcInfoParent);
  847. }
  848. else
  849. {
  850. this->DefineUncachedFunctions(funcInfoParent);
  851. }
  852. }
  853. // Iterate over all child functions in a function's parameter and body scopes.
  854. template<typename Fn>
  855. void MapContainerScopeFunctions(ParseNode* pnodeScope, Fn fn)
  856. {
  857. auto mapFncDeclsInScopeList = [&](ParseNode *pnodeHead)
  858. {
  859. for (ParseNode *pnode = pnodeHead; pnode != nullptr;)
  860. {
  861. switch (pnode->nop)
  862. {
  863. case knopFncDecl:
  864. fn(pnode);
  865. pnode = pnode->sxFnc.pnodeNext;
  866. break;
  867. case knopBlock:
  868. pnode = pnode->sxBlock.pnodeNext;
  869. break;
  870. case knopCatch:
  871. pnode = pnode->sxCatch.pnodeNext;
  872. break;
  873. case knopWith:
  874. pnode = pnode->sxWith.pnodeNext;
  875. break;
  876. default:
  877. AssertMsg(false, "Unexpected opcode in tree of scopes");
  878. return;
  879. }
  880. }
  881. };
  882. pnodeScope->sxFnc.MapContainerScopes(mapFncDeclsInScopeList);
  883. }
  884. void ByteCodeGenerator::DefineCachedFunctions(FuncInfo *funcInfoParent)
  885. {
  886. ParseNode *pnodeParent = funcInfoParent->root;
  887. uint slotCount = 0;
  888. auto countFncSlots = [&](ParseNode *pnodeFnc)
  889. {
  890. if (pnodeFnc->sxFnc.GetFuncSymbol() != nullptr && pnodeFnc->sxFnc.IsDeclaration())
  891. {
  892. slotCount++;
  893. }
  894. };
  895. MapContainerScopeFunctions(pnodeParent, countFncSlots);
  896. if (slotCount == 0)
  897. {
  898. return;
  899. }
  900. size_t extraBytesActual = AllocSizeMath::Mul(slotCount, sizeof(Js::FuncInfoEntry));
  901. // Reg2Aux takes int for byteCount so we need to convert to int. OOM if we can't because it would truncate data.
  902. if (extraBytesActual > INT_MAX)
  903. {
  904. Js::Throw::OutOfMemory();
  905. }
  906. int extraBytes = (int)extraBytesActual;
  907. Js::FuncInfoArray *info = AnewPlus(alloc, extraBytes, Js::FuncInfoArray, slotCount);
  908. slotCount = 0;
  909. auto fillEntries = [&](ParseNode *pnodeFnc)
  910. {
  911. Symbol *sym = pnodeFnc->sxFnc.GetFuncSymbol();
  912. if (sym != nullptr && (pnodeFnc->sxFnc.IsDeclaration()))
  913. {
  914. AssertMsg(!pnodeFnc->sxFnc.IsGenerator(), "Generator functions are not supported by InitCachedFuncs but since they always escape they should disable function caching");
  915. Js::FuncInfoEntry *entry = &info->elements[slotCount];
  916. entry->nestedIndex = pnodeFnc->sxFnc.nestedIndex;
  917. entry->scopeSlot = sym->GetScopeSlot();
  918. slotCount++;
  919. }
  920. };
  921. MapContainerScopeFunctions(pnodeParent, fillEntries);
  922. m_writer.AuxNoReg(Js::OpCode::InitCachedFuncs,
  923. info,
  924. sizeof(Js::FuncInfoArray) + extraBytes,
  925. sizeof(Js::FuncInfoArray) + extraBytes);
  926. slotCount = 0;
  927. auto defineOrGetCachedFunc = [&](ParseNode *pnodeFnc)
  928. {
  929. Symbol *sym = pnodeFnc->sxFnc.GetFuncSymbol();
  930. if (pnodeFnc->sxFnc.IsDeclaration())
  931. {
  932. // Do we need to define the function here (i.e., is it not one of our cached locals)?
  933. // Only happens if the sym is null (e.g., function x.y(){}).
  934. if (sym == nullptr)
  935. {
  936. this->DefineOneFunction(pnodeFnc, funcInfoParent);
  937. }
  938. else if (!sym->IsInSlot(funcInfoParent) && sym->GetLocation() != Js::Constants::NoRegister)
  939. {
  940. // If it was defined by InitCachedFuncs, do we need to put it in a register rather than a slot?
  941. m_writer.Reg1Unsigned1(Js::OpCode::GetCachedFunc, sym->GetLocation(), slotCount);
  942. }
  943. // The "x = function() {...}" case is being generated on the fly, during emission,
  944. // so the caller expects to be able to release this register.
  945. funcInfoParent->ReleaseLoc(pnodeFnc);
  946. pnodeFnc->location = Js::Constants::NoRegister;
  947. slotCount++;
  948. }
  949. };
  950. MapContainerScopeFunctions(pnodeParent, defineOrGetCachedFunc);
  951. AdeletePlus(alloc, extraBytes, info);
  952. }
  953. void ByteCodeGenerator::DefineUncachedFunctions(FuncInfo *funcInfoParent)
  954. {
  955. ParseNode *pnodeParent = funcInfoParent->root;
  956. auto defineCheck = [&](ParseNode *pnodeFnc)
  957. {
  958. Assert(pnodeFnc->nop == knopFncDecl);
  959. //
  960. // Don't define the function upfront in following cases
  961. // 1. x = function() {...};
  962. // Don't define the function for all modes.
  963. // Such a function can only be accessed via the LHS, so we define it at the assignment point
  964. // rather than the scope entry to save a register (and possibly save the whole definition).
  965. //
  966. // 2. x = function f() {...};
  967. // f is not visible in the enclosing scope.
  968. // Such function expressions should be emitted only at the assignment point, as can be used only
  969. // after the assignment. Might save register.
  970. //
  971. if (pnodeFnc->sxFnc.IsDeclaration())
  972. {
  973. this->DefineOneFunction(pnodeFnc, funcInfoParent);
  974. // The "x = function() {...}" case is being generated on the fly, during emission,
  975. // so the caller expects to be able to release this register.
  976. funcInfoParent->ReleaseLoc(pnodeFnc);
  977. pnodeFnc->location = Js::Constants::NoRegister;
  978. }
  979. };
  980. MapContainerScopeFunctions(pnodeParent, defineCheck);
  981. }
  982. void EmitAssignmentToFuncName(ParseNode *pnodeFnc, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfoParent)
  983. {
  984. // Assign the location holding the func object reference to the given name.
  985. Symbol *sym = pnodeFnc->sxFnc.pnodeName->sxVar.sym;
  986. if (sym != nullptr && !sym->GetFuncExpr())
  987. {
  988. if (sym->GetIsGlobal())
  989. {
  990. Js::PropertyId propertyId = sym->GetPosition();
  991. byteCodeGenerator->EmitGlobalFncDeclInit(pnodeFnc->location, propertyId, funcInfoParent);
  992. if (byteCodeGenerator->GetScriptContext()->GetConfig()->IsBlockScopeEnabled() &&
  993. byteCodeGenerator->GetFlags() & fscrEval && !funcInfoParent->GetIsStrictMode())
  994. {
  995. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  996. }
  997. }
  998. else
  999. {
  1000. if (sym->NeedsSlotAlloc(funcInfoParent))
  1001. {
  1002. if (!sym->GetHasNonCommittedReference() ||
  1003. (funcInfoParent->GetParsedFunctionBody()->DoStackNestedFunc()))
  1004. {
  1005. // No point in trying to optimize if there are no references before we have to commit to slot.
  1006. // And not safe to delay putting a stack function in the slot, since we may miss boxing.
  1007. sym->SetIsCommittedToSlot();
  1008. }
  1009. }
  1010. byteCodeGenerator->EmitLocalPropInit(pnodeFnc->location, sym, funcInfoParent);
  1011. Symbol * fncScopeSym = sym->GetFuncScopeVarSym();
  1012. if (fncScopeSym)
  1013. {
  1014. Assert(byteCodeGenerator->GetScriptContext()->GetConfig()->IsBlockScopeEnabled());
  1015. if (fncScopeSym->GetIsGlobal() && byteCodeGenerator->GetFlags() & fscrEval)
  1016. {
  1017. Js::PropertyId propertyId = fncScopeSym->GetPosition();
  1018. byteCodeGenerator->EmitGlobalFncDeclInit(pnodeFnc->location, propertyId, funcInfoParent);
  1019. }
  1020. else
  1021. {
  1022. byteCodeGenerator->EmitPropStore(pnodeFnc->location, fncScopeSym, nullptr, funcInfoParent, false, false, /* isFncDeclVar */true);
  1023. }
  1024. }
  1025. }
  1026. }
  1027. }
  1028. Js::RegSlot ByteCodeGenerator::DefineOneFunction(ParseNode *pnodeFnc, FuncInfo *funcInfoParent, bool generateAssignment, Js::RegSlot regEnv, Js::RegSlot frameDisplayTemp)
  1029. {
  1030. Assert(pnodeFnc->nop == knopFncDecl);
  1031. funcInfoParent->AcquireLoc(pnodeFnc);
  1032. if (regEnv == Js::Constants::NoRegister)
  1033. {
  1034. // If the child needs a closure, find a heap-allocated frame to pass to it.
  1035. if (frameDisplayTemp != Js::Constants::NoRegister)
  1036. {
  1037. // We allocated a temp to hold a local frame display value. Use that.
  1038. // It's likely that the FD is on the stack, and we used the temp to load it back.
  1039. regEnv = frameDisplayTemp;
  1040. }
  1041. else if (funcInfoParent->frameDisplayRegister != Js::Constants::NoRegister)
  1042. {
  1043. // This function has built a frame display, so pass it down.
  1044. regEnv = funcInfoParent->frameDisplayRegister;
  1045. }
  1046. else
  1047. {
  1048. // This function has no captured locals but inherits a closure environment, so pass it down.
  1049. regEnv = funcInfoParent->GetEnvRegister();
  1050. }
  1051. regEnv = this->PrependLocalScopes(regEnv, Js::Constants::NoRegister, funcInfoParent);
  1052. }
  1053. // AssertMsg(funcInfo->nonLocalSymbols == 0 || regEnv != funcInfoParent->nullConstantRegister,
  1054. // "We need a closure for the nested function");
  1055. if (regEnv == funcInfoParent->frameDisplayRegister || regEnv == funcInfoParent->GetEnvRegister())
  1056. {
  1057. m_writer.NewFunction(pnodeFnc->location, pnodeFnc->sxFnc.nestedIndex, pnodeFnc->sxFnc.IsGenerator());
  1058. }
  1059. else
  1060. {
  1061. m_writer.NewInnerFunction(pnodeFnc->location, pnodeFnc->sxFnc.nestedIndex, regEnv, pnodeFnc->sxFnc.IsGenerator());
  1062. }
  1063. if (funcInfoParent->IsGlobalFunction() && (this->flags & fscrEval))
  1064. {
  1065. // A function declared at global scope in eval is untrackable,
  1066. // so make sure the caller's cached scope is invalidated.
  1067. this->funcEscapes = true;
  1068. }
  1069. else
  1070. {
  1071. if (pnodeFnc->sxFnc.IsDeclaration())
  1072. {
  1073. Symbol * funcSymbol = pnodeFnc->sxFnc.GetFuncSymbol();
  1074. if (funcSymbol)
  1075. {
  1076. // In the case where a let/const declaration is the same symbol name
  1077. // as the function declaration (shadowing case), the let/const var and
  1078. // the function declaration symbol are the same and share the same flags
  1079. // (particularly, sym->GetIsBlockVar() for this code path).
  1080. //
  1081. // For example:
  1082. // let a = 0; // <-- sym->GetIsBlockVar() = true
  1083. // function b(){} // <-- sym2->GetIsBlockVar() = false
  1084. //
  1085. // let x = 0; // <-- sym3->GetIsBlockVar() = true
  1086. // function x(){} // <-- sym3->GetIsBlockVar() = true
  1087. //
  1088. // In order to tell if the function is actually part
  1089. // of a block scope, we compare against the function scope here.
  1090. // Note that having a function with the same name as a let/const declaration
  1091. // is a redeclaration error, but we're pushing the fix for this out since it's
  1092. // a bit involved.
  1093. //
  1094. // TODO: Once the redeclaration error is in place, this boolean can be replaced
  1095. // by funcSymbol->GetIsBlockVar().
  1096. Assert(funcInfoParent->GetBodyScope() != nullptr && funcSymbol->GetScope() != nullptr);
  1097. bool isFunctionDeclarationInBlock = funcSymbol->GetScope() != funcInfoParent->GetBodyScope();
  1098. // Track all vars/lets/consts register slot function declarations.
  1099. if (ShouldTrackDebuggerMetadata()
  1100. // If this is a let binding function declaration at global level, we want to
  1101. // be sure to track the register location as well.
  1102. && !(funcInfoParent->IsGlobalFunction() && !isFunctionDeclarationInBlock))
  1103. {
  1104. if (!funcSymbol->IsInSlot(funcInfoParent))
  1105. {
  1106. funcInfoParent->byteCodeFunction->GetFunctionBody()->InsertSymbolToRegSlotList(funcSymbol->GetName(), pnodeFnc->location, funcInfoParent->varRegsCount);
  1107. }
  1108. }
  1109. if (isFunctionDeclarationInBlock)
  1110. {
  1111. // We only track inner let bindings for the debugger side.
  1112. this->TrackFunctionDeclarationPropertyForDebugger(funcSymbol, funcInfoParent);
  1113. }
  1114. }
  1115. }
  1116. }
  1117. if (pnodeFnc->sxFnc.pnodeName == nullptr || !generateAssignment)
  1118. {
  1119. return regEnv;
  1120. }
  1121. EmitAssignmentToFuncName(pnodeFnc, this, funcInfoParent);
  1122. return regEnv;
  1123. }
  1124. void ByteCodeGenerator::DefineUserVars(FuncInfo *funcInfo)
  1125. {
  1126. // Initialize scope-wide variables on entry to the scope. TODO: optimize by detecting uses that are always reached
  1127. // by an existing initialization.
  1128. BOOL fGlobal = funcInfo->IsGlobalFunction();
  1129. ParseNode *pnode;
  1130. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1131. // Global declarations need a temp register to hold the init value, but the node shouldn't get a register.
  1132. // Just assign one on the fly and re-use it for all initializations.
  1133. Js::RegSlot tmpReg = fGlobal ? funcInfo->AcquireTmpRegister() : Js::Constants::NoRegister;
  1134. for (pnode = funcInfo->root->sxFnc.pnodeVars; pnode; pnode = pnode->sxVar.pnodeNext)
  1135. {
  1136. Symbol* sym = pnode->sxVar.sym;
  1137. if (sym != nullptr && !(pnode->sxVar.isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  1138. {
  1139. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  1140. {
  1141. // The init node was bound to the catch object, because it's inside a catch and has the
  1142. // same name as the catch object. But we want to define a user var at function scope,
  1143. // so find the right symbol. (We'll still assign the RHS value to the catch object symbol.)
  1144. // This also applies to a var declaration in the same scope as a let declaration.
  1145. #if DBG
  1146. if (!sym->GetIsCatch())
  1147. {
  1148. // Assert that catch cannot be at function scope and let and var at function scope is redeclaration error.
  1149. Assert(funcInfo->bodyScope != sym->GetScope() || !this->scriptContext->GetConfig()->IsBlockScopeEnabled());
  1150. }
  1151. #endif
  1152. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  1153. Assert(sym && !sym->GetIsCatch() && !sym->GetIsBlockVar());
  1154. }
  1155. if (sym->GetSymbolType() == STVariable)
  1156. {
  1157. if (fGlobal)
  1158. {
  1159. Js::PropertyId propertyId = sym->EnsurePosition(this);
  1160. // We do need to initialize some globals to avoid JS errors on loading undefined variables.
  1161. // But we first need to make sure we're not trashing built-ins.
  1162. if (this->flags & fscrEval)
  1163. {
  1164. if (funcInfo->byteCodeFunction->GetIsStrictMode())
  1165. {
  1166. // Check/Init the property of the frame object
  1167. this->m_writer.ElementRootU(Js::OpCode::LdLocalElemUndef,
  1168. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1169. }
  1170. else
  1171. {
  1172. // The check and the init involve the first element in the scope chain.
  1173. this->m_writer.ElementScopedU(
  1174. Js::OpCode::LdElemUndefScoped, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1175. }
  1176. }
  1177. else
  1178. {
  1179. this->m_writer.ElementU(Js::OpCode::LdElemUndef, ByteCodeGenerator::RootObjectRegister,
  1180. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1181. }
  1182. }
  1183. else if (!sym->GetIsArguments())
  1184. {
  1185. if (sym->NeedsSlotAlloc(funcInfo))
  1186. {
  1187. if (!sym->GetHasNonCommittedReference() ||
  1188. (sym->GetHasFuncAssignment() && funcInfo->GetParsedFunctionBody()->DoStackNestedFunc()))
  1189. {
  1190. // No point in trying to optimize if there are no references before we have to commit to slot.
  1191. // And not safe to delay putting a stack function in the slot, since we may miss boxing.
  1192. sym->SetIsCommittedToSlot();
  1193. }
  1194. }
  1195. if ((!sym->GetHasInit() && !sym->IsInSlot(funcInfo)) ||
  1196. (funcInfo->bodyScope->GetIsObject() && !funcInfo->GetHasCachedScope()))
  1197. {
  1198. Js::RegSlot reg = sym->GetLocation();
  1199. if (reg == Js::Constants::NoRegister)
  1200. {
  1201. Assert(sym->IsInSlot(funcInfo));
  1202. reg = funcInfo->AcquireTmpRegister();
  1203. }
  1204. this->m_writer.Reg1(Js::OpCode::LdUndef, reg);
  1205. this->EmitLocalPropInit(reg, sym, funcInfo);
  1206. if (ShouldTrackDebuggerMetadata() && !sym->GetHasInit() && !sym->IsInSlot(funcInfo))
  1207. {
  1208. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), reg, funcInfo->varRegsCount);
  1209. }
  1210. funcInfo->ReleaseTmpRegister(reg);
  1211. }
  1212. }
  1213. else if (ShouldTrackDebuggerMetadata())
  1214. {
  1215. if (!sym->GetHasInit() && !sym->IsInSlot(funcInfo))
  1216. {
  1217. Js::RegSlot reg = sym->GetLocation();
  1218. if (reg != Js::Constants::NoRegister)
  1219. {
  1220. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), reg, funcInfo->varRegsCount);
  1221. }
  1222. }
  1223. }
  1224. sym->SetHasInit(TRUE);
  1225. }
  1226. }
  1227. }
  1228. if (tmpReg != Js::Constants::NoRegister)
  1229. {
  1230. funcInfo->ReleaseTmpRegister(tmpReg);
  1231. }
  1232. for (int i = 0; i < funcInfo->nonUserNonTempRegistersToInitialize.Count(); ++i)
  1233. {
  1234. m_writer.Reg1(Js::OpCode::LdUndef, funcInfo->nonUserNonTempRegistersToInitialize.Item(i));
  1235. }
  1236. this->InitBlockScopedNonTemps(funcInfo->root->sxFnc.pnodeScopes, funcInfo);
  1237. }
  1238. void ByteCodeGenerator::InitBlockScopedNonTemps(ParseNode *pnode, FuncInfo *funcInfo)
  1239. {
  1240. // Initialize all non-temp register variables on entry to the enclosing func - in particular,
  1241. // those with lifetimes that begin after the start of user code and may not be initialized normally.
  1242. // This protects us from, for instance, trying to restore garbage on bailout.
  1243. // It was originally done in debugger mode only, but we do it always to avoid issues with boxing
  1244. // garbage on exit from jitted loop bodies.
  1245. while (pnode)
  1246. {
  1247. switch (pnode->nop)
  1248. {
  1249. case knopFncDecl:
  1250. if (this->scriptContext->GetConfig()->IsBlockScopeEnabled())
  1251. {
  1252. // If this is a block-scoped function, initialize it.
  1253. ParseNode *pnodeName = pnode->sxFnc.pnodeName;
  1254. if (!pnode->sxFnc.IsMethod() && pnodeName && pnodeName->nop == knopVarDecl)
  1255. {
  1256. Symbol *sym = pnodeName->sxVar.sym;
  1257. Assert(sym);
  1258. if (sym->GetLocation() != Js::Constants::NoRegister &&
  1259. sym->GetScope()->IsBlockScope(funcInfo) &&
  1260. sym->GetScope()->GetFunc() == funcInfo)
  1261. {
  1262. this->m_writer.Reg1(Js::OpCode::LdUndef, sym->GetLocation());
  1263. }
  1264. }
  1265. }
  1266. // No need to recurse to the nested scopes, as they belong to a nested function.
  1267. pnode = pnode->sxFnc.pnodeNext;
  1268. break;
  1269. case knopBlock:
  1270. {
  1271. Scope *scope = pnode->sxBlock.scope;
  1272. if (scope)
  1273. {
  1274. if (scope->IsBlockScope(funcInfo))
  1275. {
  1276. Js::RegSlot scopeLoc = scope->GetLocation();
  1277. if (scopeLoc != Js::Constants::NoRegister && !funcInfo->IsTmpReg(scopeLoc))
  1278. {
  1279. this->m_writer.Reg1(Js::OpCode::LdUndef, scopeLoc);
  1280. }
  1281. }
  1282. auto fnInit = [this, funcInfo](ParseNode *pnode)
  1283. {
  1284. Symbol *sym = pnode->sxVar.sym;
  1285. if (!sym->IsInSlot(funcInfo) && !sym->GetIsGlobal())
  1286. {
  1287. this->m_writer.Reg1(Js::OpCode::InitUndecl, pnode->sxVar.sym->GetLocation());
  1288. }
  1289. };
  1290. IterateBlockScopedVariables(pnode, fnInit);
  1291. }
  1292. InitBlockScopedNonTemps(pnode->sxBlock.pnodeScopes, funcInfo);
  1293. pnode = pnode->sxBlock.pnodeNext;
  1294. break;
  1295. }
  1296. case knopCatch:
  1297. InitBlockScopedNonTemps(pnode->sxCatch.pnodeScopes, funcInfo);
  1298. pnode = pnode->sxCatch.pnodeNext;
  1299. break;
  1300. case knopWith:
  1301. {
  1302. Js::RegSlot withLoc = pnode->location;
  1303. AssertMsg(withLoc != Js::Constants::NoRegister && !funcInfo->IsTmpReg(withLoc),
  1304. "We should put with objects at known stack locations in debug mode");
  1305. this->m_writer.Reg1(Js::OpCode::LdUndef, withLoc);
  1306. InitBlockScopedNonTemps(pnode->sxWith.pnodeScopes, funcInfo);
  1307. pnode = pnode->sxWith.pnodeNext;
  1308. break;
  1309. }
  1310. default:
  1311. Assert(false);
  1312. return;
  1313. }
  1314. }
  1315. }
  1316. void ByteCodeGenerator::EmitScopeObjectInit(FuncInfo *funcInfo)
  1317. {
  1318. Assert(!funcInfo->byteCodeFunction->GetFunctionBody()->DoStackNestedFunc());
  1319. if (!funcInfo->GetHasCachedScope() /* || forcing scope/inner func caching */)
  1320. {
  1321. return;
  1322. }
  1323. uint slotCount = funcInfo->bodyScope->GetScopeSlotCount();
  1324. uint cachedFuncCount = 0;
  1325. Js::PropertyId firstFuncSlot = Js::Constants::NoProperty;
  1326. Js::PropertyId firstVarSlot = Js::Constants::NoProperty;
  1327. uint extraAlloc = (slotCount + Js::ActivationObjectEx::ExtraSlotCount()) * sizeof(Js::PropertyId);
  1328. // Create and fill the array of local property ID's.
  1329. // They all have slots assigned to them already (if they need them): see StartEmitFunction.
  1330. Js::PropertyIdArray *propIds = AnewPlus(alloc, extraAlloc, Js::PropertyIdArray, slotCount);
  1331. ParseNode *pnodeFnc = funcInfo->root;
  1332. ParseNode *pnode;
  1333. Symbol *sym;
  1334. if (funcInfo->GetFuncExprNameReference() && pnodeFnc->sxFnc.GetFuncSymbol()->GetScope() == funcInfo->GetBodyScope())
  1335. {
  1336. Symbol::SaveToPropIdArray(pnodeFnc->sxFnc.GetFuncSymbol(), propIds, this);
  1337. }
  1338. if (funcInfo->GetHasArguments())
  1339. {
  1340. // Because the arguments object can access all instances of same-named formals ("function(x,x){...}"),
  1341. // be sure we initialize any duplicate appearances of a formal parameter to "NoProperty".
  1342. Js::PropertyId slot = 0;
  1343. auto initArg = [&](ParseNode *pnode)
  1344. {
  1345. if (pnode->IsVarLetOrConst())
  1346. {
  1347. Symbol *sym = pnode->sxVar.sym;
  1348. Assert(sym);
  1349. if (sym->GetScopeSlot() == slot)
  1350. {
  1351. // This is the last appearance of the formal, so record the ID.
  1352. Symbol::SaveToPropIdArray(sym, propIds, this);
  1353. }
  1354. else
  1355. {
  1356. // This is an earlier duplicate appearance of the formal, so use NoProperty as a placeholder
  1357. // since this slot can't be accessed by name.
  1358. Assert(sym->GetScopeSlot() != Js::Constants::NoProperty && sym->GetScopeSlot() > slot);
  1359. propIds->elements[slot] = Js::Constants::NoProperty;
  1360. }
  1361. slot++;
  1362. }
  1363. };
  1364. MapFormalsWithoutRest(pnodeFnc, initArg);
  1365. // initArg assumes the sym is in a slot, but this may not be true for the rest parameter.
  1366. if (pnodeFnc->sxFnc.pnodeRest != nullptr && pnodeFnc->sxFnc.pnodeRest->sxVar.sym->IsInSlot(funcInfo))
  1367. {
  1368. initArg(pnodeFnc->sxFnc.pnodeRest);
  1369. }
  1370. }
  1371. else
  1372. {
  1373. MapFormals(pnodeFnc, [&](ParseNode *pnode)
  1374. {
  1375. if (pnode->IsVarLetOrConst())
  1376. {
  1377. Symbol::SaveToPropIdArray(pnode->sxVar.sym, propIds, this);
  1378. }
  1379. });
  1380. }
  1381. auto saveFunctionVarsToPropIdArray = [&](ParseNode *pnodeFunction)
  1382. {
  1383. if (pnodeFunction->sxFnc.IsDeclaration())
  1384. {
  1385. ParseNode *pnodeName = pnodeFunction->sxFnc.pnodeName;
  1386. if (pnodeName != nullptr)
  1387. {
  1388. while (pnodeName->nop == knopList)
  1389. {
  1390. if (pnodeName->sxBin.pnode1->nop == knopVarDecl)
  1391. {
  1392. sym = pnodeName->sxBin.pnode1->sxVar.sym;
  1393. if (sym)
  1394. {
  1395. Symbol::SaveToPropIdArray(sym, propIds, this, &firstFuncSlot);
  1396. }
  1397. }
  1398. pnodeName = pnodeName->sxBin.pnode2;
  1399. }
  1400. if (pnodeName->nop == knopVarDecl)
  1401. {
  1402. sym = pnodeName->sxVar.sym;
  1403. if (sym)
  1404. {
  1405. Symbol::SaveToPropIdArray(sym, propIds, this, &firstFuncSlot);
  1406. cachedFuncCount++;
  1407. }
  1408. }
  1409. }
  1410. }
  1411. };
  1412. MapContainerScopeFunctions(pnodeFnc, saveFunctionVarsToPropIdArray);
  1413. for (pnode = pnodeFnc->sxFnc.pnodeVars; pnode; pnode = pnode->sxVar.pnodeNext)
  1414. {
  1415. sym = pnode->sxVar.sym;
  1416. if (!(pnode->sxVar.isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  1417. {
  1418. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  1419. {
  1420. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  1421. }
  1422. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1423. }
  1424. }
  1425. ParseNode *pnodeBlock = pnodeFnc->sxFnc.pnodeScopes;
  1426. for (pnode = pnodeBlock->sxBlock.pnodeLexVars; pnode; pnode = pnode->sxVar.pnodeNext)
  1427. {
  1428. sym = pnode->sxVar.sym;
  1429. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1430. }
  1431. pnodeBlock = pnodeFnc->sxFnc.pnodeBodyScope;
  1432. for (pnode = pnodeBlock->sxBlock.pnodeLexVars; pnode; pnode = pnode->sxVar.pnodeNext)
  1433. {
  1434. sym = pnode->sxVar.sym;
  1435. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1436. }
  1437. if (funcInfo->thisScopeSlot != Js::Constants::NoRegister)
  1438. {
  1439. propIds->elements[funcInfo->thisScopeSlot] = Js::PropertyIds::_lexicalThisSlotSymbol;
  1440. }
  1441. if (funcInfo->newTargetScopeSlot != Js::Constants::NoRegister)
  1442. {
  1443. propIds->elements[funcInfo->newTargetScopeSlot] = Js::PropertyIds::_lexicalNewTargetSymbol;
  1444. }
  1445. if (funcInfo->superScopeSlot != Js::Constants::NoRegister)
  1446. {
  1447. propIds->elements[funcInfo->superScopeSlot] = Js::PropertyIds::_superReferenceSymbol;
  1448. }
  1449. if (funcInfo->superCtorScopeSlot != Js::Constants::NoRegister)
  1450. {
  1451. propIds->elements[funcInfo->superCtorScopeSlot] = Js::PropertyIds::_superCtorReferenceSymbol;
  1452. }
  1453. // Write the first func slot and first var slot into the auxiliary data
  1454. Js::PropertyId *slots = propIds->elements + slotCount;
  1455. slots[0] = cachedFuncCount;
  1456. slots[1] = firstFuncSlot;
  1457. slots[2] = firstVarSlot;
  1458. slots[3] = funcInfo->GetParsedFunctionBody()->NewObjectLiteral();
  1459. propIds->hasNonSimpleParams = !funcInfo->root->sxFnc.IsSimpleParameterList();
  1460. funcInfo->localPropIdOffset = m_writer.InsertAuxiliaryData(propIds, sizeof(Js::PropertyIdArray) + extraAlloc);
  1461. Assert(funcInfo->localPropIdOffset == 0);
  1462. funcInfo->GetParsedFunctionBody()->SetHasCachedScopePropIds(true);
  1463. AdeletePlus(alloc, extraAlloc, propIds);
  1464. }
  1465. void ByteCodeGenerator::FinalizeRegisters(FuncInfo * funcInfo, Js::FunctionBody * byteCodeFunction)
  1466. {
  1467. if (funcInfo->NeedEnvRegister())
  1468. {
  1469. bool constReg = !funcInfo->GetIsEventHandler() && funcInfo->IsGlobalFunction() && !(this->flags & fscrEval);
  1470. funcInfo->AssignEnvRegister(constReg);
  1471. }
  1472. // Set the function body's constant count before emitting anything so that the byte code writer
  1473. // can distinguish constants from variables.
  1474. byteCodeFunction->SetConstantCount(funcInfo->constRegsCount);
  1475. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  1476. {
  1477. byteCodeFunction->SetLocalFrameDisplayReg(funcInfo->frameDisplayRegister);
  1478. }
  1479. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  1480. {
  1481. byteCodeFunction->SetLocalClosureReg(funcInfo->frameObjRegister);
  1482. byteCodeFunction->SetHasScopeObject(true);
  1483. }
  1484. else if (funcInfo->frameSlotsRegister != Js::Constants::NoRegister)
  1485. {
  1486. byteCodeFunction->SetLocalClosureReg(funcInfo->frameSlotsRegister);
  1487. }
  1488. if (this->IsInDebugMode())
  1489. {
  1490. // Give permanent registers to the inner scopes in debug mode.
  1491. uint innerScopeCount = funcInfo->InnerScopeCount();
  1492. byteCodeFunction->SetInnerScopeCount(innerScopeCount);
  1493. if (innerScopeCount)
  1494. {
  1495. funcInfo->SetFirstInnerScopeReg(funcInfo->NextVarRegister());
  1496. for (uint i = 1; i < innerScopeCount; i++)
  1497. {
  1498. funcInfo->NextVarRegister();
  1499. }
  1500. }
  1501. }
  1502. // NOTE: The FB expects the yield reg to be the final non-temp.
  1503. if (byteCodeFunction->IsGenerator())
  1504. {
  1505. funcInfo->AssignYieldRegister();
  1506. }
  1507. Js::RegSlot firstTmpReg = funcInfo->varRegsCount;
  1508. funcInfo->SetFirstTmpReg(firstTmpReg);
  1509. byteCodeFunction->SetFirstTmpReg(funcInfo->RegCount());
  1510. }
  1511. void ByteCodeGenerator::InitScopeSlotArray(FuncInfo * funcInfo)
  1512. {
  1513. // Record slots info for ScopeSlots/ScopeObject.
  1514. uint scopeSlotCount = funcInfo->bodyScope->GetScopeSlotCount();
  1515. if (scopeSlotCount == 0)
  1516. {
  1517. return;
  1518. }
  1519. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1520. Js::PropertyId *propertyIdsForScopeSlotArray = RecyclerNewArrayLeafZ(scriptContext->GetRecycler(), Js::PropertyId, scopeSlotCount);
  1521. AssertMsg(!byteCodeFunction->IsReparsed() || byteCodeFunction->m_wasEverAsmjsMode || byteCodeFunction->scopeSlotArraySize == scopeSlotCount,
  1522. "The slot array size is different between debug and non-debug mode");
  1523. byteCodeFunction->SetPropertyIdsForScopeSlotArray(propertyIdsForScopeSlotArray, scopeSlotCount);
  1524. #if DEBUG
  1525. for (UINT i = 0; i < scopeSlotCount; i++)
  1526. {
  1527. propertyIdsForScopeSlotArray[i] = Js::Constants::NoProperty;
  1528. }
  1529. #endif
  1530. auto setPropIdsForScopeSlotArray = [funcInfo, propertyIdsForScopeSlotArray](Symbol *const sym)
  1531. {
  1532. if (sym->NeedsSlotAlloc(funcInfo))
  1533. {
  1534. // All properties should get correct propertyId here.
  1535. Assert(sym->HasScopeSlot()); // We can't allocate scope slot now. Any symbol needing scope slot must have allocated it before this point.
  1536. propertyIdsForScopeSlotArray[sym->GetScopeSlot()] = sym->EnsurePosition(funcInfo);
  1537. }
  1538. };
  1539. if (funcInfo->GetParamScope() != nullptr)
  1540. {
  1541. funcInfo->GetParamScope()->ForEachSymbol(setPropIdsForScopeSlotArray);
  1542. }
  1543. funcInfo->GetBodyScope()->ForEachSymbol(setPropIdsForScopeSlotArray);
  1544. if (funcInfo->thisScopeSlot != Js::Constants::NoRegister)
  1545. {
  1546. propertyIdsForScopeSlotArray[funcInfo->thisScopeSlot] = Js::PropertyIds::_lexicalThisSlotSymbol;
  1547. }
  1548. if (funcInfo->newTargetScopeSlot != Js::Constants::NoRegister)
  1549. {
  1550. propertyIdsForScopeSlotArray[funcInfo->newTargetScopeSlot] = Js::PropertyIds::_lexicalNewTargetSymbol;
  1551. }
  1552. if (funcInfo->superScopeSlot != Js::Constants::NoRegister)
  1553. {
  1554. propertyIdsForScopeSlotArray[funcInfo->superScopeSlot] = Js::PropertyIds::_superReferenceSymbol;
  1555. }
  1556. if (funcInfo->superCtorScopeSlot != Js::Constants::NoRegister)
  1557. {
  1558. propertyIdsForScopeSlotArray[funcInfo->superCtorScopeSlot] = Js::PropertyIds::_superCtorReferenceSymbol;
  1559. }
  1560. #if DEBUG
  1561. for (UINT i = 0; i < scopeSlotCount; i++)
  1562. {
  1563. Assert(propertyIdsForScopeSlotArray[i] != Js::Constants::NoProperty
  1564. || funcInfo->frameObjRegister != Js::Constants::NoRegister); // ScopeObject may have unassigned entries, e.g. for same-named parameters
  1565. }
  1566. #endif
  1567. }
  1568. // temporarily load all constants and special registers in a single block
  1569. void ByteCodeGenerator::LoadAllConstants(FuncInfo *funcInfo)
  1570. {
  1571. Symbol *sym;
  1572. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1573. byteCodeFunction->CreateConstantTable();
  1574. if (funcInfo->nullConstantRegister != Js::Constants::NoRegister)
  1575. {
  1576. byteCodeFunction->RecordNullObject(byteCodeFunction->MapRegSlot(funcInfo->nullConstantRegister));
  1577. }
  1578. if (funcInfo->undefinedConstantRegister != Js::Constants::NoRegister)
  1579. {
  1580. byteCodeFunction->RecordUndefinedObject(byteCodeFunction->MapRegSlot(funcInfo->undefinedConstantRegister));
  1581. }
  1582. if (funcInfo->trueConstantRegister != Js::Constants::NoRegister)
  1583. {
  1584. byteCodeFunction->RecordTrueObject(byteCodeFunction->MapRegSlot(funcInfo->trueConstantRegister));
  1585. }
  1586. if (funcInfo->falseConstantRegister != Js::Constants::NoRegister)
  1587. {
  1588. byteCodeFunction->RecordFalseObject(byteCodeFunction->MapRegSlot(funcInfo->falseConstantRegister));
  1589. }
  1590. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  1591. {
  1592. m_writer.RecordObjectRegister(funcInfo->frameObjRegister);
  1593. if (!funcInfo->GetApplyEnclosesArgs())
  1594. {
  1595. this->EmitScopeObjectInit(funcInfo);
  1596. }
  1597. #if DBG
  1598. uint count = 0;
  1599. funcInfo->GetBodyScope()->ForEachSymbol([&](Symbol *const sym)
  1600. {
  1601. if (sym->NeedsSlotAlloc(funcInfo))
  1602. {
  1603. // All properties should get correct propertyId here.
  1604. count++;
  1605. }
  1606. });
  1607. if (funcInfo->GetParamScope() != nullptr)
  1608. {
  1609. funcInfo->GetParamScope()->ForEachSymbol([&](Symbol *const sym)
  1610. {
  1611. if (sym->NeedsSlotAlloc(funcInfo))
  1612. {
  1613. // All properties should get correct propertyId here.
  1614. count++;
  1615. }
  1616. });
  1617. }
  1618. // A reparse should result in the same size of the activation object.
  1619. // Exclude functions which were created from the ByteCodeCache.
  1620. AssertMsg(!byteCodeFunction->IsReparsed() || byteCodeFunction->HasGeneratedFromByteCodeCache() ||
  1621. byteCodeFunction->scopeObjectSize == count || byteCodeFunction->m_wasEverAsmjsMode,
  1622. "The activation object size is different between debug and non-debug mode");
  1623. byteCodeFunction->scopeObjectSize = count;
  1624. #endif
  1625. }
  1626. else if (funcInfo->frameSlotsRegister != Js::Constants::NoRegister)
  1627. {
  1628. int scopeSlotCount = funcInfo->bodyScope->GetScopeSlotCount();
  1629. if (scopeSlotCount == 0)
  1630. {
  1631. AssertMsg(funcInfo->frameDisplayRegister != Js::Constants::NoRegister, "Why do we need scope slots?");
  1632. m_writer.Reg1(Js::OpCode::LdC_A_Null, funcInfo->frameSlotsRegister);
  1633. }
  1634. }
  1635. if (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject())
  1636. {
  1637. byteCodeFunction->SetFuncExprScopeReg(funcInfo->funcExprScope->GetLocation());
  1638. byteCodeFunction->SetEnvDepth((uint16)-1);
  1639. }
  1640. bool thisLoadedFromParams = false;
  1641. if (funcInfo->NeedEnvRegister())
  1642. {
  1643. byteCodeFunction->SetEnvReg(funcInfo->GetEnvRegister());
  1644. if (funcInfo->GetIsEventHandler())
  1645. {
  1646. byteCodeFunction->SetThisRegForEventHandler(funcInfo->thisPointerRegister);
  1647. // The environment is the namespace hierarchy starting with "this".
  1648. Assert(!funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1649. thisLoadedFromParams = true;
  1650. this->InvalidateCachedOuterScopes(funcInfo);
  1651. }
  1652. else if (funcInfo->IsGlobalFunction() && !(this->flags & fscrEval))
  1653. {
  1654. Assert(funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1655. if (funcInfo->GetIsStrictMode())
  1656. {
  1657. byteCodeFunction->RecordStrictNullDisplayConstant(byteCodeFunction->MapRegSlot(funcInfo->GetEnvRegister()));
  1658. }
  1659. else
  1660. {
  1661. byteCodeFunction->RecordNullDisplayConstant(byteCodeFunction->MapRegSlot(funcInfo->GetEnvRegister()));
  1662. }
  1663. }
  1664. else
  1665. {
  1666. // environment may be required to load "this"
  1667. Assert(!funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1668. this->InvalidateCachedOuterScopes(funcInfo);
  1669. }
  1670. }
  1671. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  1672. {
  1673. m_writer.RecordFrameDisplayRegister(funcInfo->frameDisplayRegister);
  1674. }
  1675. // new.target may be used to construct the 'this' register so make sure to load it first
  1676. if (funcInfo->newTargetRegister != Js::Constants::NoRegister)
  1677. {
  1678. this->LoadNewTargetObject(funcInfo);
  1679. }
  1680. if (funcInfo->thisPointerRegister != Js::Constants::NoRegister)
  1681. {
  1682. this->LoadThisObject(funcInfo, thisLoadedFromParams);
  1683. }
  1684. this->RecordAllIntConstants(funcInfo);
  1685. this->RecordAllStrConstants(funcInfo);
  1686. this->RecordAllStringTemplateCallsiteConstants(funcInfo);
  1687. funcInfo->doubleConstantToRegister.Map([byteCodeFunction](double d, Js::RegSlot location)
  1688. {
  1689. byteCodeFunction->RecordFloatConstant(byteCodeFunction->MapRegSlot(location), d);
  1690. });
  1691. if (funcInfo->GetHasArguments())
  1692. {
  1693. sym = funcInfo->GetArgumentsSymbol();
  1694. Assert(sym);
  1695. Assert(funcInfo->GetHasHeapArguments());
  1696. if (funcInfo->GetCallsEval() || (!funcInfo->GetApplyEnclosesArgs()))
  1697. {
  1698. this->LoadHeapArguments(funcInfo);
  1699. }
  1700. }
  1701. else if (!funcInfo->IsGlobalFunction() && !IsInNonDebugMode())
  1702. {
  1703. uint count = funcInfo->inArgsCount + (funcInfo->root->sxFnc.pnodeRest != nullptr ? 1 : 0) - 1;
  1704. if (count != 0)
  1705. {
  1706. Js::PropertyIdArray *propIds = RecyclerNewPlus(scriptContext->GetRecycler(), count * sizeof(Js::PropertyId), Js::PropertyIdArray, count);
  1707. GetFormalArgsArray(this, funcInfo, propIds);
  1708. byteCodeFunction->SetPropertyIdsOfFormals(propIds);
  1709. }
  1710. }
  1711. //
  1712. // If the function is a function expression with a name,
  1713. // load the function object at runtime to its activation object.
  1714. //
  1715. sym = funcInfo->root->sxFnc.GetFuncSymbol();
  1716. bool funcExprWithName = !funcInfo->IsGlobalFunction() && sym && sym->GetFuncExpr();
  1717. if (funcExprWithName)
  1718. {
  1719. if (funcInfo->GetFuncExprNameReference() ||
  1720. (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject()))
  1721. {
  1722. //
  1723. // x = function f(...) { ... }
  1724. // A named function expression's name (Symbol:f) belongs to the enclosing scope.
  1725. // Thus there are no uses of 'f' within the scope of the function (as references to 'f'
  1726. // are looked up in the closure). So, we can't use f's register as it is from the enclosing
  1727. // scope's register namespace. So use a tmp register.
  1728. // In ES5 mode though 'f' is *not* a part of the enclosing scope. So we always assign 'f' a register
  1729. // from it's register namespace, which LdFuncExpr can use.
  1730. //
  1731. Js::RegSlot ldFuncExprDst = sym->GetLocation();
  1732. this->m_writer.Reg1(Js::OpCode::LdFuncExpr, ldFuncExprDst);
  1733. if (sym->IsInSlot(funcInfo))
  1734. {
  1735. Assert(!this->TopFuncInfo()->GetParsedFunctionBody()->DoStackNestedFunc());
  1736. Js::RegSlot scopeLocation;
  1737. AnalysisAssert(funcInfo->funcExprScope);
  1738. if (funcInfo->funcExprScope->GetIsObject())
  1739. {
  1740. scopeLocation = funcInfo->funcExprScope->GetLocation();
  1741. this->m_writer.Property(Js::OpCode::StFuncExpr, sym->GetLocation(), scopeLocation,
  1742. funcInfo->FindOrAddReferencedPropertyId(sym->GetPosition()));
  1743. }
  1744. else
  1745. {
  1746. this->m_writer.ElementU(Js::OpCode::StLocalFuncExpr, sym->GetLocation(),
  1747. funcInfo->FindOrAddReferencedPropertyId(sym->GetPosition()));
  1748. }
  1749. }
  1750. else if (ShouldTrackDebuggerMetadata())
  1751. {
  1752. funcInfo->byteCodeFunction->GetFunctionBody()->InsertSymbolToRegSlotList(sym->GetName(), sym->GetLocation(), funcInfo->varRegsCount);
  1753. }
  1754. }
  1755. }
  1756. }
  1757. void ByteCodeGenerator::InvalidateCachedOuterScopes(FuncInfo *funcInfo)
  1758. {
  1759. Assert(funcInfo->GetEnvRegister() != Js::Constants::NoRegister);
  1760. // Walk the scope stack, from funcInfo outward, looking for scopes that have been cached.
  1761. Scope *scope = funcInfo->GetBodyScope()->GetEnclosingScope();
  1762. uint32 envIndex = 0;
  1763. while (scope && scope->GetFunc() == funcInfo)
  1764. {
  1765. // Skip over FuncExpr Scope and parameter scope for current funcInfo to get to the first enclosing scope of the outer function.
  1766. scope = scope->GetEnclosingScope();
  1767. }
  1768. for (; scope; scope = scope->GetEnclosingScope())
  1769. {
  1770. FuncInfo *func = scope->GetFunc();
  1771. if (scope == func->GetBodyScope())
  1772. {
  1773. if (func->Escapes() && func->GetHasCachedScope())
  1774. {
  1775. Assert(scope->GetIsObject());
  1776. this->m_writer.Unsigned1(Js::OpCode::InvalCachedScope, envIndex);
  1777. }
  1778. }
  1779. if (scope->GetMustInstantiate())
  1780. {
  1781. envIndex++;
  1782. }
  1783. }
  1784. }
  1785. void ByteCodeGenerator::LoadThisObject(FuncInfo *funcInfo, bool thisLoadedFromParams)
  1786. {
  1787. if (this->scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled() && funcInfo->IsClassConstructor())
  1788. {
  1789. // Derived class constructors initialize 'this' to be Undecl
  1790. // - we'll check this value during a super call and during 'this' access
  1791. // Base class constructors initialize 'this' to a new object using new.target
  1792. if (funcInfo->IsBaseClassConstructor())
  1793. {
  1794. EmitBaseClassConstructorThisObject(funcInfo);
  1795. }
  1796. else
  1797. {
  1798. this->m_writer.Reg1(Js::OpCode::InitUndecl, funcInfo->thisPointerRegister);
  1799. }
  1800. }
  1801. else if (!funcInfo->IsGlobalFunction() || (this->flags & fscrEval))
  1802. {
  1803. //
  1804. // thisLoadedFromParams would be true for the event Handler case,
  1805. // "this" would have been loaded from parameters to put in the environment
  1806. //
  1807. if (!thisLoadedFromParams && !funcInfo->IsLambda())
  1808. {
  1809. m_writer.ArgIn0(funcInfo->thisPointerRegister);
  1810. }
  1811. if (!(this->flags & fscrEval) || !funcInfo->IsGlobalFunction())
  1812. {
  1813. // we don't want to emit 'this' for eval, because 'this' value in eval is equal to 'this' value of caller
  1814. // and does not depend on "use strict" inside of eval.
  1815. // so we pass 'this' directly in GlobalObject::EntryEval()
  1816. EmitThis(funcInfo, funcInfo->thisPointerRegister);
  1817. }
  1818. }
  1819. else
  1820. {
  1821. Assert(funcInfo->IsGlobalFunction());
  1822. Js::RegSlot root = funcInfo->nullConstantRegister;
  1823. EmitThis(funcInfo, root);
  1824. }
  1825. }
  1826. void ByteCodeGenerator::LoadNewTargetObject(FuncInfo *funcInfo)
  1827. {
  1828. if (funcInfo->IsClassConstructor())
  1829. {
  1830. Assert(!funcInfo->IsLambda());
  1831. m_writer.ArgIn0(funcInfo->newTargetRegister);
  1832. }
  1833. else if (funcInfo->IsLambda() && !(this->flags & fscrEval))
  1834. {
  1835. Scope *scope;
  1836. Js::PropertyId envIndex = -1;
  1837. GetEnclosingNonLambdaScope(funcInfo, scope, envIndex);
  1838. if (scope->GetFunc()->IsGlobalFunction())
  1839. {
  1840. m_writer.Reg1(Js::OpCode::LdUndef, funcInfo->newTargetRegister);
  1841. }
  1842. else
  1843. {
  1844. Js::PropertyId slot = scope->GetFunc()->newTargetScopeSlot;
  1845. EmitInternalScopedSlotLoad(funcInfo, scope, envIndex, slot, funcInfo->newTargetRegister);
  1846. }
  1847. }
  1848. else if (this->flags & fscrEval)
  1849. {
  1850. Js::RegSlot scopeLocation;
  1851. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  1852. {
  1853. scopeLocation = funcInfo->frameDisplayRegister;
  1854. }
  1855. else if (funcInfo->NeedEnvRegister())
  1856. {
  1857. scopeLocation = funcInfo->GetEnvRegister();
  1858. }
  1859. else
  1860. {
  1861. // If this eval doesn't have environment register or frame display register, we didn't capture anything from a class constructor.
  1862. m_writer.Reg1(Js::OpCode::LdNewTarget, funcInfo->newTargetRegister);
  1863. return;
  1864. }
  1865. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, Js::PropertyIds::_lexicalNewTargetSymbol, false, false);
  1866. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, funcInfo->newTargetRegister, cacheId);
  1867. }
  1868. else if (funcInfo->IsGlobalFunction())
  1869. {
  1870. m_writer.Reg1(Js::OpCode::LdUndef, funcInfo->newTargetRegister);
  1871. }
  1872. else
  1873. {
  1874. m_writer.Reg1(Js::OpCode::LdNewTarget, funcInfo->newTargetRegister);
  1875. }
  1876. }
  1877. void ByteCodeGenerator::EmitScopeSlotLoadThis(FuncInfo *funcInfo, Js::RegSlot regLoc, bool chkUndecl)
  1878. {
  1879. FuncInfo* nonLambdaFunc = funcInfo;
  1880. if (funcInfo->IsLambda())
  1881. {
  1882. nonLambdaFunc = FindEnclosingNonLambda();
  1883. }
  1884. if (nonLambdaFunc->IsClassConstructor() && !nonLambdaFunc->IsBaseClassConstructor())
  1885. {
  1886. // If we are in a derived class constructor and we have a scope slot for 'this',
  1887. // we need to load 'this' from the scope slot. This is to support the case where
  1888. // the call to initialize 'this' via super() is inside a lambda since the lambda
  1889. // can't assign to the 'this' register of the parent constructor.
  1890. if (nonLambdaFunc->thisScopeSlot != Js::Constants::NoRegister)
  1891. {
  1892. Js::PropertyId slot = nonLambdaFunc->thisScopeSlot;
  1893. EmitInternalScopedSlotLoad(funcInfo, slot, regLoc, chkUndecl);
  1894. }
  1895. else if (funcInfo->thisPointerRegister != Js::Constants::NoRegister && chkUndecl)
  1896. {
  1897. this->m_writer.Reg1(Js::OpCode::ChkUndecl, funcInfo->thisPointerRegister);
  1898. }
  1899. else if (chkUndecl)
  1900. {
  1901. // If we don't have a scope slot for 'this' we know that super could not have
  1902. // been called inside a lambda so we can check to see if we called
  1903. // super and assigned to the this register already. If not, this should trigger
  1904. // a ReferenceError.
  1905. EmitUseBeforeDeclarationRuntimeError(this, regLoc, false);
  1906. }
  1907. }
  1908. else if (this->flags & fscrEval && (funcInfo->IsGlobalFunction() || (funcInfo->IsLambda() && nonLambdaFunc->IsGlobalFunction()))
  1909. && funcInfo->GetBodyScope()->GetIsObject())
  1910. {
  1911. Js::RegSlot scopeLocation;
  1912. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  1913. {
  1914. scopeLocation = funcInfo->frameDisplayRegister;
  1915. }
  1916. else if (funcInfo->NeedEnvRegister())
  1917. {
  1918. scopeLocation = funcInfo->GetEnvRegister();
  1919. }
  1920. else
  1921. {
  1922. // If this eval doesn't have environment register or frame display register, we didn't capture anything from a class constructor
  1923. return;
  1924. }
  1925. // CONSIDER [tawoll] - Should we add a ByteCodeGenerator flag (fscrEvalWithClassConstructorParent) and avoid doing this runtime check?
  1926. Js::ByteCodeLabel skipLabel = this->Writer()->DefineLabel();
  1927. this->Writer()->BrReg1(Js::OpCode::BrNotUndecl_A, skipLabel, funcInfo->thisPointerRegister);
  1928. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, Js::PropertyIds::_lexicalThisSlotSymbol, false, false);
  1929. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, funcInfo->thisPointerRegister, cacheId);
  1930. if (chkUndecl)
  1931. {
  1932. this->m_writer.Reg1(Js::OpCode::ChkUndecl, funcInfo->thisPointerRegister);
  1933. }
  1934. this->Writer()->MarkLabel(skipLabel);
  1935. }
  1936. }
  1937. void ByteCodeGenerator::EmitScopeSlotStoreThis(FuncInfo *funcInfo, Js::RegSlot regLoc, bool chkUndecl)
  1938. {
  1939. if (this->flags & fscrEval && (funcInfo->IsGlobalFunction() || (funcInfo->IsLambda() && FindEnclosingNonLambda()->IsGlobalFunction())))
  1940. {
  1941. Js::RegSlot scopeLocation;
  1942. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  1943. {
  1944. scopeLocation = funcInfo->frameDisplayRegister;
  1945. }
  1946. else
  1947. {
  1948. scopeLocation = funcInfo->GetEnvRegister();
  1949. }
  1950. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, Js::PropertyIds::_lexicalThisSlotSymbol, false, true);
  1951. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo->byteCodeFunction->GetIsStrictMode()), funcInfo->thisPointerRegister, cacheId);
  1952. }
  1953. else if (regLoc != Js::Constants::NoRegister)
  1954. {
  1955. EmitInternalScopedSlotStore(funcInfo, regLoc, funcInfo->thisPointerRegister);
  1956. }
  1957. }
  1958. void ByteCodeGenerator::EmitSuperCall(FuncInfo* funcInfo, ParseNode* pnode, BOOL fReturnValue)
  1959. {
  1960. Assert(pnode->sxCall.pnodeTarget->nop == knopSuper);
  1961. FuncInfo* nonLambdaFunc = funcInfo;
  1962. if (funcInfo->IsLambda())
  1963. {
  1964. nonLambdaFunc = this->FindEnclosingNonLambda();
  1965. }
  1966. if (nonLambdaFunc->IsBaseClassConstructor())
  1967. {
  1968. // super() is not allowed in base class constructors. If we detect this, emit a ReferenceError and skip making the call.
  1969. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_ClassSuperInBaseClass));
  1970. return;
  1971. }
  1972. else
  1973. {
  1974. EmitSuperFieldPatch(funcInfo, pnode, this);
  1975. pnode->isUsed = true;
  1976. }
  1977. // We already know pnode->sxCall.pnodeTarget->nop is super but we can't use the super register in case
  1978. // this is an eval and we will load super dynamically from the scope using ScopedLdSuper.
  1979. // That means we'll have to rely on the location of the call target to be sure.
  1980. // We have to make sure to allocate the location for the node now, before we try to branch on it.
  1981. Emit(pnode->sxCall.pnodeTarget, this, funcInfo, false, /*isConstructorCall*/ true); // reuse isConstructorCall ("new super()" is illegal)
  1982. //
  1983. // if (super is class constructor) {
  1984. // _this = new.target;
  1985. // } else {
  1986. // _this = NewScObjFull(new.target);
  1987. // }
  1988. //
  1989. // temp = super.call(_this, new.target); // CallFlag_New | CallFlag_NewTarget | CallFlag_ExtraArg
  1990. // if (temp is object) {
  1991. // _this = temp;
  1992. // }
  1993. //
  1994. // if (UndeclBlockVar === this) {
  1995. // this = _this;
  1996. // } else {
  1997. // throw ReferenceError;
  1998. // }
  1999. //
  2000. funcInfo->AcquireLoc(pnode);
  2001. Js::RegSlot thisForSuperCall = funcInfo->AcquireTmpRegister();
  2002. Js::ByteCodeLabel useNewTargetForThisLabel = this->Writer()->DefineLabel();
  2003. Js::ByteCodeLabel makeCallLabel = this->Writer()->DefineLabel();
  2004. Js::ByteCodeLabel useSuperCallResultLabel = this->Writer()->DefineLabel();
  2005. Js::ByteCodeLabel doneLabel = this->Writer()->DefineLabel();
  2006. this->Writer()->BrReg1(Js::OpCode::BrOnClassConstructor, useNewTargetForThisLabel, pnode->sxCall.pnodeTarget->location);
  2007. this->Writer()->Reg2(Js::OpCode::NewScObjectNoCtorFull, thisForSuperCall, funcInfo->newTargetRegister);
  2008. this->Writer()->Br(Js::OpCode::Br, makeCallLabel);
  2009. this->Writer()->MarkLabel(useNewTargetForThisLabel);
  2010. this->Writer()->Reg2(Js::OpCode::Ld_A, thisForSuperCall, funcInfo->newTargetRegister);
  2011. this->Writer()->MarkLabel(makeCallLabel);
  2012. EmitCall(pnode, Js::Constants::NoRegister, this, funcInfo, fReturnValue, /*fEvaluateComponents*/ true, /*fHasNewTarget*/ true, thisForSuperCall);
  2013. // We have to use another temp for the this value before assigning to this register.
  2014. // This is because IRBuilder does not expect us to use the value of a temp after potentially assigning to that same temp.
  2015. // Ex:
  2016. // _this = new.target;
  2017. // temp = super.call(_this);
  2018. // if (temp is object) {
  2019. // _this = temp; // creates a new sym for _this as it was previously used
  2020. // }
  2021. // this = _this; // tries to loads a value from the old sym (which is dead)
  2022. Js::RegSlot valueForThis = funcInfo->AcquireTmpRegister();
  2023. this->Writer()->BrReg1(Js::OpCode::BrOnObject_A, useSuperCallResultLabel, pnode->location);
  2024. this->Writer()->Reg2(Js::OpCode::Ld_A, valueForThis, thisForSuperCall);
  2025. this->Writer()->Br(Js::OpCode::Br, doneLabel);
  2026. this->Writer()->MarkLabel(useSuperCallResultLabel);
  2027. this->Writer()->Reg2(Js::OpCode::Ld_A, valueForThis, pnode->location);
  2028. this->Writer()->MarkLabel(doneLabel);
  2029. // The call is done and we know what we will bind to 'this' so let's check to see if 'this' is already decl.
  2030. // We may need to load 'this' from the scope slot.
  2031. EmitScopeSlotLoadThis(funcInfo, funcInfo->thisPointerRegister, false);
  2032. Js::ByteCodeLabel skipLabel = this->Writer()->DefineLabel();
  2033. Js::RegSlot tmpUndeclReg = funcInfo->AcquireTmpRegister();
  2034. this->Writer()->Reg1(Js::OpCode::InitUndecl, tmpUndeclReg);
  2035. this->Writer()->BrReg2(Js::OpCode::BrSrEq_A, skipLabel, funcInfo->thisPointerRegister, tmpUndeclReg);
  2036. funcInfo->ReleaseTmpRegister(tmpUndeclReg);
  2037. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_ClassThisAlreadyAssigned));
  2038. this->Writer()->MarkLabel(skipLabel);
  2039. this->Writer()->Reg2(Js::OpCode::StrictLdThis, funcInfo->thisPointerRegister, valueForThis);
  2040. funcInfo->ReleaseTmpRegister(valueForThis);
  2041. funcInfo->ReleaseTmpRegister(thisForSuperCall);
  2042. // 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.
  2043. this->EmitScopeSlotStoreThis(funcInfo, nonLambdaFunc->thisScopeSlot);
  2044. }
  2045. void ByteCodeGenerator::EmitClassConstructorEndCode(FuncInfo *funcInfo)
  2046. {
  2047. if (funcInfo->thisPointerRegister != Js::Constants::NoRegister)
  2048. {
  2049. // We need to try and load 'this' from the scope slot, if there is one.
  2050. EmitScopeSlotLoadThis(funcInfo, funcInfo->thisPointerRegister);
  2051. this->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, funcInfo->thisPointerRegister);
  2052. }
  2053. else
  2054. {
  2055. // This is the case where we don't have any references to this or super in the constructor or any nested lambda functions.
  2056. // We know 'this' must be undecl so let's just emit the ReferenceError as part of the fallthrough.
  2057. EmitUseBeforeDeclarationRuntimeError(this, ByteCodeGenerator::ReturnRegister, true);
  2058. }
  2059. }
  2060. void ByteCodeGenerator::EmitBaseClassConstructorThisObject(FuncInfo *funcInfo)
  2061. {
  2062. this->Writer()->Reg2(Js::OpCode::NewScObjectNoCtorFull, funcInfo->thisPointerRegister, funcInfo->newTargetRegister);
  2063. }
  2064. void ByteCodeGenerator::EmitInternalScopedSlotLoad(FuncInfo *funcInfo, Js::RegSlot slot, Js::RegSlot symbolRegister, bool chkUndecl)
  2065. {
  2066. Scope* scope = nullptr;
  2067. if (funcInfo->IsLambda())
  2068. {
  2069. Js::PropertyId envIndex = -1;
  2070. GetEnclosingNonLambdaScope(funcInfo, scope, envIndex);
  2071. EmitInternalScopedSlotLoad(funcInfo, scope, envIndex, slot, symbolRegister, chkUndecl);
  2072. }
  2073. else
  2074. {
  2075. scope = funcInfo->GetBodyScope();
  2076. EmitInternalScopedSlotLoad(funcInfo, scope, -1, slot, symbolRegister, chkUndecl);
  2077. }
  2078. }
  2079. void ByteCodeGenerator::EmitInternalScopedSlotLoad(FuncInfo *funcInfo, Scope *scope, Js::PropertyId envIndex, Js::RegSlot slot, Js::RegSlot symbolRegister, bool chkUndecl)
  2080. {
  2081. Assert(slot != Js::Constants::NoProperty);
  2082. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(scope, symbolRegister);
  2083. Js::OpCode opcode;
  2084. Js::RegSlot scopeLocation = scope->GetLocation();
  2085. opcode = this->GetLdSlotOp(scope, envIndex, scopeLocation, funcInfo);
  2086. slot += (scope->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  2087. if (envIndex != -1)
  2088. {
  2089. this->m_writer.SlotI2(opcode, symbolRegister, envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var), slot, profileId);
  2090. }
  2091. else if (scopeLocation != Js::Constants::NoRegister &&
  2092. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  2093. {
  2094. this->m_writer.SlotI1(opcode, symbolRegister, slot, profileId);
  2095. }
  2096. else
  2097. {
  2098. this->m_writer.Slot(opcode, symbolRegister, scopeLocation, slot, profileId);
  2099. }
  2100. if (chkUndecl)
  2101. {
  2102. this->m_writer.Reg1(Js::OpCode::ChkUndecl, symbolRegister);
  2103. }
  2104. }
  2105. void ByteCodeGenerator::EmitInternalScopedSlotStore(FuncInfo *funcInfo, Js::RegSlot slot, Js::RegSlot symbolRegister)
  2106. {
  2107. Assert(slot != Js::Constants::NoProperty);
  2108. Scope* scope = nullptr;
  2109. Js::OpCode opcode;
  2110. Js::PropertyId envIndex = -1;
  2111. if (funcInfo->IsLambda())
  2112. {
  2113. GetEnclosingNonLambdaScope(funcInfo, scope, envIndex);
  2114. }
  2115. else
  2116. {
  2117. scope = funcInfo->GetBodyScope();
  2118. }
  2119. Js::RegSlot scopeLocation = scope->GetLocation();
  2120. opcode = this->GetStSlotOp(scope, envIndex, scopeLocation, false, funcInfo);
  2121. slot += (scope->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  2122. if (envIndex != -1)
  2123. {
  2124. this->m_writer.SlotI2(opcode, symbolRegister, envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var), slot);
  2125. }
  2126. else if (scopeLocation != Js::Constants::NoRegister &&
  2127. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  2128. {
  2129. this->m_writer.SlotI1(opcode, symbolRegister, slot);
  2130. }
  2131. else if (scope->GetIsObject())
  2132. {
  2133. this->m_writer.Slot(opcode, symbolRegister, scopeLocation, slot);
  2134. }
  2135. else
  2136. {
  2137. this->m_writer.SlotI2(opcode, symbolRegister, scope->GetInnerScopeIndex(), slot);
  2138. }
  2139. }
  2140. void ByteCodeGenerator::EmitInternalScopeObjInit(FuncInfo *funcInfo, Scope *scope, Js::RegSlot valueLocation, Js::PropertyId propertyId)
  2141. {
  2142. Js::RegSlot scopeLocation = scope->GetLocation();
  2143. Js::OpCode opcode = this->GetInitFldOp(scope, scopeLocation, funcInfo);
  2144. if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  2145. {
  2146. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  2147. this->m_writer.ElementP(opcode, valueLocation, cacheId);
  2148. }
  2149. else if (scope->HasInnerScopeIndex())
  2150. {
  2151. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
  2152. this->m_writer.ElementPIndexed(opcode, valueLocation, scope->GetInnerScopeIndex(), cacheId);
  2153. }
  2154. else
  2155. {
  2156. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  2157. this->m_writer.PatchableProperty(opcode, valueLocation, scopeLocation, cacheId);
  2158. }
  2159. }
  2160. void ByteCodeGenerator::GetEnclosingNonLambdaScope(FuncInfo *funcInfo, Scope * &scope, Js::PropertyId &envIndex)
  2161. {
  2162. envIndex = -1;
  2163. for (scope = funcInfo->GetBodyScope()->GetEnclosingScope(); scope; scope = scope->GetEnclosingScope())
  2164. {
  2165. if (scope->GetMustInstantiate())
  2166. {
  2167. envIndex++;
  2168. }
  2169. if ((scope == scope->GetFunc()->GetBodyScope() && !scope->GetFunc()->IsLambda()) || scope->IsGlobalEvalBlockScope())
  2170. {
  2171. break;
  2172. }
  2173. }
  2174. }
  2175. void ByteCodeGenerator::EmitThis(FuncInfo *funcInfo, Js::RegSlot fromRegister)
  2176. {
  2177. if (funcInfo->IsLambda())
  2178. {
  2179. Scope *scope;
  2180. Js::PropertyId envIndex = -1;
  2181. GetEnclosingNonLambdaScope(funcInfo, scope, envIndex);
  2182. FuncInfo* parent = scope->GetFunc();
  2183. if (parent->IsGlobalFunction())
  2184. {
  2185. if (this->flags & fscrEval)
  2186. {
  2187. scope = parent->GetGlobalEvalBlockScope();
  2188. Js::PropertyId slot = parent->thisScopeSlot;
  2189. EmitInternalScopedSlotLoad(funcInfo, scope, envIndex, slot, funcInfo->thisPointerRegister, false);
  2190. }
  2191. else
  2192. {
  2193. // Always load global object via LdThis of null to get the possibly protected via secureHostObject global object.
  2194. this->m_writer.Reg2Int1(Js::OpCode::LdThis, funcInfo->thisPointerRegister, funcInfo->nullConstantRegister, this->GetModuleID());
  2195. }
  2196. }
  2197. else if (!parent->IsClassConstructor() || parent->IsBaseClassConstructor())
  2198. {
  2199. // In a lambda inside a derived class constructor, 'this' should be loaded from the scope slot whenever 'this' is accessed.
  2200. // It's safe to load 'this' into the register for base class constructors because there is no complex assignment to 'this'
  2201. // via super call chain.
  2202. Js::PropertyId slot = parent->thisScopeSlot;
  2203. EmitInternalScopedSlotLoad(funcInfo, scope, envIndex, slot, funcInfo->thisPointerRegister, false);
  2204. }
  2205. }
  2206. else if (funcInfo->byteCodeFunction->GetIsStrictMode() && (!funcInfo->IsGlobalFunction() || this->flags & fscrEval))
  2207. {
  2208. m_writer.Reg2(Js::OpCode::StrictLdThis, funcInfo->thisPointerRegister, fromRegister);
  2209. }
  2210. else
  2211. {
  2212. m_writer.Reg2Int1(Js::OpCode::LdThis, funcInfo->thisPointerRegister, fromRegister, this->GetModuleID());
  2213. }
  2214. }
  2215. void ByteCodeGenerator::EmitLoadFormalIntoRegister(ParseNode *pnodeFormal, Js::RegSlot pos, FuncInfo *funcInfo)
  2216. {
  2217. if (pnodeFormal->IsVarLetOrConst())
  2218. {
  2219. // Get the param from its argument position into its assigned register.
  2220. // The position should match the location, otherwise, it has been shadowed by parameter with the same name
  2221. Symbol *formal = pnodeFormal->sxVar.sym;
  2222. if (formal->GetLocation() + 1 == pos)
  2223. {
  2224. // Transfer to the frame object, etc., if necessary.
  2225. this->EmitLocalPropInit(formal->GetLocation(), formal, funcInfo);
  2226. }
  2227. if (ShouldTrackDebuggerMetadata() && !formal->IsInSlot(funcInfo))
  2228. {
  2229. Assert(!formal->GetHasInit());
  2230. funcInfo->GetParsedFunctionBody()->InsertSymbolToRegSlotList(formal->GetName(), formal->GetLocation(), funcInfo->varRegsCount);
  2231. }
  2232. }
  2233. }
  2234. void ByteCodeGenerator::HomeArguments(FuncInfo *funcInfo)
  2235. {
  2236. // Transfer formal parameters to their home locations on the local frame.
  2237. if (funcInfo->GetHasArguments())
  2238. {
  2239. if (funcInfo->root->sxFnc.pnodeRest != nullptr)
  2240. {
  2241. // Since we don't have to iterate over arguments here, we'll trust the location to be correct.
  2242. EmitLoadFormalIntoRegister(funcInfo->root->sxFnc.pnodeRest, funcInfo->root->sxFnc.pnodeRest->sxVar.sym->GetLocation() + 1, funcInfo);
  2243. }
  2244. // The arguments object creation helper does this work for us.
  2245. return;
  2246. }
  2247. Js::ArgSlot pos = 1;
  2248. auto loadFormal = [&](ParseNode *pnodeFormal)
  2249. {
  2250. EmitLoadFormalIntoRegister(pnodeFormal, pos, funcInfo);
  2251. pos++;
  2252. };
  2253. MapFormals(funcInfo->root, loadFormal);
  2254. }
  2255. void ByteCodeGenerator::DefineLabels(FuncInfo *funcInfo)
  2256. {
  2257. funcInfo->singleExit = m_writer.DefineLabel();
  2258. SList<ParseNode *>::Iterator iter(&funcInfo->targetStatements);
  2259. while (iter.Next())
  2260. {
  2261. ParseNode * node = iter.Data();
  2262. node->sxStmt.breakLabel = m_writer.DefineLabel();
  2263. node->sxStmt.continueLabel = m_writer.DefineLabel();
  2264. node->emitLabels = true;
  2265. }
  2266. }
  2267. void ByteCodeGenerator::EmitGlobalBody(FuncInfo *funcInfo)
  2268. {
  2269. // Emit global code (global scope or eval), fixing up the return register with the implicit
  2270. // return value.
  2271. ParseNode *pnode = funcInfo->root->sxFnc.pnodeBody;
  2272. ParseNode *pnodeLastVal = funcInfo->root->sxProg.pnodeLastValStmt;
  2273. if (pnodeLastVal == nullptr)
  2274. {
  2275. // We're not guaranteed to compute any values, so fix up the return register at the top
  2276. // in case.
  2277. this->m_writer.Reg1(Js::OpCode::LdUndef, ReturnRegister);
  2278. }
  2279. while (pnode->nop == knopList)
  2280. {
  2281. ParseNode *stmt = pnode->sxBin.pnode1;
  2282. if (stmt == pnodeLastVal)
  2283. {
  2284. pnodeLastVal = nullptr;
  2285. }
  2286. if (pnodeLastVal == nullptr && (this->flags & fscrReturnExpression))
  2287. {
  2288. EmitTopLevelStatement(stmt, funcInfo, true);
  2289. }
  2290. else
  2291. {
  2292. // Haven't hit the post-dominating return value yet,
  2293. // so don't bother with the return register.
  2294. EmitTopLevelStatement(stmt, funcInfo, false);
  2295. }
  2296. pnode = pnode->sxBin.pnode2;
  2297. }
  2298. EmitTopLevelStatement(pnode, funcInfo, false);
  2299. }
  2300. void ByteCodeGenerator::EmitFunctionBody(FuncInfo *funcInfo)
  2301. {
  2302. // Emit a function body. Only explicit returns and the implicit "undef" at the bottom
  2303. // get copied to the return register.
  2304. ParseNode *pnodeBody = funcInfo->root->sxFnc.pnodeBody;
  2305. ParseNode *pnode = pnodeBody;
  2306. while (pnode->nop == knopList)
  2307. {
  2308. ParseNode *stmt = pnode->sxBin.pnode1;
  2309. if (stmt->CapturesSyms())
  2310. {
  2311. CapturedSymMap *map = funcInfo->EnsureCapturedSymMap();
  2312. SList<Symbol*> *list = map->Item(stmt);
  2313. FOREACH_SLIST_ENTRY(Symbol*, sym, list)
  2314. {
  2315. if (!sym->GetIsCommittedToSlot())
  2316. {
  2317. Assert(sym->GetLocation() != Js::Constants::NoProperty);
  2318. sym->SetIsCommittedToSlot();
  2319. ParseNode *decl = sym->GetDecl();
  2320. Assert(decl);
  2321. if (PHASE_TRACE(Js::DelayCapturePhase, funcInfo->byteCodeFunction))
  2322. {
  2323. Output::Print(L"--- DelayCapture: Committed symbol '%s' to slot.\n", sym->GetName());
  2324. Output::Flush();
  2325. }
  2326. this->EmitPropStore(sym->GetLocation(), sym, sym->GetPid(), funcInfo, decl->nop == knopLetDecl, decl->nop == knopConstDecl);
  2327. }
  2328. }
  2329. NEXT_SLIST_ENTRY;
  2330. }
  2331. EmitTopLevelStatement(stmt, funcInfo, false);
  2332. pnode = pnode->sxBin.pnode2;
  2333. }
  2334. Assert(!pnode->CapturesSyms());
  2335. EmitTopLevelStatement(pnode, funcInfo, false);
  2336. }
  2337. void ByteCodeGenerator::EmitProgram(ParseNode *pnodeProg)
  2338. {
  2339. // Indicate that the binding phase is over.
  2340. this->isBinding = false;
  2341. this->trackEnvDepth = true;
  2342. AssignPropertyIds(pnodeProg->sxFnc.funcInfo->byteCodeFunction);
  2343. long initSize = this->maxAstSize / AstBytecodeRatioEstimate;
  2344. // Use the temp allocator in bytecode write temp buffer.
  2345. m_writer.InitData(this->alloc, initSize);
  2346. #ifdef LOG_BYTECODE_AST_RATIO
  2347. // log the max Ast size
  2348. Output::Print(L"Max Ast size: %d", initSize);
  2349. #endif
  2350. Assert(pnodeProg && pnodeProg->nop == knopProg);
  2351. if (this->parentScopeInfo)
  2352. {
  2353. // Scope stack is already set up the way we want it, so don't visit the global scope.
  2354. // Start emitting with the nested scope (i.e., the deferred function).
  2355. this->EmitScopeList(pnodeProg->sxProg.pnodeScopes);
  2356. }
  2357. else
  2358. {
  2359. this->EmitScopeList(pnodeProg);
  2360. }
  2361. }
  2362. void ByteCodeGenerator::EmitInitCapturedThis(FuncInfo* funcInfo, Scope* scope)
  2363. {
  2364. if (scope->GetIsObject())
  2365. {
  2366. // Ensure space for the this slot
  2367. this->EmitInternalScopeObjInit(funcInfo, scope, funcInfo->thisPointerRegister, Js::PropertyIds::_lexicalThisSlotSymbol);
  2368. }
  2369. else
  2370. {
  2371. this->EmitInternalScopedSlotStore(funcInfo, funcInfo->thisScopeSlot, funcInfo->thisPointerRegister);
  2372. }
  2373. }
  2374. void ByteCodeGenerator::EmitInitCapturedNewTarget(FuncInfo* funcInfo, Scope* scope)
  2375. {
  2376. if (scope->GetIsObject())
  2377. {
  2378. // Ensure space for the new.target slot
  2379. this->EmitInternalScopeObjInit(funcInfo, scope, funcInfo->newTargetRegister, Js::PropertyIds::_lexicalNewTargetSymbol);
  2380. }
  2381. else
  2382. {
  2383. this->EmitInternalScopedSlotStore(funcInfo, funcInfo->newTargetScopeSlot, funcInfo->newTargetRegister);
  2384. }
  2385. }
  2386. void EmitDestructuredObject(ParseNode *lhs, Js::RegSlot rhsLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  2387. void EmitDestructuredValueOrInitializer(ParseNodePtr lhsElementNode, Js::RegSlot rhsLocation, ParseNodePtr initializer, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  2388. void ByteCodeGenerator::EmitDefaultArgs(FuncInfo *funcInfo, ParseNode *pnode)
  2389. {
  2390. auto emitDefaultArg = [&](ParseNode *pnodeArg)
  2391. {
  2392. if (pnodeArg->nop == knopParamPattern)
  2393. {
  2394. this->StartStatement(pnodeArg);
  2395. Assert(pnodeArg->sxParamPattern.location != Js::Constants::NoRegister);
  2396. ParseNodePtr pnode1 = pnodeArg->sxParamPattern.pnode1;
  2397. if (pnode1->IsPattern())
  2398. {
  2399. EmitAssignment(nullptr, pnode1, pnodeArg->sxParamPattern.location, this, funcInfo);
  2400. }
  2401. else
  2402. {
  2403. Assert(pnode1->nop == knopAsg);
  2404. Assert(pnode1->sxBin.pnode1->IsPattern());
  2405. EmitDestructuredValueOrInitializer(pnode1->sxBin.pnode1, pnodeArg->sxParamPattern.location, pnode1->sxBin.pnode2, this, funcInfo);
  2406. }
  2407. this->EndStatement(pnodeArg);
  2408. return;
  2409. }
  2410. else if (pnodeArg->IsVarLetOrConst())
  2411. {
  2412. Js::RegSlot location = pnodeArg->sxVar.sym->GetLocation();
  2413. if (pnodeArg->sxVar.pnodeInit == nullptr)
  2414. {
  2415. // Since the formal hasn't been initialized in LdLetHeapArguments, we'll initialize it here.
  2416. EmitPropStore(location, pnodeArg->sxVar.sym, pnodeArg->sxVar.pid, funcInfo, true);
  2417. pnodeArg->sxVar.sym->SetNeedDeclaration(false);
  2418. return;
  2419. }
  2420. // Load the default argument if we got undefined, skip RHS evaluation otherwise.
  2421. Js::ByteCodeLabel noDefaultLabel = this->m_writer.DefineLabel();
  2422. Js::ByteCodeLabel endLabel = this->m_writer.DefineLabel();
  2423. this->StartStatement(pnodeArg);
  2424. m_writer.BrReg2(Js::OpCode::BrNeq_A, noDefaultLabel, location, funcInfo->undefinedConstantRegister);
  2425. Emit(pnodeArg->sxVar.pnodeInit, this, funcInfo, false);
  2426. pnodeArg->sxVar.sym->SetNeedDeclaration(false); // After emit to prevent foo(a = a)
  2427. if (funcInfo->GetHasArguments() && pnodeArg->sxVar.sym->IsInSlot(funcInfo))
  2428. {
  2429. EmitPropStore(pnodeArg->sxVar.pnodeInit->location, pnodeArg->sxVar.sym, pnodeArg->sxVar.pid, funcInfo, true);
  2430. m_writer.Br(endLabel);
  2431. }
  2432. else
  2433. {
  2434. EmitAssignment(nullptr, pnodeArg, pnodeArg->sxVar.pnodeInit->location, this, funcInfo);
  2435. }
  2436. funcInfo->ReleaseLoc(pnodeArg->sxVar.pnodeInit);
  2437. m_writer.MarkLabel(noDefaultLabel);
  2438. if (funcInfo->GetHasArguments() && pnodeArg->sxVar.sym->IsInSlot(funcInfo))
  2439. {
  2440. EmitPropStore(location, pnodeArg->sxVar.sym, pnodeArg->sxVar.pid, funcInfo, true);
  2441. m_writer.MarkLabel(endLabel);
  2442. }
  2443. this->EndStatement(pnodeArg);
  2444. }
  2445. };
  2446. // If the function is async, we wrap the default arguments in a try catch and reject a Promise in case of error.
  2447. if (pnode->sxFnc.IsAsync())
  2448. {
  2449. uint cacheId;
  2450. Js::ByteCodeLabel catchLabel = m_writer.DefineLabel();
  2451. Js::ByteCodeLabel doneLabel = m_writer.DefineLabel();
  2452. Js::RegSlot catchArgLocation = funcInfo->AcquireTmpRegister();
  2453. Js::RegSlot promiseLocation = funcInfo->AcquireTmpRegister();
  2454. Js::RegSlot rejectLocation = funcInfo->AcquireTmpRegister();
  2455. // try
  2456. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  2457. m_writer.Br(Js::OpCode::TryCatch, catchLabel);
  2458. // Rest cannot have a default argument, so we ignore it.
  2459. MapFormalsWithoutRest(pnode, emitDefaultArg);
  2460. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  2461. m_writer.Empty(Js::OpCode::Leave);
  2462. m_writer.Br(doneLabel);
  2463. // catch
  2464. m_writer.MarkLabel(catchLabel);
  2465. m_writer.Reg1(Js::OpCode::Catch, catchArgLocation);
  2466. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  2467. m_writer.Empty(Js::OpCode::Nop);
  2468. // return Promise.reject(error);
  2469. cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(Js::PropertyIds::Promise, false, false);
  2470. m_writer.PatchableRootProperty(Js::OpCode::LdRootFld, promiseLocation, cacheId, false, false);
  2471. EmitInvoke(rejectLocation, promiseLocation, Js::PropertyIds::reject, this, funcInfo, catchArgLocation);
  2472. m_writer.Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, rejectLocation);
  2473. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  2474. m_writer.Empty(Js::OpCode::Leave);
  2475. m_writer.Br(funcInfo->singleExit);
  2476. m_writer.Empty(Js::OpCode::Leave);
  2477. m_writer.MarkLabel(doneLabel);
  2478. this->SetHasTry(true);
  2479. funcInfo->ReleaseTmpRegister(rejectLocation);
  2480. funcInfo->ReleaseTmpRegister(promiseLocation);
  2481. funcInfo->ReleaseTmpRegister(catchArgLocation);
  2482. }
  2483. else
  2484. {
  2485. // Rest cannot have a default argument, so we ignore it.
  2486. MapFormalsWithoutRest(pnode, emitDefaultArg);
  2487. }
  2488. }
  2489. void ByteCodeGenerator::EmitOneFunction(ParseNode *pnode)
  2490. {
  2491. Assert(pnode && (pnode->nop == knopProg || pnode->nop == knopFncDecl));
  2492. FuncInfo *funcInfo = pnode->sxFnc.funcInfo;
  2493. Assert(funcInfo != nullptr);
  2494. if (funcInfo->IsFakeGlobalFunction(this->flags))
  2495. {
  2496. return;
  2497. }
  2498. Js::ParseableFunctionInfo* deferParseFunction = funcInfo->byteCodeFunction;
  2499. deferParseFunction->SetGrfscr(deferParseFunction->GetGrfscr() | (this->flags & ~fscrDeferredFncExpression));
  2500. deferParseFunction->SetSourceInfo(this->GetCurrentSourceIndex(),
  2501. funcInfo->root,
  2502. !!(this->flags & fscrEvalCode),
  2503. ((this->flags & fscrDynamicCode) && !(this->flags & fscrEvalCode)));
  2504. deferParseFunction->SetInParamsCount(funcInfo->inArgsCount);
  2505. if (pnode->sxFnc.HasDefaultArguments())
  2506. {
  2507. deferParseFunction->SetReportedInParamsCount(pnode->sxFnc.firstDefaultArg + 1);
  2508. }
  2509. else
  2510. {
  2511. deferParseFunction->SetReportedInParamsCount(funcInfo->inArgsCount);
  2512. }
  2513. if (funcInfo->root->sxFnc.pnodeBody == nullptr)
  2514. {
  2515. if (scriptContext->GetConfig()->BindDeferredPidRefs() &&
  2516. !PHASE_OFF1(Js::SkipNestedDeferredPhase))
  2517. {
  2518. deferParseFunction->BuildDeferredStubs(funcInfo->root);
  2519. }
  2520. return;
  2521. }
  2522. Js::FunctionBody* byteCodeFunction = funcInfo->GetParsedFunctionBody();
  2523. // We've now done a full parse of this function, so we no longer need to remember the extents
  2524. // and attributes of the top-level nested functions. (The above code has run for all of those,
  2525. // so they have pointers to the stub sub-trees they need.)
  2526. byteCodeFunction->SetDeferredStubs(nullptr);
  2527. try
  2528. {
  2529. // Bug : 301517
  2530. // In the debug mode the hasOnlyThis optimization needs to be disabled, since user can break in this function
  2531. // and do operation on 'this' and its property, which may not be defined yet.
  2532. if (funcInfo->root->sxFnc.HasOnlyThisStmts() && !IsInDebugMode())
  2533. {
  2534. byteCodeFunction->SetHasOnlyThisStmts(true);
  2535. }
  2536. if (byteCodeFunction->IsInlineApplyDisabled() || this->scriptContext->GetConfig()->IsNoNative())
  2537. {
  2538. if ((pnode->nop == knopFncDecl) && (funcInfo->GetHasHeapArguments()) && (!funcInfo->GetCallsEval()) && ApplyEnclosesArgs(pnode, this))
  2539. {
  2540. bool applyEnclosesArgs = true;
  2541. for (ParseNode* pnodeVar = funcInfo->root->sxFnc.pnodeVars; pnodeVar; pnodeVar = pnodeVar->sxVar.pnodeNext)
  2542. {
  2543. Symbol* sym = pnodeVar->sxVar.sym;
  2544. if (sym->GetSymbolType() == STVariable && !sym->GetIsArguments())
  2545. {
  2546. applyEnclosesArgs = false;
  2547. break;
  2548. }
  2549. }
  2550. auto constAndLetCheck = [](ParseNode *pnodeBlock, bool *applyEnclosesArgs)
  2551. {
  2552. if (*applyEnclosesArgs)
  2553. {
  2554. for (auto lexvar = pnodeBlock->sxBlock.pnodeLexVars; lexvar; lexvar = lexvar->sxVar.pnodeNext)
  2555. {
  2556. Symbol* sym = lexvar->sxVar.sym;
  2557. if (sym->GetSymbolType() == STVariable && !sym->GetIsArguments())
  2558. {
  2559. *applyEnclosesArgs = false;
  2560. break;
  2561. }
  2562. }
  2563. }
  2564. };
  2565. constAndLetCheck(funcInfo->root->sxFnc.pnodeScopes, &applyEnclosesArgs);
  2566. constAndLetCheck(funcInfo->root->sxFnc.pnodeBodyScope, &applyEnclosesArgs);
  2567. funcInfo->SetApplyEnclosesArgs(applyEnclosesArgs);
  2568. }
  2569. }
  2570. if (!funcInfo->IsGlobalFunction())
  2571. {
  2572. if (CanStackNestedFunc(funcInfo, true))
  2573. {
  2574. #if DBG
  2575. byteCodeFunction->SetCanDoStackNestedFunc();
  2576. #endif
  2577. if (funcInfo->root->sxFnc.astSize <= PnFnc::MaxStackClosureAST)
  2578. {
  2579. byteCodeFunction->SetStackNestedFunc(true);
  2580. }
  2581. }
  2582. }
  2583. InitScopeSlotArray(funcInfo);
  2584. FinalizeRegisters(funcInfo, byteCodeFunction);
  2585. DebugOnly(Js::RegSlot firstTmpReg = funcInfo->varRegsCount);
  2586. // Reserve temp registers for the inner scopes. We prefer temps because the JIT will then renumber them
  2587. // and see different lifetimes. (Note that debug mode requires permanent registers. See FinalizeRegisters.)
  2588. uint innerScopeCount = funcInfo->InnerScopeCount();
  2589. if (!this->IsInDebugMode())
  2590. {
  2591. byteCodeFunction->SetInnerScopeCount(innerScopeCount);
  2592. if (innerScopeCount)
  2593. {
  2594. funcInfo->SetFirstInnerScopeReg(funcInfo->AcquireTmpRegister());
  2595. for (uint i = 1; i < innerScopeCount; i++)
  2596. {
  2597. funcInfo->AcquireTmpRegister();
  2598. }
  2599. }
  2600. }
  2601. funcInfo->inlineCacheMap = Anew(alloc, FuncInfo::InlineCacheMap,
  2602. alloc,
  2603. funcInfo->RegCount() // Pass the actual register count. // TODO: Check if we can reduce this count
  2604. );
  2605. funcInfo->rootObjectLoadInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2606. alloc,
  2607. 10);
  2608. funcInfo->rootObjectLoadMethodInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2609. alloc,
  2610. 10);
  2611. funcInfo->rootObjectStoreInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2612. alloc,
  2613. 10);
  2614. funcInfo->referencedPropertyIdToMapIndex = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2615. alloc,
  2616. 10);
  2617. byteCodeFunction->AllocateLiteralRegexArray();
  2618. m_callSiteId = 0;
  2619. m_writer.Begin(this, byteCodeFunction, alloc, this->DoJitLoopBodies(funcInfo), funcInfo->hasLoop);
  2620. this->PushFuncInfo(L"EmitOneFunction", funcInfo);
  2621. this->inPrologue = true;
  2622. // Class constructors do not have a [[call]] slot but we don't implement a generic way to express this.
  2623. // What we do is emit a check for the new flag here. If we don't have CallFlags_New set, the opcode will throw.
  2624. // We need to do this before emitting 'this' since the base class constructor will try to construct a new object.
  2625. if (funcInfo->IsClassConstructor())
  2626. {
  2627. m_writer.Empty(Js::OpCode::ChkNewCallFlag);
  2628. }
  2629. // For now, emit all constant loads at top of function (should instead put in closest dominator of uses).
  2630. LoadAllConstants(funcInfo);
  2631. HomeArguments(funcInfo);
  2632. if (funcInfo->root->sxFnc.pnodeRest != nullptr)
  2633. {
  2634. byteCodeFunction->SetHasRestParameter();
  2635. }
  2636. if (funcInfo->thisScopeSlot != Js::Constants::NoRegister && !(funcInfo->IsLambda() || (funcInfo->IsGlobalFunction() && this->flags & fscrEval)))
  2637. {
  2638. EmitInitCapturedThis(funcInfo, funcInfo->bodyScope);
  2639. }
  2640. // Any function with a super reference or an eval call inside a class method needs to load super,
  2641. if ((funcInfo->HasSuperReference() || (funcInfo->GetCallsEval() && funcInfo->root->sxFnc.IsClassMember()))
  2642. // unless we are already inside the 'global' scope inside an eval (in which case 'ScopedLdSuper' is emitted at every 'super' reference).
  2643. && !((GetFlags() & fscrEval) && funcInfo->IsGlobalFunction()))
  2644. {
  2645. if (funcInfo->IsLambda())
  2646. {
  2647. Scope *scope;
  2648. Js::PropertyId envIndex = -1;
  2649. GetEnclosingNonLambdaScope(funcInfo, scope, envIndex);
  2650. FuncInfo* parent = scope->GetFunc();
  2651. if (!parent->IsGlobalFunction())
  2652. {
  2653. // lambda in non-global scope (eval and non-eval)
  2654. EmitInternalScopedSlotLoad(funcInfo, scope, envIndex, parent->superScopeSlot, funcInfo->superRegister);
  2655. if (funcInfo->superCtorRegister != Js::Constants::NoRegister)
  2656. {
  2657. EmitInternalScopedSlotLoad(funcInfo, scope, envIndex, parent->superCtorScopeSlot, funcInfo->superCtorRegister);
  2658. }
  2659. }
  2660. else if (!(GetFlags() & fscrEval))
  2661. {
  2662. // lambda in non-eval global scope
  2663. m_writer.Reg1(Js::OpCode::LdUndef, funcInfo->superRegister);
  2664. }
  2665. // lambda in eval global scope: ScopedLdSuper will handle error throwing
  2666. }
  2667. else
  2668. {
  2669. m_writer.Reg1(Js::OpCode::LdSuper, funcInfo->superRegister);
  2670. if (funcInfo->superCtorRegister != Js::Constants::NoRegister) // super() is allowed only in derived class constructors
  2671. {
  2672. m_writer.Reg1(Js::OpCode::LdSuperCtor, funcInfo->superCtorRegister);
  2673. }
  2674. if (!funcInfo->IsGlobalFunction())
  2675. {
  2676. if (funcInfo->bodyScope->GetIsObject() && funcInfo->bodyScope->GetLocation() != Js::Constants::NoRegister)
  2677. {
  2678. // Stash the super reference in case something inside the eval or lambda references it.
  2679. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->bodyScope->GetLocation(), Js::PropertyIds::_superReferenceSymbol, false, true);
  2680. m_writer.ElementP(Js::OpCode::InitLocalFld, funcInfo->superRegister, cacheId);
  2681. if (funcInfo->superCtorRegister != Js::Constants::NoRegister)
  2682. {
  2683. cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->bodyScope->GetLocation(), Js::PropertyIds::_superCtorReferenceSymbol, false, true);
  2684. m_writer.ElementP(Js::OpCode::InitLocalFld, funcInfo->superCtorRegister, cacheId);
  2685. }
  2686. }
  2687. else if (funcInfo->superScopeSlot == Js::Constants::NoProperty || funcInfo->superCtorScopeSlot == Js::Constants::NoProperty)
  2688. {
  2689. // While the diag locals walker will pick up super from scoped slots or an activation object,
  2690. // it will not pick it up when it is only in a register.
  2691. byteCodeFunction->InsertSymbolToRegSlotList(funcInfo->superRegister, Js::PropertyIds::_superReferenceSymbol, funcInfo->varRegsCount);
  2692. if (funcInfo->superCtorRegister != Js::Constants::NoRegister)
  2693. {
  2694. byteCodeFunction->InsertSymbolToRegSlotList(funcInfo->superCtorRegister, Js::PropertyIds::_superCtorReferenceSymbol, funcInfo->varRegsCount);
  2695. }
  2696. }
  2697. }
  2698. }
  2699. }
  2700. if (funcInfo->newTargetScopeSlot != Js::Constants::NoRegister && !funcInfo->IsGlobalFunction())
  2701. {
  2702. EmitInitCapturedNewTarget(funcInfo, funcInfo->bodyScope);
  2703. }
  2704. // We don't want to load super if we are already in an eval. ScopedLdSuper will take care of loading super in that case.
  2705. if (!(GetFlags() & fscrEval) && !funcInfo->bodyScope->GetIsObject())
  2706. {
  2707. if (funcInfo->superScopeSlot != Js::Constants::NoRegister)
  2708. {
  2709. this->EmitInternalScopedSlotStore(funcInfo, funcInfo->superScopeSlot, funcInfo->superRegister);
  2710. }
  2711. if (funcInfo->superCtorScopeSlot != Js::Constants::NoRegister)
  2712. {
  2713. this->EmitInternalScopedSlotStore(funcInfo, funcInfo->superCtorScopeSlot, funcInfo->superCtorRegister);
  2714. }
  2715. }
  2716. if (byteCodeFunction->DoStackNestedFunc())
  2717. {
  2718. uint nestedCount = byteCodeFunction->GetNestedCount();
  2719. for (uint i = 0; i < nestedCount; i++)
  2720. {
  2721. Js::FunctionProxy * nested = byteCodeFunction->GetNestedFunc(i);
  2722. if (nested->IsFunctionBody())
  2723. {
  2724. nested->GetFunctionBody()->SetStackNestedFuncParent(byteCodeFunction);
  2725. }
  2726. }
  2727. }
  2728. if (scriptContext->GetConfig()->IsLetAndConstEnabled() && funcInfo->IsGlobalFunction())
  2729. {
  2730. EnsureNoRedeclarations(pnode->sxFnc.pnodeScopes, funcInfo);
  2731. }
  2732. // Emit all scope-wide function definitions before emitting function bodies
  2733. // so that calls may reference functions they precede lexically.
  2734. // Note, global eval scope is a fake local scope and is handled as if it were
  2735. // a lexical block instead of a true global scope, so do not define the functions
  2736. // here. They will be defined during BeginEmitBlock.
  2737. if (!(funcInfo->IsGlobalFunction() && this->IsEvalWithBlockScopingNoParentScopeInfo()))
  2738. {
  2739. DefineFunctions(funcInfo);
  2740. }
  2741. DefineUserVars(funcInfo);
  2742. ::BeginEmitBlock(pnode->sxFnc.pnodeScopes, this, funcInfo);
  2743. if (pnode->sxFnc.pnodeBodyScope != nullptr)
  2744. {
  2745. ::BeginEmitBlock(pnode->sxFnc.pnodeBodyScope, this, funcInfo);
  2746. }
  2747. DefineLabels(funcInfo);
  2748. if (!pnode->sxFnc.IsSimpleParameterList())
  2749. {
  2750. EmitDefaultArgs(funcInfo, pnode);
  2751. }
  2752. else if (funcInfo->GetHasArguments() && !NeedScopeObjectForArguments(funcInfo, pnode))
  2753. {
  2754. // If we didn't create a scope object and didn't have default args, we still need to transfer the formals to their slots.
  2755. MapFormalsWithoutRest(pnode, [&](ParseNode *pnodeArg) { EmitPropStore(pnodeArg->sxVar.sym->GetLocation(), pnodeArg->sxVar.sym, pnodeArg->sxVar.pid, funcInfo); });
  2756. }
  2757. // Rest needs to trigger use before declaration until all default args have been processed.
  2758. if (pnode->sxFnc.pnodeRest != nullptr)
  2759. {
  2760. pnode->sxFnc.pnodeRest->sxVar.sym->SetNeedDeclaration(false);
  2761. }
  2762. this->inPrologue = false;
  2763. if (funcInfo->IsGlobalFunction())
  2764. {
  2765. EmitGlobalBody(funcInfo);
  2766. }
  2767. else
  2768. {
  2769. EmitFunctionBody(funcInfo);
  2770. }
  2771. if (pnode->sxFnc.pnodeBodyScope != nullptr)
  2772. {
  2773. ::EndEmitBlock(pnode->sxFnc.pnodeBodyScope, this, funcInfo);
  2774. }
  2775. ::EndEmitBlock(pnode->sxFnc.pnodeScopes, this, funcInfo);
  2776. if (!this->IsInDebugMode())
  2777. {
  2778. // Release the temp registers that we reserved for inner scopes above.
  2779. if (innerScopeCount)
  2780. {
  2781. Js::RegSlot tmpReg = funcInfo->FirstInnerScopeReg() + innerScopeCount - 1;
  2782. for (uint i = 0; i < innerScopeCount; i++)
  2783. {
  2784. funcInfo->ReleaseTmpRegister(tmpReg);
  2785. tmpReg--;
  2786. }
  2787. }
  2788. }
  2789. Assert(funcInfo->firstTmpReg == firstTmpReg);
  2790. Assert(funcInfo->curTmpReg == firstTmpReg);
  2791. Assert(byteCodeFunction->GetFirstTmpReg() == firstTmpReg + byteCodeFunction->GetConstantCount());
  2792. byteCodeFunction->SetVarCount(funcInfo->varRegsCount);
  2793. byteCodeFunction->SetOutParamDepth(funcInfo->outArgsMaxDepth);
  2794. // Do a uint32 add just to verify that we haven't overflowed the reg slot type.
  2795. UInt32Math::Add(funcInfo->varRegsCount, funcInfo->constRegsCount);
  2796. #if DBG_DUMP
  2797. if (PHASE_STATS1(Js::ByteCodePhase))
  2798. {
  2799. Output::Print(L" BCode: %-10d, Aux: %-10d, AuxC: %-10d Total: %-10d, %s\n",
  2800. m_writer.ByteCodeDataSize(),
  2801. m_writer.AuxiliaryDataSize(),
  2802. m_writer.AuxiliaryContextDataSize(),
  2803. m_writer.ByteCodeDataSize() + m_writer.AuxiliaryDataSize() + m_writer.AuxiliaryContextDataSize(),
  2804. funcInfo->name);
  2805. this->scriptContext->byteCodeDataSize += m_writer.ByteCodeDataSize();
  2806. this->scriptContext->byteCodeAuxiliaryDataSize += m_writer.AuxiliaryDataSize();
  2807. this->scriptContext->byteCodeAuxiliaryContextDataSize += m_writer.AuxiliaryContextDataSize();
  2808. }
  2809. #endif
  2810. this->MapCacheIdsToPropertyIds(funcInfo);
  2811. this->MapReferencedPropertyIds(funcInfo);
  2812. Assert(this->TopFuncInfo() == funcInfo);
  2813. PopFuncInfo(L"EmitOneFunction");
  2814. m_writer.SetCallSiteCount(m_callSiteId);
  2815. #ifdef LOG_BYTECODE_AST_RATIO
  2816. m_writer.End(funcInfo->root->sxFnc.astSize, this->maxAstSize);
  2817. #else
  2818. m_writer.End();
  2819. #endif
  2820. }
  2821. catch (...)
  2822. {
  2823. // Failed to generate byte-code for this function body (likely OOM or stack overflow). Notify the function body so that
  2824. // it can revert intermediate state changes that may have taken place during byte code generation before the failure.
  2825. byteCodeFunction->ResetByteCodeGenState();
  2826. m_writer.Reset();
  2827. throw;
  2828. }
  2829. #ifdef PERF_HINT
  2830. if (PHASE_TRACE1(Js::PerfHintPhase) && !byteCodeFunction->GetIsGlobalFunc())
  2831. {
  2832. if (byteCodeFunction->GetHasTry())
  2833. {
  2834. WritePerfHint(PerfHints::HasTryBlock_Verbose, byteCodeFunction);
  2835. }
  2836. if (funcInfo->GetCallsEval())
  2837. {
  2838. WritePerfHint(PerfHints::CallsEval_Verbose, byteCodeFunction);
  2839. }
  2840. else if (funcInfo->GetChildCallsEval())
  2841. {
  2842. WritePerfHint(PerfHints::ChildCallsEval, byteCodeFunction);
  2843. }
  2844. }
  2845. #endif
  2846. byteCodeFunction->SetInitialDefaultEntryPoint();
  2847. byteCodeFunction->SetIsByteCodeDebugMode(this->IsInDebugMode());
  2848. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2849. if (byteCodeFunction->IsByteCodeDebugMode() != scriptContext->IsInDebugMode()) // debug mode mismatch
  2850. {
  2851. if (m_utf8SourceInfo->GetIsLibraryCode())
  2852. {
  2853. Assert(!byteCodeFunction->IsByteCodeDebugMode()); // Library script byteCode is never in debug mode
  2854. }
  2855. else
  2856. {
  2857. Js::Throw::FatalInternalError();
  2858. }
  2859. }
  2860. #endif
  2861. #if DBG_DUMP
  2862. if (PHASE_DUMP(Js::ByteCodePhase, funcInfo->byteCodeFunction) && Js::Configuration::Global.flags.Verbose)
  2863. {
  2864. pnode->Dump();
  2865. }
  2866. if (this->Trace() || PHASE_DUMP(Js::ByteCodePhase, funcInfo->byteCodeFunction))
  2867. {
  2868. Js::ByteCodeDumper::Dump(byteCodeFunction);
  2869. }
  2870. if (PHASE_DUMP(Js::DebuggerScopePhase, funcInfo->byteCodeFunction))
  2871. {
  2872. byteCodeFunction->DumpScopes();
  2873. }
  2874. #endif
  2875. #if ENABLE_NATIVE_CODEGEN
  2876. if ((!PHASE_OFF(Js::BackEndPhase, funcInfo->byteCodeFunction))
  2877. && !this->forceNoNative
  2878. && !this->scriptContext->GetConfig()->IsNoNative())
  2879. {
  2880. GenerateFunction(this->scriptContext->GetNativeCodeGenerator(), byteCodeFunction);
  2881. }
  2882. #endif
  2883. }
  2884. void ByteCodeGenerator::MapCacheIdsToPropertyIds(FuncInfo *funcInfo)
  2885. {
  2886. Js::FunctionBody *functionBody = funcInfo->GetParsedFunctionBody();
  2887. uint rootObjectLoadInlineCacheStart = funcInfo->GetInlineCacheCount();
  2888. uint rootObjectLoadMethodInlineCacheStart = rootObjectLoadInlineCacheStart + funcInfo->GetRootObjectLoadInlineCacheCount();
  2889. uint rootObjectStoreInlineCacheStart = rootObjectLoadMethodInlineCacheStart + funcInfo->GetRootObjectLoadMethodInlineCacheCount();
  2890. uint totalFieldAccessInlineCacheCount = rootObjectStoreInlineCacheStart + funcInfo->GetRootObjectStoreInlineCacheCount();
  2891. functionBody->CreateCacheIdToPropertyIdMap(rootObjectLoadInlineCacheStart, rootObjectLoadMethodInlineCacheStart,
  2892. rootObjectStoreInlineCacheStart, totalFieldAccessInlineCacheCount, funcInfo->GetIsInstInlineCacheCount());
  2893. if (totalFieldAccessInlineCacheCount == 0)
  2894. {
  2895. return;
  2896. }
  2897. funcInfo->inlineCacheMap->Map([functionBody](Js::RegSlot regSlot, FuncInfo::InlineCacheIdMap *inlineCacheIdMap)
  2898. {
  2899. inlineCacheIdMap->Map([functionBody](Js::PropertyId propertyId, FuncInfo::InlineCacheList* inlineCacheList)
  2900. {
  2901. if (inlineCacheList)
  2902. {
  2903. inlineCacheList->Iterate([functionBody, propertyId](InlineCacheUnit cacheUnit)
  2904. {
  2905. CompileAssert(offsetof(InlineCacheUnit, cacheId) == offsetof(InlineCacheUnit, loadCacheId));
  2906. if (cacheUnit.loadCacheId != -1)
  2907. {
  2908. functionBody->SetPropertyIdForCacheId(cacheUnit.loadCacheId, propertyId);
  2909. }
  2910. if (cacheUnit.loadMethodCacheId != -1)
  2911. {
  2912. functionBody->SetPropertyIdForCacheId(cacheUnit.loadMethodCacheId, propertyId);
  2913. }
  2914. if (cacheUnit.storeCacheId != -1)
  2915. {
  2916. functionBody->SetPropertyIdForCacheId(cacheUnit.storeCacheId, propertyId);
  2917. }
  2918. });
  2919. }
  2920. });
  2921. });
  2922. funcInfo->rootObjectLoadInlineCacheMap->Map([functionBody, rootObjectLoadInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  2923. {
  2924. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectLoadInlineCacheStart, propertyId);
  2925. });
  2926. funcInfo->rootObjectLoadMethodInlineCacheMap->Map([functionBody, rootObjectLoadMethodInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  2927. {
  2928. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectLoadMethodInlineCacheStart, propertyId);
  2929. });
  2930. funcInfo->rootObjectStoreInlineCacheMap->Map([functionBody, rootObjectStoreInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  2931. {
  2932. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectStoreInlineCacheStart, propertyId);
  2933. });
  2934. SListBase<uint>::Iterator valueOfIter(&funcInfo->valueOfStoreCacheIds);
  2935. while (valueOfIter.Next())
  2936. {
  2937. functionBody->SetPropertyIdForCacheId(valueOfIter.Data(), Js::PropertyIds::valueOf);
  2938. }
  2939. SListBase<uint>::Iterator toStringIter(&funcInfo->toStringStoreCacheIds);
  2940. while (toStringIter.Next())
  2941. {
  2942. functionBody->SetPropertyIdForCacheId(toStringIter.Data(), Js::PropertyIds::toString);
  2943. }
  2944. #if DBG
  2945. functionBody->VerifyCacheIdToPropertyIdMap();
  2946. #endif
  2947. }
  2948. void ByteCodeGenerator::MapReferencedPropertyIds(FuncInfo * funcInfo)
  2949. {
  2950. Js::FunctionBody *functionBody = funcInfo->GetParsedFunctionBody();
  2951. uint referencedPropertyIdCount = funcInfo->GetReferencedPropertyIdCount();
  2952. functionBody->CreateReferencedPropertyIdMap(referencedPropertyIdCount);
  2953. funcInfo->referencedPropertyIdToMapIndex->Map([functionBody](Js::PropertyId propertyId, uint mapIndex)
  2954. {
  2955. functionBody->SetReferencedPropertyIdWithMapIndex(mapIndex, propertyId);
  2956. });
  2957. #if DBG
  2958. functionBody->VerifyReferencedPropertyIdMap();
  2959. #endif
  2960. }
  2961. void ByteCodeGenerator::EmitScopeList(ParseNode *pnode)
  2962. {
  2963. while (pnode)
  2964. {
  2965. switch (pnode->nop)
  2966. {
  2967. case knopFncDecl:
  2968. #ifndef TEMP_DISABLE_ASMJS
  2969. if (pnode->sxFnc.GetAsmjsMode())
  2970. {
  2971. Js::ExclusiveContext context(this, GetScriptContext());
  2972. if (Js::AsmJSCompiler::Compile(&context, pnode, pnode->sxFnc.pnodeArgs))
  2973. {
  2974. pnode = pnode->sxFnc.pnodeNext;
  2975. break;
  2976. }
  2977. else if (CONFIG_FLAG(AsmJsStopOnError))
  2978. {
  2979. exit(JSERR_AsmJsCompileError);
  2980. }
  2981. else if (!(flags & fscrDeferFncParse))
  2982. {
  2983. // If deferral is not allowed, throw and reparse everything with asm.js disabled.
  2984. throw Js::AsmJsParseException();
  2985. }
  2986. }
  2987. #endif
  2988. // FALLTHROUGH
  2989. case knopProg:
  2990. if (pnode->sxFnc.funcInfo)
  2991. {
  2992. this->StartEmitFunction(pnode);
  2993. this->EmitScopeList(pnode->sxFnc.pnodeScopes);
  2994. this->EmitOneFunction(pnode);
  2995. this->EndEmitFunction(pnode);
  2996. }
  2997. pnode = pnode->sxFnc.pnodeNext;
  2998. break;
  2999. case knopBlock:
  3000. this->StartEmitBlock(pnode);
  3001. this->EmitScopeList(pnode->sxBlock.pnodeScopes);
  3002. this->EndEmitBlock(pnode);
  3003. pnode = pnode->sxBlock.pnodeNext;
  3004. break;
  3005. case knopCatch:
  3006. this->StartEmitCatch(pnode);
  3007. this->EmitScopeList(pnode->sxCatch.pnodeScopes);
  3008. this->EndEmitCatch(pnode);
  3009. pnode = pnode->sxCatch.pnodeNext;
  3010. break;
  3011. case knopWith:
  3012. this->StartEmitWith(pnode);
  3013. this->EmitScopeList(pnode->sxWith.pnodeScopes);
  3014. this->EndEmitWith(pnode);
  3015. pnode = pnode->sxWith.pnodeNext;
  3016. break;
  3017. default:
  3018. AssertMsg(false, "Unexpected opcode in tree of scopes");
  3019. break;
  3020. }
  3021. }
  3022. }
  3023. void EnsureFncDeclScopeSlot(ParseNode *pnodeFnc, FuncInfo *funcInfo)
  3024. {
  3025. if (pnodeFnc->sxFnc.pnodeName)
  3026. {
  3027. Assert(pnodeFnc->sxFnc.pnodeName->nop == knopVarDecl);
  3028. Symbol *sym = pnodeFnc->sxFnc.pnodeName->sxVar.sym;
  3029. if (sym)
  3030. {
  3031. sym->EnsureScopeSlot(funcInfo);
  3032. }
  3033. }
  3034. }
  3035. // Similar to EnsureFncScopeSlot visitor function, but verifies that a slot is needed before assigning it.
  3036. void CheckFncDeclScopeSlot(ParseNode *pnodeFnc, FuncInfo *funcInfo)
  3037. {
  3038. if (pnodeFnc->sxFnc.pnodeName && pnodeFnc->sxFnc.pnodeName->nop == knopVarDecl)
  3039. {
  3040. Assert(pnodeFnc->sxFnc.pnodeName->nop == knopVarDecl);
  3041. Symbol *sym = pnodeFnc->sxFnc.pnodeName->sxVar.sym;
  3042. if (sym && sym->NeedsSlotAlloc(funcInfo))
  3043. {
  3044. sym->EnsureScopeSlot(funcInfo);
  3045. }
  3046. }
  3047. }
  3048. void ByteCodeGenerator::StartEmitFunction(ParseNode *pnodeFnc)
  3049. {
  3050. Assert(pnodeFnc->nop == knopFncDecl || pnodeFnc->nop == knopProg);
  3051. FuncInfo *funcInfo = pnodeFnc->sxFnc.funcInfo;
  3052. if (funcInfo->byteCodeFunction->IsFunctionParsed() &&
  3053. !(flags & (fscrEval | fscrImplicitThis | fscrImplicitParents)))
  3054. {
  3055. // Only set the environment depth if it's truly known (i.e., not in eval or event handler).
  3056. funcInfo->GetParsedFunctionBody()->SetEnvDepth(this->envDepth);
  3057. }
  3058. if (funcInfo->GetCallsEval())
  3059. {
  3060. funcInfo->byteCodeFunction->SetDontInline(true);
  3061. }
  3062. Scope * const funcExprScope = funcInfo->funcExprScope;
  3063. if (funcExprScope)
  3064. {
  3065. if (funcInfo->GetCallsEval())
  3066. {
  3067. Assert(funcExprScope->GetIsObject());
  3068. }
  3069. if (funcExprScope->GetIsObject())
  3070. {
  3071. funcExprScope->SetCapturesAll(true);
  3072. funcExprScope->SetMustInstantiate(true);
  3073. PushScope(funcExprScope);
  3074. }
  3075. else
  3076. {
  3077. Symbol *sym = funcInfo->root->sxFnc.GetFuncSymbol();
  3078. funcInfo->bodyScope->AddSymbol(sym);
  3079. }
  3080. }
  3081. Scope * const bodyScope = funcInfo->bodyScope;
  3082. if (pnodeFnc->nop != knopProg)
  3083. {
  3084. if (!bodyScope->GetIsObject() && NeedObjectAsFunctionScope(funcInfo, pnodeFnc))
  3085. {
  3086. Assert(bodyScope->GetIsObject());
  3087. }
  3088. if (bodyScope->GetIsObject())
  3089. {
  3090. bodyScope->SetLocation(funcInfo->frameObjRegister);
  3091. }
  3092. else
  3093. {
  3094. bodyScope->SetLocation(funcInfo->frameSlotsRegister);
  3095. }
  3096. bodyScope->SetMustInstantiate(funcInfo->frameObjRegister != Js::Constants::NoRegister || funcInfo->frameSlotsRegister != Js::Constants::NoRegister);
  3097. if (bodyScope->GetIsObject())
  3098. {
  3099. // Win8 908700: Disable under F12 debugger because there are too many cached scopes holding onto locals.
  3100. funcInfo->SetHasCachedScope(
  3101. !PHASE_OFF(Js::CachedScopePhase, funcInfo->byteCodeFunction) &&
  3102. !funcInfo->Escapes() &&
  3103. funcInfo->frameObjRegister != Js::Constants::NoRegister &&
  3104. !ApplyEnclosesArgs(pnodeFnc, this) &&
  3105. (PHASE_FORCE(Js::CachedScopePhase, funcInfo->byteCodeFunction) || !IsInDebugMode()));
  3106. if (funcInfo->GetHasCachedScope())
  3107. {
  3108. Assert(funcInfo->funcObjRegister == Js::Constants::NoRegister);
  3109. Symbol *funcSym = funcInfo->root->sxFnc.GetFuncSymbol();
  3110. if (funcSym && funcSym->GetFuncExpr())
  3111. {
  3112. if (funcSym->GetLocation() == Js::Constants::NoRegister)
  3113. {
  3114. funcInfo->funcObjRegister = funcInfo->NextVarRegister();
  3115. }
  3116. else
  3117. {
  3118. funcInfo->funcObjRegister = funcSym->GetLocation();
  3119. }
  3120. }
  3121. else
  3122. {
  3123. funcInfo->funcObjRegister = funcInfo->NextVarRegister();
  3124. }
  3125. Assert(funcInfo->funcObjRegister != Js::Constants::NoRegister);
  3126. }
  3127. ParseNode *pnode;
  3128. Symbol *sym;
  3129. PushScope(bodyScope);
  3130. // Turns on capturesAll temporarily if func has deferred child, so that the following EnsureScopeSlot
  3131. // will allocate scope slots no matter if symbol hasNonLocalRefence or not.
  3132. Js::ScopeInfo::AutoCapturesAllScope autoCapturesAllScope(bodyScope, funcInfo->HasDeferredChild());
  3133. if (funcInfo->GetHasArguments())
  3134. {
  3135. // Process function's formal parameters
  3136. MapFormals(pnodeFnc, [&](ParseNode *pnode)
  3137. {
  3138. if (pnode->IsVarLetOrConst())
  3139. {
  3140. pnode->sxVar.sym->EnsureScopeSlot(funcInfo);
  3141. }
  3142. });
  3143. MapFormalsFromPattern(pnodeFnc, [&](ParseNode *pnode) { pnode->sxVar.sym->EnsureScopeSlot(funcInfo); });
  3144. // Only allocate scope slot for "arguments" when really necessary. "hasDeferredChild"
  3145. // doesn't require scope slot for "arguments" because inner functions can't access
  3146. // outer function's arguments directly.
  3147. sym = funcInfo->GetArgumentsSymbol();
  3148. Assert(sym);
  3149. if (sym->GetHasNonLocalReference() || autoCapturesAllScope.OldCapturesAll())
  3150. {
  3151. sym->EnsureScopeSlot(funcInfo);
  3152. }
  3153. }
  3154. sym = funcInfo->root->sxFnc.GetFuncSymbol();
  3155. if (sym && sym->NeedsSlotAlloc(funcInfo))
  3156. {
  3157. if (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject())
  3158. {
  3159. sym->SetScopeSlot(0);
  3160. }
  3161. else if (funcInfo->GetFuncExprNameReference())
  3162. {
  3163. sym->EnsureScopeSlot(funcInfo);
  3164. }
  3165. }
  3166. if (!funcInfo->GetHasArguments())
  3167. {
  3168. Symbol *formal;
  3169. Js::ArgSlot pos = 1;
  3170. auto moveArgToReg = [&](ParseNode *pnode)
  3171. {
  3172. if (pnode->IsVarLetOrConst())
  3173. {
  3174. formal = pnode->sxVar.sym;
  3175. // Get the param from its argument position into its assigned register.
  3176. // The position should match the location; otherwise, it has been shadowed by parameter with the same name.
  3177. if (formal->GetLocation() + 1 == pos)
  3178. {
  3179. pnode->sxVar.sym->EnsureScopeSlot(funcInfo);
  3180. }
  3181. }
  3182. pos++;
  3183. };
  3184. MapFormals(pnodeFnc, moveArgToReg);
  3185. MapFormalsFromPattern(pnodeFnc, [&](ParseNode *pnode) { pnode->sxVar.sym->EnsureScopeSlot(funcInfo); });
  3186. }
  3187. if (funcInfo->isThisLexicallyCaptured)
  3188. {
  3189. funcInfo->EnsureThisScopeSlot();
  3190. }
  3191. if (((!funcInfo->IsLambda() && funcInfo->GetCallsEval())
  3192. || funcInfo->isSuperLexicallyCaptured))
  3193. {
  3194. if (funcInfo->superRegister != Js::Constants::NoRegister)
  3195. {
  3196. funcInfo->EnsureSuperScopeSlot();
  3197. }
  3198. if (funcInfo->superCtorRegister != Js::Constants::NoRegister)
  3199. {
  3200. funcInfo->EnsureSuperCtorScopeSlot();
  3201. }
  3202. }
  3203. if (funcInfo->isNewTargetLexicallyCaptured)
  3204. {
  3205. funcInfo->EnsureNewTargetScopeSlot();
  3206. }
  3207. auto ensureFncDeclScopeSlots = [&](ParseNode *pnodeScope)
  3208. {
  3209. for (pnode = pnodeScope; pnode;)
  3210. {
  3211. switch (pnode->nop)
  3212. {
  3213. case knopFncDecl:
  3214. if (pnode->sxFnc.IsDeclaration())
  3215. {
  3216. EnsureFncDeclScopeSlot(pnode, funcInfo);
  3217. }
  3218. pnode = pnode->sxFnc.pnodeNext;
  3219. break;
  3220. case knopBlock:
  3221. pnode = pnode->sxBlock.pnodeNext;
  3222. break;
  3223. case knopCatch:
  3224. pnode = pnode->sxCatch.pnodeNext;
  3225. break;
  3226. case knopWith:
  3227. pnode = pnode->sxWith.pnodeNext;
  3228. break;
  3229. }
  3230. }
  3231. };
  3232. pnodeFnc->sxFnc.MapContainerScopes(ensureFncDeclScopeSlots);
  3233. for (pnode = pnodeFnc->sxFnc.pnodeVars; pnode; pnode = pnode->sxVar.pnodeNext)
  3234. {
  3235. sym = pnode->sxVar.sym;
  3236. if (!(pnode->sxVar.isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  3237. {
  3238. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  3239. {
  3240. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  3241. }
  3242. if (sym->GetSymbolType() == STVariable && !sym->GetIsArguments())
  3243. {
  3244. sym->EnsureScopeSlot(funcInfo);
  3245. }
  3246. }
  3247. }
  3248. if (pnodeFnc->sxFnc.pnodeBody)
  3249. {
  3250. Assert(pnodeFnc->sxFnc.pnodeScopes->nop == knopBlock);
  3251. this->EnsureLetConstScopeSlots(pnodeFnc->sxFnc.pnodeBodyScope, funcInfo);
  3252. }
  3253. }
  3254. else
  3255. {
  3256. ParseNode *pnode;
  3257. Symbol *sym;
  3258. // Don't rely on the Emit() pass to assign scope slots where needed, because peeps/shortcuts
  3259. // may cause some expressions not to be emitted. Assign the slots we need before we start
  3260. // emitting the prolog.
  3261. // TODO: Investigate moving detection of non-local references to Emit() so we don't assign
  3262. // slots to symbols that are never referenced in emitted code.
  3263. if (funcInfo->isThisLexicallyCaptured)
  3264. {
  3265. funcInfo->EnsureThisScopeSlot();
  3266. }
  3267. if (funcInfo->isSuperLexicallyCaptured)
  3268. {
  3269. funcInfo->EnsureSuperScopeSlot();
  3270. }
  3271. if (funcInfo->isSuperCtorLexicallyCaptured)
  3272. {
  3273. funcInfo->EnsureSuperCtorScopeSlot();
  3274. }
  3275. if (funcInfo->isNewTargetLexicallyCaptured)
  3276. {
  3277. funcInfo->EnsureNewTargetScopeSlot();
  3278. }
  3279. pnodeFnc->sxFnc.MapContainerScopes([&](ParseNode *pnodeScope) { this->EnsureFncScopeSlots(pnodeScope, funcInfo); });
  3280. PushScope(bodyScope);
  3281. for (pnode = pnodeFnc->sxFnc.pnodeVars; pnode; pnode = pnode->sxVar.pnodeNext)
  3282. {
  3283. sym = pnode->sxVar.sym;
  3284. if (!(pnode->sxVar.isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  3285. {
  3286. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  3287. {
  3288. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  3289. }
  3290. if (sym->GetSymbolType() == STVariable && sym->NeedsSlotAlloc(funcInfo) && !sym->GetIsArguments())
  3291. {
  3292. sym->EnsureScopeSlot(funcInfo);
  3293. }
  3294. }
  3295. }
  3296. auto ensureScopeSlot = [&](ParseNode *pnode)
  3297. {
  3298. if (pnode->IsVarLetOrConst())
  3299. {
  3300. sym = pnode->sxVar.sym;
  3301. if (sym->GetSymbolType() == STFormal && sym->NeedsSlotAlloc(funcInfo))
  3302. {
  3303. sym->EnsureScopeSlot(funcInfo);
  3304. }
  3305. }
  3306. };
  3307. // Process function's formal parameters
  3308. MapFormals(pnodeFnc, ensureScopeSlot);
  3309. MapFormalsFromPattern(pnodeFnc, ensureScopeSlot);
  3310. if (pnodeFnc->sxFnc.pnodeBody)
  3311. {
  3312. this->EnsureLetConstScopeSlots(pnodeFnc->sxFnc.pnodeScopes, funcInfo);
  3313. this->EnsureLetConstScopeSlots(pnodeFnc->sxFnc.pnodeBodyScope, funcInfo);
  3314. }
  3315. }
  3316. }
  3317. else
  3318. {
  3319. bool newScopeForEval = (funcInfo->byteCodeFunction->GetIsStrictMode() && (this->GetFlags() & fscrEval));
  3320. if (newScopeForEval)
  3321. {
  3322. Assert(bodyScope->GetIsObject());
  3323. }
  3324. PushScope(bodyScope);
  3325. }
  3326. // Persist outer func scope info if nested func is deferred
  3327. if (CONFIG_FLAG(DeferNested))
  3328. {
  3329. FuncInfo* parentFunc = TopFuncInfo();
  3330. Js::ScopeInfo::SaveScopeInfoForDeferParse(this, parentFunc, funcInfo);
  3331. PushFuncInfo(L"StartEmitFunction", funcInfo);
  3332. }
  3333. }
  3334. void ByteCodeGenerator::EnsureLetConstScopeSlots(ParseNode *pnodeBlock, FuncInfo *funcInfo)
  3335. {
  3336. bool hasNonLocalReference = pnodeBlock->sxBlock.GetCallsEval() || pnodeBlock->sxBlock.GetChildCallsEval();
  3337. auto ensureLetConstSlots = ([this, pnodeBlock, funcInfo, hasNonLocalReference](ParseNode *pnode)
  3338. {
  3339. Symbol *sym = pnode->sxVar.sym;
  3340. sym->EnsureScopeSlot(funcInfo);
  3341. if (hasNonLocalReference)
  3342. {
  3343. sym->SetHasNonLocalReference(true, this);
  3344. }
  3345. });
  3346. IterateBlockScopedVariables(pnodeBlock, ensureLetConstSlots);
  3347. }
  3348. void ByteCodeGenerator::EnsureFncScopeSlots(ParseNode *pnode, FuncInfo *funcInfo)
  3349. {
  3350. while (pnode)
  3351. {
  3352. switch (pnode->nop)
  3353. {
  3354. case knopFncDecl:
  3355. if (pnode->sxFnc.IsDeclaration())
  3356. {
  3357. CheckFncDeclScopeSlot(pnode, funcInfo);
  3358. }
  3359. pnode = pnode->sxFnc.pnodeNext;
  3360. break;
  3361. case knopBlock:
  3362. pnode = pnode->sxBlock.pnodeNext;
  3363. break;
  3364. case knopCatch:
  3365. pnode = pnode->sxCatch.pnodeNext;
  3366. break;
  3367. case knopWith:
  3368. pnode = pnode->sxWith.pnodeNext;
  3369. break;
  3370. }
  3371. }
  3372. }
  3373. void ByteCodeGenerator::EndEmitFunction(ParseNode *pnodeFnc)
  3374. {
  3375. Assert(pnodeFnc->nop == knopFncDecl || pnodeFnc->nop == knopProg);
  3376. Assert(pnodeFnc->nop == knopFncDecl && currentScope->GetEnclosingScope() != nullptr || pnodeFnc->nop == knopProg);
  3377. PopScope(); // function body
  3378. FuncInfo *funcInfo = pnodeFnc->sxFnc.funcInfo;
  3379. Scope *scope = funcInfo->funcExprScope;
  3380. if (scope && scope->GetMustInstantiate())
  3381. {
  3382. Assert(currentScope == scope);
  3383. PopScope();
  3384. }
  3385. if (CONFIG_FLAG(DeferNested))
  3386. {
  3387. Assert(funcInfo == this->TopFuncInfo());
  3388. PopFuncInfo(L"EndEmitFunction");
  3389. }
  3390. }
  3391. void ByteCodeGenerator::StartEmitCatch(ParseNode *pnodeCatch)
  3392. {
  3393. Assert(pnodeCatch->nop == knopCatch);
  3394. Scope *scope = pnodeCatch->sxCatch.scope;
  3395. FuncInfo *funcInfo = scope->GetFunc();
  3396. // 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).
  3397. if (funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval() || (this->flags & (fscrEval | fscrImplicitThis | fscrImplicitParents)))
  3398. {
  3399. scope->SetIsObject();
  3400. }
  3401. if (pnodeCatch->sxCatch.pnodeParam->nop == knopParamPattern)
  3402. {
  3403. scope->SetCapturesAll(funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval());
  3404. scope->SetMustInstantiate(scope->Count() > 0 && (scope->GetMustInstantiate() || scope->GetCapturesAll() || funcInfo->IsGlobalFunction()));
  3405. Parser::MapBindIdentifier(pnodeCatch->sxCatch.pnodeParam->sxParamPattern.pnode1, [&](ParseNodePtr item)
  3406. {
  3407. Symbol *sym = item->sxVar.sym;
  3408. if (funcInfo->IsGlobalFunction())
  3409. {
  3410. sym->SetIsGlobalCatch(true);
  3411. }
  3412. Assert(sym->GetScopeSlot() == Js::Constants::NoProperty);
  3413. if (sym->NeedsSlotAlloc(funcInfo))
  3414. {
  3415. sym->EnsureScopeSlot(funcInfo);
  3416. }
  3417. });
  3418. // In the case of pattern we will always going to push the scope.
  3419. PushScope(scope);
  3420. }
  3421. else
  3422. {
  3423. Symbol *sym = pnodeCatch->sxCatch.pnodeParam->sxPid.sym;
  3424. // Catch object is stored in the catch scope if there may be an ambiguous lookup or a var declaration that hides it.
  3425. scope->SetCapturesAll(funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval() || sym->GetHasNonLocalReference());
  3426. scope->SetMustInstantiate(scope->GetCapturesAll() || funcInfo->IsGlobalFunction() || currentScope != funcInfo->GetBodyScope());
  3427. if (funcInfo->IsGlobalFunction())
  3428. {
  3429. sym->SetIsGlobalCatch(true);
  3430. }
  3431. if (scope->GetMustInstantiate())
  3432. {
  3433. // Since there is only one symbol we are pushing to slot.
  3434. // Also in order to make IsInSlot to return true - forcing the sym-has-non-local-reference.
  3435. sym->SetHasNonLocalReference(true, this);
  3436. sym->EnsureScopeSlot(funcInfo);
  3437. PushScope(scope);
  3438. }
  3439. else
  3440. {
  3441. // Add it to the parent function's scope and treat it like any other local.
  3442. // We can only do this if we don't need to get the symbol from a slot, though, because adding it to the
  3443. // parent's scope object on entry to the catch could re-size the slot array.
  3444. funcInfo->bodyScope->AddSymbol(sym);
  3445. }
  3446. }
  3447. }
  3448. void ByteCodeGenerator::EndEmitCatch(ParseNode *pnodeCatch)
  3449. {
  3450. Assert(pnodeCatch->nop == knopCatch);
  3451. if (pnodeCatch->sxCatch.scope->GetMustInstantiate() || pnodeCatch->sxCatch.pnodeParam->nop == knopParamPattern)
  3452. {
  3453. Assert(currentScope == pnodeCatch->sxCatch.scope);
  3454. PopScope();
  3455. }
  3456. }
  3457. void ByteCodeGenerator::StartEmitBlock(ParseNode *pnodeBlock)
  3458. {
  3459. if (!BlockHasOwnScope(pnodeBlock, this))
  3460. {
  3461. return;
  3462. }
  3463. Assert(pnodeBlock->nop == knopBlock);
  3464. PushBlock(pnodeBlock);
  3465. Scope *scope = pnodeBlock->sxBlock.scope;
  3466. if (pnodeBlock->sxBlock.GetCallsEval() || pnodeBlock->sxBlock.GetChildCallsEval() || (this->flags & (fscrEval | fscrImplicitThis | fscrImplicitParents)))
  3467. {
  3468. Assert(scope->GetIsObject());
  3469. }
  3470. // TODO: Consider nested deferred parsing.
  3471. if (scope->GetMustInstantiate())
  3472. {
  3473. FuncInfo *funcInfo = scope->GetFunc();
  3474. if (scope->IsGlobalEvalBlockScope() && funcInfo->isThisLexicallyCaptured)
  3475. {
  3476. funcInfo->EnsureThisScopeSlot();
  3477. }
  3478. this->EnsureFncScopeSlots(pnodeBlock->sxBlock.pnodeScopes, funcInfo);
  3479. this->EnsureLetConstScopeSlots(pnodeBlock, funcInfo);
  3480. PushScope(scope);
  3481. }
  3482. }
  3483. void ByteCodeGenerator::EndEmitBlock(ParseNode *pnodeBlock)
  3484. {
  3485. if (!BlockHasOwnScope(pnodeBlock, this))
  3486. {
  3487. return;
  3488. }
  3489. Assert(pnodeBlock->nop == knopBlock);
  3490. Scope *scope = pnodeBlock->sxBlock.scope;
  3491. if (scope && scope->GetMustInstantiate())
  3492. {
  3493. Assert(currentScope == pnodeBlock->sxBlock.scope);
  3494. PopScope();
  3495. }
  3496. PopBlock();
  3497. }
  3498. void ByteCodeGenerator::StartEmitWith(ParseNode *pnodeWith)
  3499. {
  3500. Assert(pnodeWith->nop == knopWith);
  3501. Scope *scope = pnodeWith->sxWith.scope;
  3502. Assert(scope->GetIsObject());
  3503. PushScope(scope);
  3504. }
  3505. void ByteCodeGenerator::EndEmitWith(ParseNode *pnodeWith)
  3506. {
  3507. Assert(pnodeWith->nop == knopWith);
  3508. Assert(currentScope == pnodeWith->sxWith.scope);
  3509. PopScope();
  3510. }
  3511. Js::RegSlot ByteCodeGenerator::PrependLocalScopes(Js::RegSlot evalEnv, Js::RegSlot tempLoc, FuncInfo *funcInfo)
  3512. {
  3513. Scope *currScope = this->currentScope;
  3514. Scope *funcScope = funcInfo->GetBodyScope();
  3515. if (currScope == funcScope)
  3516. {
  3517. return evalEnv;
  3518. }
  3519. bool acquireTempLoc = tempLoc == Js::Constants::NoRegister;
  3520. if (acquireTempLoc)
  3521. {
  3522. tempLoc = funcInfo->AcquireTmpRegister();
  3523. }
  3524. // The with/catch objects must be prepended to the environment we pass to eval() or to a func declared inside with,
  3525. // but the list must first be reversed so that innermost scopes appear first in the list.
  3526. while (currScope != funcScope)
  3527. {
  3528. Scope *innerScope;
  3529. for (innerScope = currScope; innerScope->GetEnclosingScope() != funcScope; innerScope = innerScope->GetEnclosingScope())
  3530. ;
  3531. if (innerScope->GetMustInstantiate())
  3532. {
  3533. if (!innerScope->HasInnerScopeIndex())
  3534. {
  3535. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  3536. {
  3537. this->m_writer.Reg2(Js::OpCode::LdInnerFrameDisplayNoParent, tempLoc, innerScope->GetLocation());
  3538. }
  3539. else
  3540. {
  3541. this->m_writer.Reg3(Js::OpCode::LdInnerFrameDisplay, tempLoc, innerScope->GetLocation(), evalEnv);
  3542. }
  3543. }
  3544. else
  3545. {
  3546. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  3547. {
  3548. this->m_writer.Reg1Unsigned1(Js::OpCode::LdIndexedFrameDisplayNoParent, tempLoc, innerScope->GetInnerScopeIndex());
  3549. }
  3550. else
  3551. {
  3552. this->m_writer.Reg2Int1(Js::OpCode::LdIndexedFrameDisplay, tempLoc, evalEnv, innerScope->GetInnerScopeIndex());
  3553. }
  3554. }
  3555. evalEnv = tempLoc;
  3556. }
  3557. funcScope = innerScope;
  3558. }
  3559. if (acquireTempLoc)
  3560. {
  3561. funcInfo->ReleaseTmpRegister(tempLoc);
  3562. }
  3563. return evalEnv;
  3564. }
  3565. void ByteCodeGenerator::EmitLoadInstance(Symbol *sym, IdentPtr pid, Js::RegSlot *pThisLocation, Js::RegSlot *pInstLocation, FuncInfo *funcInfo)
  3566. {
  3567. Js::ByteCodeLabel doneLabel = 0;
  3568. bool fLabelDefined = false;
  3569. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  3570. Js::RegSlot thisLocation = *pThisLocation;
  3571. Js::RegSlot instLocation = *pInstLocation;
  3572. Js::PropertyId envIndex = -1;
  3573. Scope *scope = nullptr;
  3574. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  3575. Assert(symScope);
  3576. for (;;)
  3577. {
  3578. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  3579. if (scope == this->globalScope)
  3580. {
  3581. break;
  3582. }
  3583. if (scope != symScope)
  3584. {
  3585. // We're not sure where the function is (eval/with/etc).
  3586. // So we're going to need registers to hold the instance where we (dynamically) find
  3587. // the function, and possibly to hold the "this" pointer we will pass to it.
  3588. // Assign them here so that they can't overlap with the scopeLocation assigned below.
  3589. // Otherwise we wind up with temp lifetime confusion in the IRBuilder. (Win8 281689)
  3590. if (instLocation == Js::Constants::NoRegister)
  3591. {
  3592. instLocation = funcInfo->AcquireTmpRegister();
  3593. // The "this" pointer will not be the same as the instance, so give it its own register.
  3594. thisLocation = funcInfo->AcquireTmpRegister();
  3595. }
  3596. }
  3597. if (envIndex == -1)
  3598. {
  3599. Assert(funcInfo == scope->GetFunc());
  3600. scopeLocation = scope->GetLocation();
  3601. }
  3602. if (scope == symScope)
  3603. {
  3604. break;
  3605. }
  3606. // Found a scope to which the property may have been added.
  3607. Assert(scope && scope->GetIsDynamic());
  3608. if (!fLabelDefined)
  3609. {
  3610. fLabelDefined = true;
  3611. doneLabel = this->m_writer.DefineLabel();
  3612. }
  3613. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  3614. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  3615. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  3616. if (envIndex != -1)
  3617. {
  3618. this->m_writer.BrEnvProperty(
  3619. Js::OpCode::BrOnNoEnvProperty, nextLabel,
  3620. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  3621. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  3622. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  3623. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, tmpReg,
  3624. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  3625. Js::OpCode op = unwrapWithObj ? Js::OpCode::UnwrapWithObj : Js::OpCode::Ld_A;
  3626. this->m_writer.Reg2(op, instLocation, tmpReg);
  3627. if (thisLocation != Js::Constants::NoRegister)
  3628. {
  3629. this->m_writer.Reg2(op, thisLocation, tmpReg);
  3630. }
  3631. funcInfo->ReleaseTmpRegister(tmpReg);
  3632. }
  3633. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  3634. {
  3635. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  3636. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  3637. Assert(!unwrapWithObj);
  3638. this->m_writer.Reg1(Js::OpCode::LdLocalObj, instLocation);
  3639. if (thisLocation != Js::Constants::NoRegister)
  3640. {
  3641. this->m_writer.Reg1(Js::OpCode::LdLocalObj, thisLocation);
  3642. }
  3643. }
  3644. else
  3645. {
  3646. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  3647. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  3648. Js::OpCode op = unwrapWithObj ? Js::OpCode::UnwrapWithObj : Js::OpCode::Ld_A;
  3649. this->m_writer.Reg2(op, instLocation, scopeLocation);
  3650. if (thisLocation != Js::Constants::NoRegister)
  3651. {
  3652. this->m_writer.Reg2(op, thisLocation, scopeLocation);
  3653. }
  3654. }
  3655. this->m_writer.Br(doneLabel);
  3656. this->m_writer.MarkLabel(nextLabel);
  3657. }
  3658. if (sym == nullptr || sym->GetIsGlobal())
  3659. {
  3660. if (this->flags & (fscrEval | fscrImplicitThis | fscrImplicitParents))
  3661. {
  3662. // Load of a symbol with unknown scope from within eval.
  3663. // Get it from the closure environment.
  3664. if (instLocation == Js::Constants::NoRegister)
  3665. {
  3666. instLocation = funcInfo->AcquireTmpRegister();
  3667. }
  3668. // TODO: It should be possible to avoid this double call to ScopedLdInst by having it return both
  3669. // results at once. The reason for the uncertainty here is that we don't know whether the callee
  3670. // belongs to a "with" object. If it does, we have to pass the "with" object as "this"; in all other
  3671. // cases, we pass "undefined". For now, there are apparently no significant performance issues.
  3672. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  3673. if (thisLocation == Js::Constants::NoRegister)
  3674. {
  3675. thisLocation = funcInfo->AcquireTmpRegister();
  3676. }
  3677. this->m_writer.ScopedProperty2(Js::OpCode::ScopedLdInst, instLocation,
  3678. funcInfo->FindOrAddReferencedPropertyId(propertyId), thisLocation);
  3679. }
  3680. else
  3681. {
  3682. if (instLocation == Js::Constants::NoRegister)
  3683. {
  3684. instLocation = ByteCodeGenerator::RootObjectRegister;
  3685. }
  3686. else
  3687. {
  3688. this->m_writer.Reg2(Js::OpCode::Ld_A, instLocation, ByteCodeGenerator::RootObjectRegister);
  3689. }
  3690. if (thisLocation == Js::Constants::NoRegister)
  3691. {
  3692. thisLocation = funcInfo->undefinedConstantRegister;
  3693. }
  3694. else
  3695. {
  3696. this->m_writer.Reg2(Js::OpCode::Ld_A, thisLocation, funcInfo->undefinedConstantRegister);
  3697. }
  3698. }
  3699. }
  3700. else if (instLocation != Js::Constants::NoRegister)
  3701. {
  3702. if (envIndex != -1)
  3703. {
  3704. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation,
  3705. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  3706. }
  3707. else if (scope->HasInnerScopeIndex())
  3708. {
  3709. this->m_writer.Reg1Unsigned1(Js::OpCode::LdInnerScope, instLocation, scope->GetInnerScopeIndex());
  3710. }
  3711. else if (symScope != funcInfo->GetBodyScope())
  3712. {
  3713. this->m_writer.Reg2(Js::OpCode::Ld_A, instLocation, scopeLocation);
  3714. }
  3715. else
  3716. {
  3717. this->m_writer.Reg1(Js::OpCode::LdLocalObj, instLocation);
  3718. }
  3719. if (thisLocation != Js::Constants::NoRegister)
  3720. {
  3721. this->m_writer.Reg2(Js::OpCode::Ld_A, thisLocation, funcInfo->undefinedConstantRegister);
  3722. }
  3723. else
  3724. {
  3725. thisLocation = funcInfo->undefinedConstantRegister;
  3726. }
  3727. }
  3728. *pThisLocation = thisLocation;
  3729. *pInstLocation = instLocation;
  3730. if (fLabelDefined)
  3731. {
  3732. this->m_writer.MarkLabel(doneLabel);
  3733. }
  3734. }
  3735. void ByteCodeGenerator::EmitGlobalFncDeclInit(Js::RegSlot rhsLocation, Js::PropertyId propertyId, FuncInfo * funcInfo)
  3736. {
  3737. // Note: declared variables and assignments in the global function go to the root object directly.
  3738. if (this->flags & fscrEval)
  3739. {
  3740. // Func decl's always get their init values before any use, so we don't pre-initialize the property to undef.
  3741. // That means that we have to use ScopedInitFld so that we initialize the property on the right instance
  3742. // even if the instance doesn't have the property yet (i.e., collapse the init-to-undef and the store
  3743. // into one operation). See WOOB 1121763 and 1120973.
  3744. this->m_writer.ScopedProperty(Js::OpCode::ScopedInitFunc, rhsLocation,
  3745. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  3746. }
  3747. else
  3748. {
  3749. this->EmitPatchableRootProperty(Js::OpCode::InitRootFld, rhsLocation, propertyId, false, true, funcInfo);
  3750. }
  3751. }
  3752. void
  3753. ByteCodeGenerator::EmitPatchableRootProperty(Js::OpCode opcode,
  3754. Js::RegSlot regSlot, Js::PropertyId propertyId, bool isLoadMethod, bool isStore, FuncInfo * funcInfo)
  3755. {
  3756. uint cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, isLoadMethod, isStore);
  3757. this->m_writer.PatchableRootProperty(opcode, regSlot, cacheId, isLoadMethod, isStore);
  3758. }
  3759. void ByteCodeGenerator::EmitLocalPropInit(Js::RegSlot rhsLocation, Symbol *sym, FuncInfo *funcInfo)
  3760. {
  3761. Scope *scope = sym->GetScope();
  3762. // Check consistency of sym->IsInSlot.
  3763. Assert(sym->NeedsSlotAlloc(funcInfo) || sym->GetScopeSlot() == Js::Constants::NoProperty);
  3764. // Arrived at the scope in which the property was defined.
  3765. if (sym->NeedsSlotAlloc(funcInfo))
  3766. {
  3767. // The property is in memory rather than register. We'll have to load it from the slots.
  3768. if (scope->GetIsObject())
  3769. {
  3770. Assert(!this->TopFuncInfo()->GetParsedFunctionBody()->DoStackNestedFunc());
  3771. Js::PropertyId propertyId = sym->EnsurePosition(this);
  3772. Js::RegSlot objReg;
  3773. if (scope->HasInnerScopeIndex())
  3774. {
  3775. objReg = funcInfo->InnerScopeToRegSlot(scope);
  3776. }
  3777. else
  3778. {
  3779. objReg = scope->GetLocation();
  3780. }
  3781. uint cacheId = funcInfo->FindOrAddInlineCacheId(objReg, propertyId, false, true);
  3782. Js::OpCode op = this->GetInitFldOp(scope, objReg, funcInfo, sym->GetIsNonSimpleParameter());
  3783. if (objReg != Js::Constants::NoRegister && objReg == funcInfo->frameObjRegister)
  3784. {
  3785. this->m_writer.ElementP(op, rhsLocation, cacheId);
  3786. }
  3787. else if (scope->HasInnerScopeIndex())
  3788. {
  3789. this->m_writer.ElementPIndexed(op, rhsLocation, scope->GetInnerScopeIndex(), cacheId);
  3790. }
  3791. else
  3792. {
  3793. this->m_writer.PatchableProperty(op, rhsLocation, scope->GetLocation(), cacheId);
  3794. }
  3795. }
  3796. else
  3797. {
  3798. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  3799. Js::PropertyId slot = sym->EnsureScopeSlot(funcInfo);
  3800. Js::RegSlot slotReg = scope->GetCanMerge() ? funcInfo->frameSlotsRegister : scope->GetLocation();
  3801. // Now store the property to its slot.
  3802. Js::OpCode op = this->GetStSlotOp(scope, -1, slotReg, false, funcInfo);
  3803. if (slotReg != Js::Constants::NoRegister && slotReg == funcInfo->frameSlotsRegister)
  3804. {
  3805. this->m_writer.SlotI1(op, rhsLocation, slot + Js::ScopeSlots::FirstSlotIndex);
  3806. }
  3807. else
  3808. {
  3809. this->m_writer.SlotI2(op, rhsLocation, scope->GetInnerScopeIndex(), slot + Js::ScopeSlots::FirstSlotIndex);
  3810. }
  3811. }
  3812. }
  3813. if (sym->GetLocation() != Js::Constants::NoRegister && rhsLocation != sym->GetLocation())
  3814. {
  3815. this->m_writer.Reg2(Js::OpCode::Ld_A, sym->GetLocation(), rhsLocation);
  3816. }
  3817. }
  3818. Js::OpCode
  3819. ByteCodeGenerator::GetStSlotOp(Scope *scope, int envIndex, Js::RegSlot scopeLocation, bool chkBlockVar, FuncInfo *funcInfo)
  3820. {
  3821. Js::OpCode op;
  3822. if (envIndex != -1)
  3823. {
  3824. if (scope->GetIsObject())
  3825. {
  3826. op = Js::OpCode::StEnvObjSlot;
  3827. }
  3828. else
  3829. {
  3830. op = Js::OpCode::StEnvSlot;
  3831. }
  3832. }
  3833. else if (scopeLocation != Js::Constants::NoRegister &&
  3834. scopeLocation == funcInfo->frameSlotsRegister)
  3835. {
  3836. op = Js::OpCode::StLocalSlot;
  3837. }
  3838. else if (scopeLocation != Js::Constants::NoRegister &&
  3839. scopeLocation == funcInfo->frameObjRegister)
  3840. {
  3841. op = Js::OpCode::StLocalObjSlot;
  3842. }
  3843. else
  3844. {
  3845. Assert(scope->HasInnerScopeIndex());
  3846. if (scope->GetIsObject())
  3847. {
  3848. op = Js::OpCode::StInnerObjSlot;
  3849. }
  3850. else
  3851. {
  3852. op = Js::OpCode::StInnerSlot;
  3853. }
  3854. }
  3855. if (chkBlockVar)
  3856. {
  3857. op = this->ToChkUndeclOp(op);
  3858. }
  3859. return op;
  3860. }
  3861. Js::OpCode
  3862. ByteCodeGenerator::GetInitFldOp(Scope *scope, Js::RegSlot scopeLocation, FuncInfo *funcInfo, bool letDecl)
  3863. {
  3864. Js::OpCode op;
  3865. if (scopeLocation != Js::Constants::NoRegister &&
  3866. scopeLocation == funcInfo->frameObjRegister)
  3867. {
  3868. op = letDecl ? Js::OpCode::InitLocalLetFld : Js::OpCode::InitLocalFld;
  3869. }
  3870. else if (scope->HasInnerScopeIndex())
  3871. {
  3872. op = letDecl ? Js::OpCode::InitInnerLetFld : Js::OpCode::InitInnerFld;
  3873. }
  3874. else
  3875. {
  3876. op = letDecl ? Js::OpCode::InitLetFld : Js::OpCode::InitFld;
  3877. }
  3878. return op;
  3879. }
  3880. void ByteCodeGenerator::EmitPropStore(Js::RegSlot rhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool isLetDecl, bool isConstDecl, bool isFncDeclVar)
  3881. {
  3882. Js::ByteCodeLabel doneLabel = 0;
  3883. bool fLabelDefined = false;
  3884. Js::PropertyId envIndex = -1;
  3885. Scope *symScope = sym == nullptr || sym->GetIsGlobal() ? this->globalScope : sym->GetScope();
  3886. Assert(symScope);
  3887. // isFncDeclVar denotes that the symbol being stored to here is the var
  3888. // binding of a function declaration and we know we want to store directly
  3889. // to it, skipping over any dynamic scopes that may lie in between.
  3890. Scope *scope = isFncDeclVar ? symScope : nullptr;
  3891. Js::RegSlot scopeLocation = isFncDeclVar ? scope->GetLocation() : Js::Constants::NoRegister;
  3892. bool scopeAcquired = false;
  3893. Js::OpCode op;
  3894. while (!isFncDeclVar)
  3895. {
  3896. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  3897. if (scope == this->globalScope)
  3898. {
  3899. break;
  3900. }
  3901. if (envIndex == -1)
  3902. {
  3903. Assert(funcInfo == scope->GetFunc());
  3904. scopeLocation = scope->GetLocation();
  3905. }
  3906. if (scope == symScope)
  3907. {
  3908. break;
  3909. }
  3910. // Found a scope to which the property may have been added.
  3911. Assert(scope && scope->GetIsDynamic());
  3912. if (!fLabelDefined)
  3913. {
  3914. fLabelDefined = true;
  3915. doneLabel = this->m_writer.DefineLabel();
  3916. }
  3917. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  3918. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  3919. Js::RegSlot unwrappedScopeLocation = scopeLocation;
  3920. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  3921. if (envIndex != -1)
  3922. {
  3923. this->m_writer.BrEnvProperty(
  3924. Js::OpCode::BrOnNoEnvProperty,
  3925. nextLabel,
  3926. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  3927. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  3928. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  3929. this->m_writer.SlotI1(
  3930. Js::OpCode::LdEnvObj,
  3931. instLocation,
  3932. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  3933. if (unwrapWithObj)
  3934. {
  3935. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  3936. }
  3937. this->m_writer.PatchableProperty(
  3938. Js::OpCode::StFld,
  3939. rhsLocation,
  3940. instLocation,
  3941. funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, true));
  3942. funcInfo->ReleaseTmpRegister(instLocation);
  3943. }
  3944. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  3945. {
  3946. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  3947. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  3948. Assert(!unwrapWithObj);
  3949. this->m_writer.ElementP(Js::OpCode::StLocalFld, rhsLocation,
  3950. funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true));
  3951. }
  3952. else
  3953. {
  3954. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  3955. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  3956. if (unwrapWithObj)
  3957. {
  3958. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  3959. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  3960. scopeLocation = unwrappedScopeLocation;
  3961. }
  3962. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  3963. this->m_writer.PatchableProperty(Js::OpCode::StFld, rhsLocation, scopeLocation, cacheId);
  3964. if (unwrapWithObj)
  3965. {
  3966. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  3967. }
  3968. }
  3969. this->m_writer.Br(doneLabel);
  3970. this->m_writer.MarkLabel(nextLabel);
  3971. }
  3972. // Arrived at the scope in which the property was defined.
  3973. if (sym == nullptr || sym->GetIsGlobal())
  3974. {
  3975. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  3976. if (this->flags & fscrEval)
  3977. {
  3978. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  3979. {
  3980. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->frameDisplayRegister, propertyId, false, true);
  3981. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo), rhsLocation, cacheId);
  3982. }
  3983. else
  3984. {
  3985. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, true);
  3986. bool isConsoleScopeLetConst = this->IsConsoleScopeEval() && (isLetDecl || isConstDecl);
  3987. // In "eval", store to a symbol with unknown scope goes through the closure environment.
  3988. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo, isConsoleScopeLetConst), rhsLocation, cacheId);
  3989. }
  3990. }
  3991. else if (this->flags & (fscrImplicitThis | fscrImplicitParents))
  3992. {
  3993. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, true);
  3994. // In "eval", store to a symbol with unknown scope goes through the closure environment.
  3995. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo), rhsLocation, cacheId);
  3996. }
  3997. else
  3998. {
  3999. this->EmitPatchableRootProperty(GetStFldOpCode(funcInfo, true, isLetDecl, isConstDecl, false), rhsLocation, propertyId, false, true, funcInfo);
  4000. }
  4001. }
  4002. else if (sym->GetFuncExpr())
  4003. {
  4004. // Store to function expr variable.
  4005. // strict mode: we need to throw type error
  4006. if (funcInfo->byteCodeFunction->GetIsStrictMode())
  4007. {
  4008. // Note that in this case the sym's location belongs to the parent function, so we can't use it.
  4009. // It doesn't matter which register we use, as long as it's valid for this function.
  4010. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_CantAssignToReadOnly));
  4011. }
  4012. }
  4013. else if (sym->IsInSlot(funcInfo) || envIndex != -1)
  4014. {
  4015. if (!isConstDecl && sym->GetDecl() && sym->GetDecl()->nop == knopConstDecl)
  4016. {
  4017. // This is a case where const reassignment can't be proven statically (e.g., eval, with) so
  4018. // we have to catch it at runtime.
  4019. this->m_writer.W1(
  4020. Js::OpCode::RuntimeReferenceError, SCODE_CODE(ERRAssignmentToConst));
  4021. }
  4022. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4023. Js::PropertyId slot = sym->EnsureScopeSlot(funcInfo);
  4024. bool chkBlockVar = !isLetDecl && !isConstDecl && NeedCheckBlockVar(sym, scope, funcInfo);
  4025. // The property is in memory rather than register. We'll have to load it from the slots.
  4026. op = this->GetStSlotOp(scope, envIndex, scopeLocation, chkBlockVar, funcInfo);
  4027. if (envIndex != -1)
  4028. {
  4029. this->m_writer.SlotI2(op, rhsLocation,
  4030. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var),
  4031. slot + (sym->GetScope()->GetIsObject()? 0 : Js::ScopeSlots::FirstSlotIndex));
  4032. }
  4033. else if (scopeLocation != Js::Constants::NoRegister &&
  4034. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4035. {
  4036. this->m_writer.SlotI1(op, rhsLocation,
  4037. slot + (sym->GetScope()->GetIsObject()? 0 : Js::ScopeSlots::FirstSlotIndex));
  4038. }
  4039. else
  4040. {
  4041. Assert(scope->HasInnerScopeIndex());
  4042. this->m_writer.SlotI2(op, rhsLocation, scope->GetInnerScopeIndex(),
  4043. slot + (sym->GetScope()->GetIsObject()? 0 : Js::ScopeSlots::FirstSlotIndex));
  4044. }
  4045. if (this->ShouldTrackDebuggerMetadata() && (isLetDecl || isConstDecl))
  4046. {
  4047. Js::PropertyId location = scope->GetIsObject() ? sym->GetLocation() : slot;
  4048. this->UpdateDebuggerPropertyInitializationOffset(location, sym->GetPosition(), false);
  4049. }
  4050. }
  4051. else if (isConstDecl)
  4052. {
  4053. this->m_writer.Reg2(Js::OpCode::InitConst, sym->GetLocation(), rhsLocation);
  4054. if (this->ShouldTrackDebuggerMetadata())
  4055. {
  4056. this->UpdateDebuggerPropertyInitializationOffset(sym->GetLocation(), sym->GetPosition());
  4057. }
  4058. }
  4059. else
  4060. {
  4061. if (!isConstDecl && sym->GetDecl() && sym->GetDecl()->nop == knopConstDecl)
  4062. {
  4063. // This is a case where const reassignment can't be proven statically (e.g., eval, with) so
  4064. // we have to catch it at runtime.
  4065. this->m_writer.W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(ERRAssignmentToConst));
  4066. }
  4067. if (rhsLocation != sym->GetLocation())
  4068. {
  4069. this->m_writer.Reg2(Js::OpCode::Ld_A, sym->GetLocation(), rhsLocation);
  4070. if (this->ShouldTrackDebuggerMetadata() && isLetDecl)
  4071. {
  4072. this->UpdateDebuggerPropertyInitializationOffset(sym->GetLocation(), sym->GetPosition());
  4073. }
  4074. }
  4075. }
  4076. if (fLabelDefined)
  4077. {
  4078. this->m_writer.MarkLabel(doneLabel);
  4079. }
  4080. if (scopeAcquired)
  4081. {
  4082. funcInfo->ReleaseTmpRegister(scopeLocation);
  4083. }
  4084. }
  4085. Js::OpCode
  4086. ByteCodeGenerator::GetLdSlotOp(Scope *scope, int envIndex, Js::RegSlot scopeLocation, FuncInfo *funcInfo)
  4087. {
  4088. Js::OpCode op;
  4089. if (envIndex != -1)
  4090. {
  4091. if (scope->GetIsObject())
  4092. {
  4093. op = Js::OpCode::LdEnvObjSlot;
  4094. }
  4095. else
  4096. {
  4097. op = Js::OpCode::LdEnvSlot;
  4098. }
  4099. }
  4100. else if (scopeLocation != Js::Constants::NoRegister &&
  4101. scopeLocation == funcInfo->frameSlotsRegister)
  4102. {
  4103. op = Js::OpCode::LdLocalSlot;
  4104. }
  4105. else if (scopeLocation != Js::Constants::NoRegister &&
  4106. scopeLocation == funcInfo->frameObjRegister)
  4107. {
  4108. op = Js::OpCode::LdLocalObjSlot;
  4109. }
  4110. else if (scope->HasInnerScopeIndex())
  4111. {
  4112. if (scope->GetIsObject())
  4113. {
  4114. op = Js::OpCode::LdInnerObjSlot;
  4115. }
  4116. else
  4117. {
  4118. op = Js::OpCode::LdInnerSlot;
  4119. }
  4120. }
  4121. else
  4122. {
  4123. Assert(scope->GetIsObject());
  4124. op = Js::OpCode::LdObjSlot;
  4125. }
  4126. return op;
  4127. }
  4128. void ByteCodeGenerator::EmitPropLoad(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo)
  4129. {
  4130. // If sym belongs to a parent frame, get it from the closure environment.
  4131. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4132. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4133. // Otherwise, just copy the value to the lhsLocation.
  4134. Js::ByteCodeLabel doneLabel = 0;
  4135. bool fLabelDefined = false;
  4136. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4137. Js::PropertyId envIndex = -1;
  4138. Scope *scope = nullptr;
  4139. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4140. Assert(symScope);
  4141. for (;;)
  4142. {
  4143. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4144. if (scope == this->globalScope)
  4145. {
  4146. break;
  4147. }
  4148. scopeLocation = scope->GetLocation();
  4149. if (scope == symScope)
  4150. {
  4151. break;
  4152. }
  4153. // Found a scope to which the property may have been added.
  4154. Assert(scope && scope->GetIsDynamic());
  4155. if (!fLabelDefined)
  4156. {
  4157. fLabelDefined = true;
  4158. doneLabel = this->m_writer.DefineLabel();
  4159. }
  4160. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4161. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4162. Js::RegSlot unwrappedScopeLocation = Js::Constants::NoRegister;
  4163. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4164. if (envIndex != -1)
  4165. {
  4166. this->m_writer.BrEnvProperty(
  4167. Js::OpCode::BrOnNoEnvProperty,
  4168. nextLabel,
  4169. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4170. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  4171. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4172. this->m_writer.SlotI1(
  4173. Js::OpCode::LdEnvObj,
  4174. instLocation,
  4175. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  4176. if (unwrapWithObj)
  4177. {
  4178. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4179. }
  4180. this->m_writer.PatchableProperty(
  4181. Js::OpCode::LdFld,
  4182. lhsLocation,
  4183. instLocation,
  4184. funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, false));
  4185. funcInfo->ReleaseTmpRegister(instLocation);
  4186. }
  4187. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4188. {
  4189. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4190. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4191. Assert(!unwrapWithObj);
  4192. this->m_writer.ElementP(Js::OpCode::LdLocalFld, lhsLocation,
  4193. funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, false));
  4194. }
  4195. else
  4196. {
  4197. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4198. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4199. if (unwrapWithObj)
  4200. {
  4201. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4202. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4203. scopeLocation = unwrappedScopeLocation;
  4204. }
  4205. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, false);
  4206. this->m_writer.PatchableProperty(Js::OpCode::LdFld, lhsLocation, scopeLocation, cacheId);
  4207. if (unwrapWithObj)
  4208. {
  4209. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4210. }
  4211. }
  4212. this->m_writer.Br(doneLabel);
  4213. this->m_writer.MarkLabel(nextLabel);
  4214. }
  4215. // Arrived at the scope in which the property was defined.
  4216. if (sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo)
  4217. {
  4218. // Ensure this symbol has a slot if it needs one.
  4219. if (sym->IsInSlot(funcInfo))
  4220. {
  4221. Js::PropertyId slot = sym->EnsureScopeSlot(funcInfo);
  4222. funcInfo->FindOrAddSlotProfileId(scope, slot);
  4223. }
  4224. EmitUseBeforeDeclarationRuntimeError(this, lhsLocation);
  4225. }
  4226. else if (sym == nullptr || sym->GetIsGlobal())
  4227. {
  4228. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4229. if (this->flags & fscrEval)
  4230. {
  4231. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4232. {
  4233. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->frameDisplayRegister, propertyId, false, false);
  4234. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4235. }
  4236. else
  4237. {
  4238. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, false);
  4239. // Load of a symbol with unknown scope from within eval
  4240. // Get it from the closure environment.
  4241. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4242. }
  4243. }
  4244. else if (this->flags & (fscrImplicitThis | fscrImplicitParents))
  4245. {
  4246. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, false);
  4247. // Load of a symbol with unknown scope from within eval or event handler.
  4248. // Get it from the closure environment.
  4249. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4250. }
  4251. else
  4252. {
  4253. // Special case non-writable built-ins
  4254. // TODO: support non-writable global property in general by detecting what attribute the property have current?
  4255. // But can't be done if we are byte code serialized, because the attribute might be different for use fields
  4256. // next time we run. May want to catch that in the JIT.
  4257. Js::OpCode opcode = Js::OpCode::LdRootFld;
  4258. // These properties are non-writable
  4259. switch (propertyId)
  4260. {
  4261. case Js::PropertyIds::NaN:
  4262. opcode = Js::OpCode::LdNaN;
  4263. break;
  4264. case Js::PropertyIds::Infinity:
  4265. opcode = Js::OpCode::LdInfinity;
  4266. break;
  4267. case Js::PropertyIds::undefined:
  4268. opcode = Js::OpCode::LdUndef;
  4269. break;
  4270. }
  4271. if (opcode == Js::OpCode::LdRootFld)
  4272. {
  4273. this->EmitPatchableRootProperty(Js::OpCode::LdRootFld, lhsLocation, propertyId, false, false, funcInfo);
  4274. }
  4275. else
  4276. {
  4277. this->Writer()->Reg1(opcode, lhsLocation);
  4278. }
  4279. }
  4280. }
  4281. else if (sym->IsInSlot(funcInfo) || envIndex != -1)
  4282. {
  4283. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4284. Js::PropertyId slot = sym->EnsureScopeSlot(funcInfo);
  4285. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(scope, slot);
  4286. bool chkBlockVar = NeedCheckBlockVar(sym, scope, funcInfo);
  4287. Js::OpCode op;
  4288. // Now get the property from its slot.
  4289. op = this->GetLdSlotOp(scope, envIndex, scopeLocation, funcInfo);
  4290. slot = slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  4291. if (envIndex != -1)
  4292. {
  4293. this->m_writer.SlotI2(op, lhsLocation, envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var), slot, profileId);
  4294. }
  4295. else if (scopeLocation != Js::Constants::NoRegister &&
  4296. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4297. {
  4298. this->m_writer.SlotI1(op, lhsLocation, slot, profileId);
  4299. }
  4300. else if (scope->HasInnerScopeIndex())
  4301. {
  4302. this->m_writer.SlotI2(op, lhsLocation, scope->GetInnerScopeIndex(), slot, profileId);
  4303. }
  4304. else
  4305. {
  4306. Assert(scope->GetIsObject());
  4307. this->m_writer.Slot(op, lhsLocation, scopeLocation, slot, profileId);
  4308. }
  4309. if (chkBlockVar)
  4310. {
  4311. this->m_writer.Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4312. }
  4313. }
  4314. else
  4315. {
  4316. if (lhsLocation != sym->GetLocation())
  4317. {
  4318. this->m_writer.Reg2(Js::OpCode::Ld_A, lhsLocation, sym->GetLocation());
  4319. }
  4320. if (sym->GetIsBlockVar() && ((sym->GetDecl()->nop == knopLetDecl || sym->GetDecl()->nop == knopConstDecl) && sym->GetDecl()->sxVar.isSwitchStmtDecl) && CONFIG_FLAG(TDZ))
  4321. {
  4322. this->m_writer.Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4323. }
  4324. }
  4325. if (fLabelDefined)
  4326. {
  4327. this->m_writer.MarkLabel(doneLabel);
  4328. }
  4329. }
  4330. bool ByteCodeGenerator::NeedCheckBlockVar(Symbol* sym, Scope* scope, FuncInfo* funcInfo) const
  4331. {
  4332. bool tdz = sym->GetIsBlockVar()
  4333. && (scope->GetFunc() != funcInfo || ((sym->GetDecl()->nop == knopLetDecl || sym->GetDecl()->nop == knopConstDecl) && sym->GetDecl()->sxVar.isSwitchStmtDecl))
  4334. && CONFIG_FLAG(TDZ);
  4335. return tdz || sym->GetIsNonSimpleParameter();
  4336. }
  4337. void ByteCodeGenerator::EmitPropDelete(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo)
  4338. {
  4339. // If sym belongs to a parent frame, delete it from the closure environment.
  4340. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4341. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4342. // Otherwise, just return false.
  4343. Js::ByteCodeLabel doneLabel = 0;
  4344. bool fLabelDefined = false;
  4345. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4346. Js::PropertyId envIndex = -1;
  4347. Scope *scope = nullptr;
  4348. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4349. Assert(symScope);
  4350. for (;;)
  4351. {
  4352. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4353. if (scope == this->globalScope)
  4354. {
  4355. scopeLocation = ByteCodeGenerator::RootObjectRegister;
  4356. }
  4357. else if (envIndex == -1)
  4358. {
  4359. Assert(funcInfo == scope->GetFunc());
  4360. scopeLocation = scope->GetLocation();
  4361. }
  4362. if (scope == symScope)
  4363. {
  4364. break;
  4365. }
  4366. // Found a scope to which the property may have been added.
  4367. Assert(scope && scope->GetIsDynamic());
  4368. if (!fLabelDefined)
  4369. {
  4370. fLabelDefined = true;
  4371. doneLabel = this->m_writer.DefineLabel();
  4372. }
  4373. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4374. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4375. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4376. if (envIndex != -1)
  4377. {
  4378. this->m_writer.BrEnvProperty(
  4379. Js::OpCode::BrOnNoEnvProperty,
  4380. nextLabel,
  4381. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4382. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  4383. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4384. this->m_writer.SlotI1(
  4385. Js::OpCode::LdEnvObj,
  4386. instLocation,
  4387. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  4388. if (unwrapWithObj)
  4389. {
  4390. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4391. }
  4392. this->m_writer.Property(Js::OpCode::DeleteFld, lhsLocation, instLocation,
  4393. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4394. funcInfo->ReleaseTmpRegister(instLocation);
  4395. }
  4396. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4397. {
  4398. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4399. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4400. Assert(!unwrapWithObj);
  4401. this->m_writer.ElementU(Js::OpCode::DeleteLocalFld, lhsLocation,
  4402. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4403. }
  4404. else
  4405. {
  4406. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4407. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4408. Js::RegSlot unwrappedScopeLocation = Js::Constants::NoRegister;
  4409. if (unwrapWithObj)
  4410. {
  4411. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4412. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4413. scopeLocation = unwrappedScopeLocation;
  4414. }
  4415. this->m_writer.Property(Js::OpCode::DeleteFld, lhsLocation, scopeLocation,
  4416. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4417. if (unwrapWithObj)
  4418. {
  4419. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4420. }
  4421. }
  4422. this->m_writer.Br(doneLabel);
  4423. this->m_writer.MarkLabel(nextLabel);
  4424. }
  4425. // Arrived at the scope in which the property was defined.
  4426. if (sym == nullptr || sym->GetIsGlobal())
  4427. {
  4428. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4429. if (this->flags & (fscrEval | fscrImplicitThis | fscrImplicitParents))
  4430. {
  4431. this->m_writer.ScopedProperty(Js::OpCode::ScopedDeleteFld, lhsLocation,
  4432. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4433. }
  4434. else
  4435. {
  4436. this->m_writer.Property(Js::OpCode::DeleteRootFld, lhsLocation, ByteCodeGenerator::RootObjectRegister,
  4437. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4438. }
  4439. }
  4440. else
  4441. {
  4442. // The delete will look like a non-local reference, so make sure a slot is reserved.
  4443. sym->EnsureScopeSlot(funcInfo);
  4444. this->m_writer.Reg1(Js::OpCode::LdFalse, lhsLocation);
  4445. }
  4446. if (fLabelDefined)
  4447. {
  4448. this->m_writer.MarkLabel(doneLabel);
  4449. }
  4450. }
  4451. void ByteCodeGenerator::EmitTypeOfFld(FuncInfo * funcInfo, Js::PropertyId propertyId, Js::RegSlot value, Js::RegSlot instance, Js::OpCode ldFldOp)
  4452. {
  4453. uint cacheId;
  4454. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  4455. switch (ldFldOp)
  4456. {
  4457. case Js::OpCode::LdRootFldForTypeOf:
  4458. cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, false, false);
  4459. this->Writer()->PatchableRootProperty(ldFldOp, tmpReg, cacheId, false, false);
  4460. break;
  4461. case Js::OpCode::LdLocalFld:
  4462. case Js::OpCode::ScopedLdFldForTypeOf:
  4463. cacheId = funcInfo->FindOrAddInlineCacheId(instance, propertyId, false, false);
  4464. this->Writer()->ElementP(ldFldOp, tmpReg, cacheId);
  4465. break;
  4466. default:
  4467. cacheId = funcInfo->FindOrAddInlineCacheId(instance, propertyId, false, false);
  4468. this->Writer()->PatchableProperty(ldFldOp, tmpReg, instance, cacheId);
  4469. break;
  4470. }
  4471. this->Writer()->Reg2(Js::OpCode::Typeof, value, tmpReg);
  4472. funcInfo->ReleaseTmpRegister(tmpReg);
  4473. }
  4474. void ByteCodeGenerator::EmitPropTypeof(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo)
  4475. {
  4476. // If sym belongs to a parent frame, delete it from the closure environment.
  4477. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4478. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4479. // Otherwise, just return false
  4480. Js::ByteCodeLabel doneLabel = 0;
  4481. bool fLabelDefined = false;
  4482. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4483. Js::PropertyId envIndex = -1;
  4484. Scope *scope = nullptr;
  4485. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4486. Assert(symScope);
  4487. for (;;)
  4488. {
  4489. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4490. if (scope == this->globalScope)
  4491. {
  4492. scopeLocation = ByteCodeGenerator::RootObjectRegister;
  4493. }
  4494. else if (envIndex == -1)
  4495. {
  4496. Assert(funcInfo == scope->GetFunc());
  4497. scopeLocation = scope->GetLocation();
  4498. }
  4499. if (scope == symScope)
  4500. {
  4501. break;
  4502. }
  4503. // Found a scope to which the property may have been added.
  4504. Assert(scope && scope->GetIsDynamic());
  4505. if (!fLabelDefined)
  4506. {
  4507. fLabelDefined = true;
  4508. doneLabel = this->m_writer.DefineLabel();
  4509. }
  4510. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4511. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4512. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4513. if (envIndex != -1)
  4514. {
  4515. this->m_writer.BrEnvProperty(Js::OpCode::BrOnNoEnvProperty, nextLabel,
  4516. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4517. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  4518. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4519. this->m_writer.SlotI1(Js::OpCode::LdEnvObj,
  4520. instLocation,
  4521. envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var));
  4522. if (unwrapWithObj)
  4523. {
  4524. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4525. }
  4526. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, instLocation, Js::OpCode::LdFldForTypeOf);
  4527. funcInfo->ReleaseTmpRegister(instLocation);
  4528. }
  4529. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4530. {
  4531. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4532. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4533. Assert(!unwrapWithObj);
  4534. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, scopeLocation, Js::OpCode::LdLocalFld);
  4535. }
  4536. else
  4537. {
  4538. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4539. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4540. Js::RegSlot unwrappedScopeLocation = Js::Constants::NoRegister;
  4541. if (unwrapWithObj)
  4542. {
  4543. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4544. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4545. scopeLocation = unwrappedScopeLocation;
  4546. }
  4547. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, scopeLocation, Js::OpCode::LdFldForTypeOf);
  4548. if (unwrapWithObj)
  4549. {
  4550. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4551. }
  4552. }
  4553. this->m_writer.Br(doneLabel);
  4554. this->m_writer.MarkLabel(nextLabel);
  4555. }
  4556. // Arrived at the scope in which the property was defined.
  4557. if (sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo)
  4558. {
  4559. // Ensure this symbol has a slot if it needs one.
  4560. if (sym->IsInSlot(funcInfo))
  4561. {
  4562. Js::PropertyId slot = sym->EnsureScopeSlot(funcInfo);
  4563. funcInfo->FindOrAddSlotProfileId(scope, slot);
  4564. }
  4565. EmitUseBeforeDeclarationRuntimeError(this, lhsLocation);
  4566. }
  4567. else if (sym == nullptr || sym->GetIsGlobal())
  4568. {
  4569. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4570. if (this->flags & fscrEval)
  4571. {
  4572. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4573. {
  4574. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->frameDisplayRegister, Js::OpCode::ScopedLdFldForTypeOf);
  4575. }
  4576. else
  4577. {
  4578. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->GetEnvRegister(), Js::OpCode::ScopedLdFldForTypeOf);
  4579. }
  4580. }
  4581. else if (this->flags & (fscrImplicitThis | fscrImplicitParents))
  4582. {
  4583. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->GetEnvRegister(), Js::OpCode::ScopedLdFldForTypeOf);
  4584. }
  4585. else
  4586. {
  4587. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, ByteCodeGenerator::RootObjectRegister, Js::OpCode::LdRootFldForTypeOf);
  4588. }
  4589. }
  4590. else if (sym->IsInSlot(funcInfo) || envIndex != -1)
  4591. {
  4592. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4593. Js::PropertyId slot = sym->EnsureScopeSlot(funcInfo);
  4594. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(scope, slot);
  4595. Js::RegSlot tmpLocation = funcInfo->AcquireTmpRegister();
  4596. bool chkBlockVar = NeedCheckBlockVar(sym, scope, funcInfo);
  4597. Js::OpCode op;
  4598. op = this->GetLdSlotOp(scope, envIndex, scopeLocation, funcInfo);
  4599. slot = slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  4600. if (envIndex != -1)
  4601. {
  4602. this->m_writer.SlotI2(op, tmpLocation, envIndex + Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var), slot, profileId);
  4603. }
  4604. else if (scopeLocation != Js::Constants::NoRegister &&
  4605. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4606. {
  4607. this->m_writer.SlotI1(op, tmpLocation, slot, profileId);
  4608. }
  4609. else if (scope->HasInnerScopeIndex())
  4610. {
  4611. this->m_writer.SlotI2(op, tmpLocation, scope->GetInnerScopeIndex(), slot, profileId);
  4612. }
  4613. else
  4614. {
  4615. Assert(scope->GetIsObject());
  4616. this->m_writer.Slot(op, tmpLocation, scopeLocation, slot, profileId);
  4617. }
  4618. if (chkBlockVar)
  4619. {
  4620. this->m_writer.Reg1(Js::OpCode::ChkUndecl, tmpLocation);
  4621. }
  4622. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, tmpLocation);
  4623. funcInfo->ReleaseTmpRegister(tmpLocation);
  4624. }
  4625. else
  4626. {
  4627. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, sym->GetLocation());
  4628. }
  4629. if (fLabelDefined)
  4630. {
  4631. this->m_writer.MarkLabel(doneLabel);
  4632. }
  4633. }
  4634. void ByteCodeGenerator::EnsureNoRedeclarations(ParseNode *pnodeBlock, FuncInfo *funcInfo)
  4635. {
  4636. // Emit dynamic runtime checks for variable re-declarations. Only necessary for global functions (script or eval).
  4637. // In eval only var declarations can cause redeclaration, and only in non-strict mode, because let/const variables
  4638. // remain local to the eval code.
  4639. Assert(pnodeBlock->nop == knopBlock);
  4640. Assert(pnodeBlock->sxBlock.blockType == PnodeBlockType::Global || pnodeBlock->sxBlock.scope->GetScopeType() == ScopeType_GlobalEvalBlock);
  4641. if (!(this->flags & fscrEvalCode))
  4642. {
  4643. IterateBlockScopedVariables(pnodeBlock, [this](ParseNode *pnode)
  4644. {
  4645. FuncInfo *funcInfo = this->TopFuncInfo();
  4646. Symbol *sym = pnode->sxVar.sym;
  4647. Assert(sym->GetIsGlobal());
  4648. Js::PropertyId propertyId = sym->EnsurePosition(this);
  4649. this->m_writer.ElementRootU(Js::OpCode::EnsureNoRootFld, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4650. });
  4651. }
  4652. for (ParseNode *pnode = funcInfo->root->sxFnc.pnodeVars; pnode; pnode = pnode->sxVar.pnodeNext)
  4653. {
  4654. Symbol* sym = pnode->sxVar.sym;
  4655. if (sym == nullptr || pnode->sxVar.isBlockScopeFncDeclVar)
  4656. continue;
  4657. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  4658. {
  4659. // The init node was bound to the catch object, because it's inside a catch and has the
  4660. // same name as the catch object. But we want to define a user var at function scope,
  4661. // so find the right symbol. (We'll still assign the RHS value to the catch object symbol.)
  4662. // This also applies to a var declaration in the same scope as a let declaration.
  4663. // Assert that catch cannot be at function scope and let and var at function scope is redeclaration error.
  4664. Assert(sym->GetIsCatch() || funcInfo->bodyScope != sym->GetScope() || !this->scriptContext->GetConfig()->IsBlockScopeEnabled());
  4665. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  4666. Assert(sym && !sym->GetIsCatch() && !sym->GetIsBlockVar());
  4667. }
  4668. Assert(sym->GetIsGlobal());
  4669. if (sym->GetSymbolType() == STVariable)
  4670. {
  4671. Js::PropertyId propertyId = sym->EnsurePosition(this);
  4672. if (this->flags & fscrEval)
  4673. {
  4674. if (!funcInfo->byteCodeFunction->GetIsStrictMode())
  4675. {
  4676. this->m_writer.ScopedProperty(Js::OpCode::ScopedEnsureNoRedeclFld, ByteCodeGenerator::RootObjectRegister,
  4677. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4678. }
  4679. }
  4680. else
  4681. {
  4682. this->m_writer.ElementRootU(Js::OpCode::EnsureNoRootRedeclFld, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4683. }
  4684. }
  4685. }
  4686. }
  4687. void ByteCodeGenerator::RecordAllIntConstants(FuncInfo * funcInfo)
  4688. {
  4689. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  4690. funcInfo->constantToRegister.Map([byteCodeFunction](unsigned int val, Js::RegSlot location)
  4691. {
  4692. byteCodeFunction->RecordIntConstant(byteCodeFunction->MapRegSlot(location), val);
  4693. });
  4694. }
  4695. void ByteCodeGenerator::RecordAllStrConstants(FuncInfo * funcInfo)
  4696. {
  4697. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  4698. funcInfo->stringToRegister.Map([byteCodeFunction](IdentPtr pid, Js::RegSlot location)
  4699. {
  4700. byteCodeFunction->RecordStrConstant(byteCodeFunction->MapRegSlot(location), pid->Psz(), pid->Cch());
  4701. });
  4702. }
  4703. void ByteCodeGenerator::RecordAllStringTemplateCallsiteConstants(FuncInfo* funcInfo)
  4704. {
  4705. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  4706. funcInfo->stringTemplateCallsiteRegisterMap.Map([byteCodeFunction](ParseNodePtr pnode, Js::RegSlot location)
  4707. {
  4708. Js::ScriptContext* scriptContext = byteCodeFunction->GetScriptContext();
  4709. Js::JavascriptLibrary* library = scriptContext->GetLibrary();
  4710. Js::RecyclableObject* callsiteObject = library->TryGetStringTemplateCallsiteObject(pnode);
  4711. if (callsiteObject == nullptr)
  4712. {
  4713. Js::RecyclableObject* rawArray = ByteCodeGenerator::BuildArrayFromStringList(pnode->sxStrTemplate.pnodeStringRawLiterals, pnode->sxStrTemplate.countStringLiterals, scriptContext);
  4714. rawArray->Freeze();
  4715. callsiteObject = ByteCodeGenerator::BuildArrayFromStringList(pnode->sxStrTemplate.pnodeStringLiterals, pnode->sxStrTemplate.countStringLiterals, scriptContext);
  4716. callsiteObject->SetPropertyWithAttributes(Js::PropertyIds::raw, rawArray, PropertyNone, nullptr);
  4717. callsiteObject->Freeze();
  4718. library->AddStringTemplateCallsiteObject(callsiteObject);
  4719. }
  4720. byteCodeFunction->RecordConstant(byteCodeFunction->MapRegSlot(location), callsiteObject);
  4721. });
  4722. }
  4723. bool IsApplyArgs(ParseNode* callNode)
  4724. {
  4725. ParseNode* target = callNode->sxCall.pnodeTarget;
  4726. ParseNode* args = callNode->sxCall.pnodeArgs;
  4727. if ((target != nullptr) && (target->nop == knopDot))
  4728. {
  4729. ParseNode* lhsNode = target->sxBin.pnode1;
  4730. if ((lhsNode != nullptr) && ((lhsNode->nop == knopDot) || (lhsNode->nop == knopName)) && !IsArguments(lhsNode))
  4731. {
  4732. ParseNode* nameNode = target->sxBin.pnode2;
  4733. if (nameNode != nullptr)
  4734. {
  4735. bool nameIsApply = nameNode->sxPid.PropertyIdFromNameNode() == Js::PropertyIds::apply;
  4736. if (nameIsApply && args != nullptr && args->nop == knopList)
  4737. {
  4738. ParseNode* arg1 = args->sxBin.pnode1;
  4739. ParseNode* arg2 = args->sxBin.pnode2;
  4740. if ((arg1 != nullptr) && (arg1->nop == knopThis) && (arg2 != nullptr) && (arg2->nop == knopName) && (arg2->sxPid.sym != nullptr))
  4741. {
  4742. return arg2->sxPid.sym->GetIsArguments();
  4743. }
  4744. }
  4745. }
  4746. }
  4747. }
  4748. return false;
  4749. }
  4750. void PostCheckApplyEnclosesArgs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, ApplyCheck* applyCheck)
  4751. {
  4752. if ((pnode == nullptr) || (!applyCheck->matches))
  4753. {
  4754. return;
  4755. }
  4756. if (pnode->nop == knopCall)
  4757. {
  4758. if ((!pnode->isUsed) && IsApplyArgs(pnode))
  4759. {
  4760. if (!applyCheck->insideApplyCall)
  4761. {
  4762. applyCheck->matches = false;
  4763. }
  4764. applyCheck->insideApplyCall = false;
  4765. }
  4766. }
  4767. }
  4768. void CheckApplyEnclosesArgs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, ApplyCheck* applyCheck)
  4769. {
  4770. if ((pnode == nullptr) || (!applyCheck->matches))
  4771. {
  4772. return;
  4773. }
  4774. switch (pnode->nop)
  4775. {
  4776. case knopName:
  4777. {
  4778. Symbol* sym = pnode->sxPid.sym;
  4779. if (sym != nullptr)
  4780. {
  4781. if (sym->GetIsArguments())
  4782. {
  4783. if (!applyCheck->insideApplyCall)
  4784. {
  4785. applyCheck->matches = false;
  4786. }
  4787. }
  4788. }
  4789. break;
  4790. }
  4791. case knopCall:
  4792. if ((!pnode->isUsed) && IsApplyArgs(pnode))
  4793. {
  4794. // no nested apply calls
  4795. if (applyCheck->insideApplyCall)
  4796. {
  4797. applyCheck->matches = false;
  4798. }
  4799. else
  4800. {
  4801. applyCheck->insideApplyCall = true;
  4802. applyCheck->sawApply = true;
  4803. pnode->sxCall.isApplyCall = true;
  4804. }
  4805. }
  4806. break;
  4807. }
  4808. }
  4809. unsigned int CountArguments(ParseNode *pnode, BOOL *pSideEffect = nullptr)
  4810. {
  4811. // If the caller passed us a pSideEffect, it wants to know whether there are potential
  4812. // side-effects in the argument list. We need to know this so that the call target
  4813. // operands can be preserved if necessary.
  4814. // For now, treat any non-leaf op as a potential side-effect. This causes no detectable slowdowns,
  4815. // but we can be more precise if we need to be.
  4816. if (pSideEffect)
  4817. {
  4818. *pSideEffect = FALSE;
  4819. }
  4820. unsigned int argCount = 1;
  4821. if (pnode != nullptr)
  4822. {
  4823. while (pnode->nop == knopList)
  4824. {
  4825. argCount++;
  4826. if (pSideEffect && !(ParseNode::Grfnop(pnode->sxBin.pnode1->nop) & fnopLeaf))
  4827. {
  4828. *pSideEffect = TRUE;
  4829. }
  4830. pnode = pnode->sxBin.pnode2;
  4831. }
  4832. argCount++;
  4833. if (pSideEffect && !(ParseNode::Grfnop(pnode->nop) & fnopLeaf))
  4834. {
  4835. *pSideEffect = TRUE;
  4836. }
  4837. }
  4838. return argCount;
  4839. }
  4840. void SaveOpndValue(ParseNode *pnode, FuncInfo *funcInfo)
  4841. {
  4842. // Save a local name to a register other than its home location.
  4843. // This guards against side-effects in cases like x.foo(x = bar()).
  4844. Symbol *sym = nullptr;
  4845. if (pnode->nop == knopName)
  4846. {
  4847. sym = pnode->sxPid.sym;
  4848. }
  4849. else if (pnode->nop == knopComputedName)
  4850. {
  4851. ParseNode *pnode1 = pnode->sxUni.pnode1;
  4852. if (pnode1->nop == knopName)
  4853. {
  4854. sym = pnode1->sxPid.sym;
  4855. }
  4856. }
  4857. if (sym == nullptr)
  4858. {
  4859. return;
  4860. }
  4861. // If the target is a local being kept in its home location,
  4862. // protect the target's value in the event the home location is overwritten.
  4863. if (pnode->location != Js::Constants::NoRegister &&
  4864. sym->GetScope()->GetFunc() == funcInfo &&
  4865. pnode->location == sym->GetLocation())
  4866. {
  4867. pnode->location = funcInfo->AcquireTmpRegister();
  4868. }
  4869. }
  4870. void ByteCodeGenerator::StartStatement(ParseNode* node)
  4871. {
  4872. Assert(TopFuncInfo() != nullptr);
  4873. m_writer.StartStatement(node, TopFuncInfo()->curTmpReg - TopFuncInfo()->firstTmpReg);
  4874. }
  4875. void ByteCodeGenerator::EndStatement(ParseNode* node)
  4876. {
  4877. m_writer.EndStatement(node);
  4878. }
  4879. void ByteCodeGenerator::StartSubexpression(ParseNode* node)
  4880. {
  4881. Assert(TopFuncInfo() != nullptr);
  4882. m_writer.StartSubexpression(node);
  4883. }
  4884. void ByteCodeGenerator::EndSubexpression(ParseNode* node)
  4885. {
  4886. m_writer.EndSubexpression(node);
  4887. }
  4888. void EmitReference(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  4889. {
  4890. // Generate code for the LHS of an assignment.
  4891. switch (pnode->nop)
  4892. {
  4893. case knopDot:
  4894. Emit(pnode->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  4895. break;
  4896. case knopIndex:
  4897. Emit(pnode->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  4898. Emit(pnode->sxBin.pnode2, byteCodeGenerator, funcInfo, false);
  4899. break;
  4900. case knopName:
  4901. break;
  4902. case knopArrayPattern:
  4903. case knopObjectPattern:
  4904. break;
  4905. case knopCall:
  4906. case knopNew:
  4907. // Emit the operands of a call that will be used as a LHS.
  4908. // These have to be emitted before the RHS, but they have to persist until
  4909. // the end of the expression.
  4910. // Emit the call target operands first.
  4911. switch (pnode->sxCall.pnodeTarget->nop)
  4912. {
  4913. case knopDot:
  4914. case knopIndex:
  4915. funcInfo->AcquireLoc(pnode->sxCall.pnodeTarget);
  4916. EmitReference(pnode->sxCall.pnodeTarget, byteCodeGenerator, funcInfo);
  4917. break;
  4918. case knopName:
  4919. {
  4920. Symbol *sym = pnode->sxCall.pnodeTarget->sxPid.sym;
  4921. if (!sym || sym->GetLocation() == Js::Constants::NoRegister)
  4922. {
  4923. funcInfo->AcquireLoc(pnode->sxCall.pnodeTarget);
  4924. }
  4925. if (sym && (sym->IsInSlot(funcInfo) || sym->GetScope()->GetFunc() != funcInfo))
  4926. {
  4927. // Can't get the value from the assigned register, so load it here.
  4928. EmitLoad(pnode->sxCall.pnodeTarget, byteCodeGenerator, funcInfo);
  4929. }
  4930. else
  4931. {
  4932. EmitReference(pnode->sxCall.pnodeTarget, byteCodeGenerator, funcInfo);
  4933. }
  4934. break;
  4935. }
  4936. default:
  4937. EmitLoad(pnode->sxCall.pnodeTarget, byteCodeGenerator, funcInfo);
  4938. break;
  4939. }
  4940. // Now the arg list. We evaluate everything now and emit the ArgOut's later.
  4941. if (pnode->sxCall.pnodeArgs)
  4942. {
  4943. ParseNode *pnodeArg = pnode->sxCall.pnodeArgs;
  4944. while (pnodeArg->nop == knopList)
  4945. {
  4946. Emit(pnodeArg->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  4947. pnodeArg = pnodeArg->sxBin.pnode2;
  4948. }
  4949. Emit(pnodeArg, byteCodeGenerator, funcInfo, false);
  4950. }
  4951. break;
  4952. default:
  4953. Emit(pnode, byteCodeGenerator, funcInfo, false);
  4954. break;
  4955. }
  4956. }
  4957. void EmitGetIterator(Js::RegSlot iteratorLocation, Js::RegSlot iterableLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  4958. void EmitIteratorNext(Js::RegSlot itemLocation, Js::RegSlot iteratorLocation, Js::RegSlot nextInputLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  4959. void EmitIteratorComplete(Js::RegSlot doneLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  4960. void EmitIteratorValue(Js::RegSlot valueLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  4961. void EmitDestructuredElement(ParseNode *elem, Js::RegSlot sourceLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo *funcInfo)
  4962. {
  4963. switch (elem->nop)
  4964. {
  4965. case knopVarDecl:
  4966. case knopLetDecl:
  4967. case knopConstDecl:
  4968. // We manually need to set NeedDeclaration since the node won't be visited.
  4969. elem->sxVar.sym->SetNeedDeclaration(false);
  4970. break;
  4971. case knopName:
  4972. if (elem->sxPid.sym != nullptr && elem->sxPid.sym->GetNeedDeclaration())
  4973. {
  4974. bool needToRelease = elem->location == Js::Constants::NoRegister;
  4975. EmitUseBeforeDeclaration(elem, byteCodeGenerator, funcInfo);
  4976. if (needToRelease && elem->location != Js::Constants::NoRegister)
  4977. {
  4978. // We have acquired register as a part of EmitUseBeforeDeclaration. We need to release that.
  4979. funcInfo->ReleaseTmpRegister(elem->location);
  4980. }
  4981. }
  4982. break;
  4983. default:
  4984. EmitReference(elem, byteCodeGenerator, funcInfo);
  4985. }
  4986. EmitAssignment(nullptr, elem, sourceLocation, byteCodeGenerator, funcInfo);
  4987. funcInfo->ReleaseReference(elem);
  4988. }
  4989. void EmitDestructuredRestArray(ParseNode *elem, Js::RegSlot iteratorLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  4990. {
  4991. Js::RegSlot restArrayLocation = funcInfo->AcquireTmpRegister();
  4992. byteCodeGenerator->Writer()->Reg1Unsigned1(
  4993. Js::OpCode::NewScArray,
  4994. restArrayLocation,
  4995. ByteCodeGenerator::DefaultArraySize);
  4996. // BytecodeGen can't convey to IRBuilder that some of the temporaries used here are live. When we
  4997. // have a rest parameter, a counter is used in a loop for the array index, but there is no way to
  4998. // convey this is live on the back edge.
  4999. // As a workaround, we have a persistent var reg that is used for the loop counter
  5000. Js::RegSlot counterLocation = elem->location;
  5001. // TODO[ianhall]: Is calling EnregisterConstant() during Emit phase allowed?
  5002. Js::RegSlot zeroConstantReg = byteCodeGenerator->EnregisterConstant(0);
  5003. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, counterLocation, zeroConstantReg);
  5004. // loopTop:
  5005. Js::ByteCodeLabel loopTop = byteCodeGenerator->Writer()->DefineLabel();
  5006. byteCodeGenerator->Writer()->MarkLabel(loopTop);
  5007. Js::RegSlot itemLocation = funcInfo->AcquireTmpRegister();
  5008. EmitIteratorNext(itemLocation, iteratorLocation, Js::Constants::NoRegister, byteCodeGenerator, funcInfo);
  5009. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  5010. EmitIteratorComplete(doneLocation, itemLocation, byteCodeGenerator, funcInfo);
  5011. Js::ByteCodeLabel iteratorDone = byteCodeGenerator->Writer()->DefineLabel();
  5012. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, iteratorDone, doneLocation);
  5013. Js::RegSlot valueLocation = funcInfo->AcquireTmpRegister();
  5014. EmitIteratorValue(valueLocation, itemLocation, byteCodeGenerator, funcInfo);
  5015. byteCodeGenerator->Writer()->Element(
  5016. ByteCodeGenerator::GetStElemIOpCode(funcInfo),
  5017. valueLocation, restArrayLocation, counterLocation);
  5018. funcInfo->ReleaseTmpRegister(valueLocation);
  5019. funcInfo->ReleaseTmpRegister(doneLocation);
  5020. funcInfo->ReleaseTmpRegister(itemLocation);
  5021. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Incr_A, counterLocation, counterLocation);
  5022. byteCodeGenerator->Writer()->Br(loopTop);
  5023. // iteratorDone:
  5024. byteCodeGenerator->Writer()->MarkLabel(iteratorDone);
  5025. ParseNode *restElem = elem->sxUni.pnode1;
  5026. EmitDestructuredElement(restElem, restArrayLocation, byteCodeGenerator, funcInfo);
  5027. funcInfo->ReleaseTmpRegister(restArrayLocation);
  5028. }
  5029. /*
  5030. EmitDestructuredArray(lhsArray, rhs):
  5031. iterator = rhs[@@iterator]
  5032. if lhsArray empty
  5033. return
  5034. for each element in lhsArray except rest
  5035. value = iterator.next()
  5036. if element is a nested destructured array
  5037. EmitDestructuredArray(element, value)
  5038. else
  5039. if value is undefined and there is an initializer
  5040. evaluate initializer
  5041. evaluate element reference
  5042. element = initializer
  5043. else
  5044. element = value
  5045. if lhsArray has a rest element
  5046. rest = []
  5047. while iterator is not done
  5048. value = iterator.next()
  5049. rest.append(value)
  5050. */
  5051. void EmitDestructuredArray(
  5052. ParseNode *lhs,
  5053. Js::RegSlot rhsLocation,
  5054. ByteCodeGenerator *byteCodeGenerator,
  5055. FuncInfo *funcInfo)
  5056. {
  5057. byteCodeGenerator->StartStatement(lhs);
  5058. Js::RegSlot iteratorLocation = funcInfo->AcquireTmpRegister();
  5059. EmitGetIterator(iteratorLocation, rhsLocation, byteCodeGenerator, funcInfo);
  5060. Assert(lhs->nop == knopArrayPattern);
  5061. ParseNode *list = lhs->sxArrLit.pnode1;
  5062. if (list == nullptr)
  5063. {
  5064. // No elements to bind or assign.
  5065. funcInfo->ReleaseTmpRegister(iteratorLocation);
  5066. return;
  5067. }
  5068. ParseNode *elem = nullptr;
  5069. while (list != nullptr)
  5070. {
  5071. ParseNode *init = nullptr;
  5072. if (list->nop == knopList)
  5073. {
  5074. elem = list->sxBin.pnode1;
  5075. }
  5076. else
  5077. {
  5078. elem = list;
  5079. }
  5080. if (elem->nop == knopEllipsis)
  5081. {
  5082. // Rest must be the last argument - no need to continue.
  5083. break;
  5084. }
  5085. switch (elem->nop)
  5086. {
  5087. case knopAsg:
  5088. // An assignment node will always have an initializer
  5089. init = elem->sxBin.pnode2;
  5090. elem = elem->sxBin.pnode1;
  5091. break;
  5092. case knopVarDecl:
  5093. case knopLetDecl:
  5094. case knopConstDecl:
  5095. init = elem->sxVar.pnodeInit;
  5096. break;
  5097. default:
  5098. break;
  5099. }
  5100. byteCodeGenerator->StartStatement(elem);
  5101. Js::RegSlot itemLocation = funcInfo->AcquireTmpRegister();
  5102. EmitIteratorNext(itemLocation, iteratorLocation, Js::Constants::NoRegister, byteCodeGenerator, funcInfo);
  5103. if (elem->nop == knopEmpty)
  5104. {
  5105. // Missing elements only require a next call.
  5106. funcInfo->ReleaseTmpRegister(itemLocation);
  5107. if (list->nop == knopList)
  5108. {
  5109. list = list->sxBin.pnode2;
  5110. continue;
  5111. }
  5112. else
  5113. {
  5114. break;
  5115. }
  5116. }
  5117. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  5118. EmitIteratorComplete(doneLocation, itemLocation, byteCodeGenerator, funcInfo);
  5119. // If the iterator hasn't completed, skip assigning undefined.
  5120. Js::ByteCodeLabel iteratorAlreadyDone = byteCodeGenerator->Writer()->DefineLabel();
  5121. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, iteratorAlreadyDone, doneLocation);
  5122. funcInfo->ReleaseTmpRegister(doneLocation);
  5123. // We're not done with the iterator, so assign the .next() value.
  5124. Js::RegSlot valueLocation = funcInfo->AcquireTmpRegister();
  5125. EmitIteratorValue(valueLocation, itemLocation, byteCodeGenerator, funcInfo);
  5126. Js::ByteCodeLabel beforeDefaultAssign = byteCodeGenerator->Writer()->DefineLabel();
  5127. byteCodeGenerator->Writer()->Br(beforeDefaultAssign);
  5128. // iteratorAlreadyDone:
  5129. byteCodeGenerator->Writer()->MarkLabel(iteratorAlreadyDone);
  5130. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocation, funcInfo->undefinedConstantRegister);
  5131. // beforeDefaultAssign:
  5132. byteCodeGenerator->Writer()->MarkLabel(beforeDefaultAssign);
  5133. if (elem->IsPattern())
  5134. {
  5135. // If we get an undefined value and have an initializer, use it in place of undefined.
  5136. if (init != nullptr)
  5137. {
  5138. /*
  5139. the IR builder uses two symbols for a temp register in the if else path
  5140. R9 <- R3
  5141. if (...)
  5142. R9 <- R2
  5143. R10 = R9.<property> // error -> IR creates a new lifetime for the if path, and the direct path dest is not referenced
  5144. hence we have to create a new temp
  5145. TEMP REG USED TO FIX THIS PRODUCES THIS
  5146. R9 <- R3
  5147. if (BrEq_A R9, R3)
  5148. R10 <- R2 :
  5149. else
  5150. R10 <- R9 : skipdefault
  5151. ... = R10[@@iterator] : loadIter
  5152. */
  5153. // Temp Register
  5154. Js::RegSlot valueLocationTmp = funcInfo->AcquireTmpRegister();
  5155. byteCodeGenerator->StartStatement(init);
  5156. Js::ByteCodeLabel skipDefault = byteCodeGenerator->Writer()->DefineLabel();
  5157. Js::ByteCodeLabel loadIter = byteCodeGenerator->Writer()->DefineLabel();
  5158. // check value is undefined
  5159. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrNeq_A, skipDefault, valueLocation, funcInfo->undefinedConstantRegister);
  5160. // Evaluate the default expression and assign it.
  5161. Emit(init, byteCodeGenerator, funcInfo, false);
  5162. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocationTmp, init->location);
  5163. funcInfo->ReleaseLoc(init);
  5164. // jmp to loadIter
  5165. byteCodeGenerator->Writer()->Br(loadIter);
  5166. // skipDefault:
  5167. byteCodeGenerator->Writer()->MarkLabel(skipDefault);
  5168. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocationTmp, valueLocation);
  5169. // loadIter:
  5170. // @@iterator
  5171. byteCodeGenerator->Writer()->MarkLabel(loadIter);
  5172. byteCodeGenerator->EndStatement(init);
  5173. if (elem->nop == knopObjectPattern)
  5174. {
  5175. EmitDestructuredObject(elem, valueLocationTmp, byteCodeGenerator, funcInfo);
  5176. }
  5177. else
  5178. {
  5179. // Recursively emit a destructured array using the current .next() as the RHS.
  5180. EmitDestructuredArray(elem, valueLocationTmp, byteCodeGenerator, funcInfo);
  5181. }
  5182. funcInfo->ReleaseTmpRegister(valueLocationTmp);
  5183. }
  5184. else
  5185. {
  5186. if (elem->nop == knopObjectPattern)
  5187. {
  5188. EmitDestructuredObject(elem, valueLocation, byteCodeGenerator, funcInfo);
  5189. }
  5190. else
  5191. {
  5192. // Recursively emit a destructured array using the current .next() as the RHS.
  5193. EmitDestructuredArray(elem, valueLocation, byteCodeGenerator, funcInfo);
  5194. }
  5195. }
  5196. }
  5197. else
  5198. {
  5199. EmitDestructuredValueOrInitializer(elem, valueLocation, init, byteCodeGenerator, funcInfo);
  5200. }
  5201. funcInfo->ReleaseTmpRegister(valueLocation);
  5202. funcInfo->ReleaseTmpRegister(itemLocation);
  5203. byteCodeGenerator->EndStatement(elem);
  5204. if (list->nop == knopList)
  5205. {
  5206. list = list->sxBin.pnode2;
  5207. }
  5208. else
  5209. {
  5210. break;
  5211. }
  5212. }
  5213. // If we saw a rest element, emit the rest array.
  5214. if (elem != nullptr && elem->nop == knopEllipsis)
  5215. {
  5216. EmitDestructuredRestArray(elem, iteratorLocation, byteCodeGenerator, funcInfo);
  5217. }
  5218. funcInfo->ReleaseTmpRegister(iteratorLocation);
  5219. byteCodeGenerator->EndStatement(lhs);
  5220. }
  5221. void EmitNameInvoke(Js::RegSlot lhsLocation,
  5222. Js::RegSlot objectLocation,
  5223. ParseNodePtr nameNode,
  5224. ByteCodeGenerator* byteCodeGenerator,
  5225. FuncInfo* funcInfo)
  5226. {
  5227. Assert(nameNode != nullptr);
  5228. if (nameNode->nop == knopComputedName)
  5229. {
  5230. ParseNodePtr pnode1 = nameNode->sxUni.pnode1;
  5231. Emit(pnode1, byteCodeGenerator, funcInfo, false/*isConstructorCall*/);
  5232. byteCodeGenerator->Writer()->Element(Js::OpCode::LdElemI_A, lhsLocation, objectLocation, pnode1->location);
  5233. funcInfo->ReleaseLoc(pnode1);
  5234. }
  5235. else
  5236. {
  5237. Assert(nameNode->nop == knopName || nameNode->nop == knopStr);
  5238. Symbol *sym = nameNode->sxPid.sym;
  5239. Js::PropertyId propertyId = sym ? sym->EnsurePosition(byteCodeGenerator) : nameNode->sxPid.pid->GetPropertyId();
  5240. uint cacheId = funcInfo->FindOrAddInlineCacheId(objectLocation, propertyId, false/*isLoadMethod*/, false/*isStore*/);
  5241. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, lhsLocation, objectLocation, cacheId);
  5242. }
  5243. }
  5244. void EmitDestructuredValueOrInitializer(ParseNodePtr lhsElementNode,
  5245. Js::RegSlot rhsLocation,
  5246. ParseNodePtr initializer,
  5247. ByteCodeGenerator *byteCodeGenerator,
  5248. FuncInfo *funcInfo)
  5249. {
  5250. // 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
  5251. Js::ByteCodeLabel useDefault = -1;
  5252. Js::ByteCodeLabel end = -1;
  5253. Js::RegSlot rhsLocationTmp = rhsLocation;
  5254. if (initializer != nullptr)
  5255. {
  5256. rhsLocationTmp = funcInfo->AcquireTmpRegister();
  5257. useDefault = byteCodeGenerator->Writer()->DefineLabel();
  5258. end = byteCodeGenerator->Writer()->DefineLabel();
  5259. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, useDefault, rhsLocation, funcInfo->undefinedConstantRegister);
  5260. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocationTmp, rhsLocation);
  5261. byteCodeGenerator->Writer()->Br(end);
  5262. byteCodeGenerator->Writer()->MarkLabel(useDefault);
  5263. Emit(initializer, byteCodeGenerator, funcInfo, false/*isConstructorCall*/);
  5264. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocationTmp, initializer->location);
  5265. funcInfo->ReleaseLoc(initializer);
  5266. byteCodeGenerator->Writer()->MarkLabel(end);
  5267. }
  5268. if (lhsElementNode->nop == knopArrayPattern)
  5269. {
  5270. EmitDestructuredArray(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5271. }
  5272. else if (lhsElementNode->nop == knopObjectPattern)
  5273. {
  5274. EmitDestructuredObject(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5275. }
  5276. else
  5277. {
  5278. EmitDestructuredElement(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5279. }
  5280. if (initializer != nullptr)
  5281. {
  5282. funcInfo->ReleaseTmpRegister(rhsLocationTmp);
  5283. }
  5284. }
  5285. void EmitDestructuredObjectMember(ParseNodePtr memberNode,
  5286. Js::RegSlot rhsLocation,
  5287. ByteCodeGenerator *byteCodeGenerator,
  5288. FuncInfo *funcInfo)
  5289. {
  5290. Assert(memberNode->nop == knopObjectPatternMember);
  5291. Js::RegSlot nameLocation = funcInfo->AcquireTmpRegister();
  5292. EmitNameInvoke(nameLocation, rhsLocation, memberNode->sxBin.pnode1, byteCodeGenerator, funcInfo);
  5293. // Imagine we are transforming
  5294. // {x:x1} = {} to x1 = {}.x (here x1 is the second node of the member but that is our lhsnode)
  5295. ParseNodePtr lhsElementNode = memberNode->sxBin.pnode2;
  5296. ParseNodePtr init = nullptr;
  5297. if (lhsElementNode->IsVarLetOrConst())
  5298. {
  5299. init = lhsElementNode->sxVar.pnodeInit;
  5300. }
  5301. else if (lhsElementNode->nop == knopAsg)
  5302. {
  5303. init = lhsElementNode->sxBin.pnode2;
  5304. lhsElementNode = lhsElementNode->sxBin.pnode1;
  5305. }
  5306. EmitDestructuredValueOrInitializer(lhsElementNode, nameLocation, init, byteCodeGenerator, funcInfo);
  5307. funcInfo->ReleaseTmpRegister(nameLocation);
  5308. }
  5309. void EmitDestructuredObject(ParseNode *lhs,
  5310. Js::RegSlot rhsLocation,
  5311. ByteCodeGenerator *byteCodeGenerator,
  5312. FuncInfo *funcInfo)
  5313. {
  5314. Assert(lhs->nop == knopObjectPattern);
  5315. ParseNodePtr pnode1 = lhs->sxUni.pnode1;
  5316. if (pnode1 != nullptr)
  5317. {
  5318. Assert(pnode1->nop == knopList || pnode1->nop == knopObjectPatternMember);
  5319. byteCodeGenerator->StartStatement(lhs);
  5320. ParseNodePtr current = pnode1;
  5321. while (current->nop == knopList)
  5322. {
  5323. ParseNodePtr memberNode = current->sxBin.pnode1;
  5324. EmitDestructuredObjectMember(memberNode, rhsLocation, byteCodeGenerator, funcInfo);
  5325. current = current->sxBin.pnode2;
  5326. }
  5327. EmitDestructuredObjectMember(current, rhsLocation, byteCodeGenerator, funcInfo);
  5328. byteCodeGenerator->EndStatement(lhs);
  5329. }
  5330. }
  5331. void EmitAssignment(
  5332. ParseNode *asgnNode,
  5333. ParseNode *lhs,
  5334. Js::RegSlot rhsLocation,
  5335. ByteCodeGenerator *byteCodeGenerator,
  5336. FuncInfo *funcInfo)
  5337. {
  5338. switch (lhs->nop)
  5339. {
  5340. // assignment to a local or global variable
  5341. case knopVarDecl:
  5342. case knopLetDecl:
  5343. case knopConstDecl:
  5344. {
  5345. Symbol *sym = lhs->sxVar.sym;
  5346. Assert(sym != nullptr);
  5347. byteCodeGenerator->EmitPropStore(rhsLocation, sym, nullptr, funcInfo, lhs->nop == knopLetDecl, lhs->nop == knopConstDecl);
  5348. break;
  5349. }
  5350. case knopName:
  5351. {
  5352. byteCodeGenerator->EmitPropStore(rhsLocation, lhs->sxPid.sym, lhs->sxPid.pid, funcInfo);
  5353. break;
  5354. }
  5355. // x.y =
  5356. case knopDot:
  5357. {
  5358. // PutValue(x, "y", rhs)
  5359. Js::PropertyId propertyId = lhs->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  5360. uint cacheId = funcInfo->FindOrAddInlineCacheId(lhs->sxBin.pnode1->location, propertyId, false, true);
  5361. if (lhs->sxBin.pnode1->nop == knopSuper)
  5362. {
  5363. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(Js::OpCode::StSuperFld, rhsLocation, lhs->sxBin.pnode1->location, funcInfo->thisPointerRegister, cacheId);
  5364. }
  5365. else
  5366. {
  5367. byteCodeGenerator->Writer()->PatchableProperty(
  5368. ByteCodeGenerator::GetStFldOpCode(funcInfo, false, false, false, false), rhsLocation, lhs->sxBin.pnode1->location, cacheId);
  5369. }
  5370. break;
  5371. }
  5372. case knopIndex:
  5373. {
  5374. byteCodeGenerator->Writer()->Element(
  5375. ByteCodeGenerator::GetStElemIOpCode(funcInfo),
  5376. rhsLocation, lhs->sxBin.pnode1->location, lhs->sxBin.pnode2->location);
  5377. break;
  5378. }
  5379. case knopObjectPattern:
  5380. {
  5381. Assert(byteCodeGenerator->IsES6DestructuringEnabled());
  5382. // Copy the rhs value to be the result of the assignment if needed.
  5383. if (asgnNode != nullptr)
  5384. {
  5385. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  5386. }
  5387. return EmitDestructuredObject(lhs, rhsLocation, byteCodeGenerator, funcInfo);
  5388. }
  5389. case knopArrayPattern:
  5390. {
  5391. Assert(byteCodeGenerator->IsES6DestructuringEnabled());
  5392. // Copy the rhs value to be the result of the assignment if needed.
  5393. if (asgnNode != nullptr)
  5394. {
  5395. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  5396. }
  5397. return EmitDestructuredArray(lhs, rhsLocation, byteCodeGenerator, funcInfo);
  5398. }
  5399. case knopArray:
  5400. case knopObject:
  5401. // Assignment to array/object can get through to byte code gen when the parser fails to convert destructuring
  5402. // assignment to pattern (because of structural mismatch between LHS & RHS?). Revisit when we nail
  5403. // down early vs. runtime errors for destructuring.
  5404. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  5405. break;
  5406. default:
  5407. Assert(!PHASE_ON1(Js::EarlyReferenceErrorsPhase));
  5408. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  5409. break;
  5410. }
  5411. if (asgnNode != nullptr)
  5412. {
  5413. // We leave it up to the caller to pass this node only if the assignment expression is used.
  5414. if (asgnNode->location != rhsLocation)
  5415. {
  5416. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  5417. }
  5418. }
  5419. }
  5420. void EmitLoad(
  5421. ParseNode *lhs,
  5422. ByteCodeGenerator *byteCodeGenerator,
  5423. FuncInfo *funcInfo)
  5424. {
  5425. // Emit the instructions to load the value into the LHS location. Do not assign/free any temps
  5426. // in the process.
  5427. // We usually get here as part of an op-equiv expression: x.y += z;
  5428. // In such a case, x has to be emitted first, then the value of x.y loaded (by this function), then z emitted.
  5429. switch (lhs->nop)
  5430. {
  5431. // load of a local or global variable
  5432. case knopName:
  5433. {
  5434. funcInfo->AcquireLoc(lhs);
  5435. byteCodeGenerator->EmitPropLoad(lhs->location, lhs->sxPid.sym, lhs->sxPid.pid, funcInfo);
  5436. break;
  5437. }
  5438. // = x.y
  5439. case knopDot:
  5440. {
  5441. // get field id for "y"
  5442. Js::PropertyId propertyId = lhs->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  5443. funcInfo->AcquireLoc(lhs);
  5444. EmitReference(lhs, byteCodeGenerator, funcInfo);
  5445. uint cacheId = funcInfo->FindOrAddInlineCacheId(lhs->sxBin.pnode1->location, propertyId, false, false);
  5446. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, lhs->location, lhs->sxBin.pnode1->location, cacheId);
  5447. break;
  5448. }
  5449. case knopIndex:
  5450. funcInfo->AcquireLoc(lhs);
  5451. EmitReference(lhs, byteCodeGenerator, funcInfo);
  5452. byteCodeGenerator->Writer()->Element(
  5453. Js::OpCode::LdElemI_A, lhs->location, lhs->sxBin.pnode1->location, lhs->sxBin.pnode2->location);
  5454. break;
  5455. // f(x) +=
  5456. case knopCall:
  5457. funcInfo->AcquireLoc(lhs);
  5458. EmitReference(lhs, byteCodeGenerator, funcInfo);
  5459. EmitCall(lhs, /*rhs=*/ Js::Constants::NoRegister, byteCodeGenerator, funcInfo, /*fReturnValue=*/ false, /*fAssignRegs=*/ false, /*fHasNewTarget=*/ false);
  5460. break;
  5461. default:
  5462. funcInfo->AcquireLoc(lhs);
  5463. Emit(lhs, byteCodeGenerator, funcInfo, false);
  5464. break;
  5465. }
  5466. }
  5467. void EmitList(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  5468. {
  5469. if (pnode != nullptr)
  5470. {
  5471. while (pnode->nop == knopList)
  5472. {
  5473. byteCodeGenerator->EmitTopLevelStatement(pnode->sxBin.pnode1, funcInfo, false);
  5474. pnode = pnode->sxBin.pnode2;
  5475. }
  5476. byteCodeGenerator->EmitTopLevelStatement(pnode, funcInfo, false);
  5477. }
  5478. }
  5479. void EmitSpreadArgToListBytecodeInstr(ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, Js::RegSlot argLoc, Js::ProfileId callSiteId, Js::ArgSlot &argIndex)
  5480. {
  5481. Js::RegSlot regVal = funcInfo->AcquireTmpRegister();
  5482. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, argLoc);
  5483. byteCodeGenerator->Writer()->ArgOut<true>(++argIndex, regVal, callSiteId);
  5484. funcInfo->ReleaseTmpRegister(regVal);
  5485. }
  5486. size_t EmitArgs(
  5487. ParseNode *pnode,
  5488. BOOL fAssignRegs,
  5489. ByteCodeGenerator *byteCodeGenerator,
  5490. FuncInfo *funcInfo,
  5491. Js::ProfileId callSiteId,
  5492. Js::AuxArray<uint32> *spreadIndices = nullptr
  5493. )
  5494. {
  5495. Js::ArgSlot argIndex = 0;
  5496. Js::ArgSlot spreadIndex = 0;
  5497. if (pnode != nullptr)
  5498. {
  5499. while (pnode->nop == knopList)
  5500. {
  5501. // If this is a put, the arguments have already been evaluated (see EmitReference).
  5502. // We just need to emit the ArgOut instructions.
  5503. if (fAssignRegs)
  5504. {
  5505. Emit(pnode->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  5506. }
  5507. if (pnode->sxBin.pnode1->nop == knopEllipsis)
  5508. {
  5509. Assert(spreadIndices != nullptr);
  5510. spreadIndices->elements[spreadIndex++] = argIndex + 1; // account for 'this'
  5511. EmitSpreadArgToListBytecodeInstr(byteCodeGenerator, funcInfo, pnode->sxBin.pnode1->location, callSiteId, argIndex);
  5512. }
  5513. else
  5514. {
  5515. byteCodeGenerator->Writer()->ArgOut<true>(++argIndex, pnode->sxBin.pnode1->location, callSiteId);
  5516. }
  5517. if (fAssignRegs)
  5518. {
  5519. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  5520. }
  5521. pnode = pnode->sxBin.pnode2;
  5522. }
  5523. // If this is a put, the call target has already been evaluated (see EmitReference).
  5524. if (fAssignRegs)
  5525. {
  5526. Emit(pnode, byteCodeGenerator, funcInfo, false);
  5527. }
  5528. if (pnode->nop == knopEllipsis)
  5529. {
  5530. Assert(spreadIndices != nullptr);
  5531. spreadIndices->elements[spreadIndex++] = argIndex + 1; // account for 'this'
  5532. EmitSpreadArgToListBytecodeInstr(byteCodeGenerator, funcInfo, pnode->location, callSiteId, argIndex);
  5533. }
  5534. else
  5535. {
  5536. byteCodeGenerator->Writer()->ArgOut<true>(++argIndex, pnode->location, callSiteId);
  5537. }
  5538. if (fAssignRegs)
  5539. {
  5540. funcInfo->ReleaseLoc(pnode);
  5541. }
  5542. }
  5543. return argIndex;
  5544. }
  5545. void EmitArgListStart(
  5546. Js::RegSlot thisLocation,
  5547. ByteCodeGenerator *byteCodeGenerator,
  5548. FuncInfo *funcInfo,
  5549. Js::ProfileId callSiteId)
  5550. {
  5551. if (thisLocation != Js::Constants::NoRegister)
  5552. {
  5553. // Emit the "this" object.
  5554. byteCodeGenerator->Writer()->ArgOut<true>(0, thisLocation, callSiteId);
  5555. }
  5556. }
  5557. Js::ArgSlot EmitArgListEnd(
  5558. ParseNode *pnode,
  5559. Js::RegSlot rhsLocation,
  5560. Js::RegSlot thisLocation,
  5561. Js::RegSlot evalLocation,
  5562. Js::RegSlot newTargetLocation,
  5563. ByteCodeGenerator *byteCodeGenerator,
  5564. FuncInfo *funcInfo,
  5565. size_t argIndex,
  5566. Js::ProfileId callSiteId)
  5567. {
  5568. BOOL fEvalInModule = false;
  5569. BOOL fIsPut = (rhsLocation != Js::Constants::NoRegister);
  5570. BOOL fIsEval = (evalLocation != Js::Constants::NoRegister);
  5571. BOOL fHasNewTarget = (newTargetLocation != Js::Constants::NoRegister);
  5572. Js::ArgSlot argSlotIndex = (Js::ArgSlot) argIndex;
  5573. static const Js::ArgSlot maxExtraArgSlot = 4; // max(extraEvalArg, extraArg), where extraEvalArg==2 (moduleRoot,env), extraArg==4 (this, eval, evalInModule, newTarget)
  5574. // check for integer overflow with margin for increments below to calculate argument count
  5575. if ((size_t)argSlotIndex != argIndex || argSlotIndex + maxExtraArgSlot < argSlotIndex)
  5576. {
  5577. Js::Throw::OutOfMemory();
  5578. }
  5579. Js::ArgSlot evalIndex;
  5580. if (fIsPut)
  5581. {
  5582. // Emit the assigned value as an additional operand. Note that the value has already been evaluated.
  5583. // We just need to emit the ArgOut instruction.
  5584. argSlotIndex++;
  5585. byteCodeGenerator->Writer()->ArgOut<true>(argSlotIndex, rhsLocation, callSiteId);
  5586. }
  5587. if (fIsEval && argSlotIndex > 0)
  5588. {
  5589. Assert(!fHasNewTarget);
  5590. // Pass the frame display as an extra argument to "eval".
  5591. // Do this only if eval is called with some args
  5592. Js::RegSlot evalEnv;
  5593. if (funcInfo->IsGlobalFunction() && !(funcInfo->GetIsStrictMode() && byteCodeGenerator->GetFlags() & fscrEval))
  5594. {
  5595. // Use current environment as the environment for the function being called when:
  5596. // - this is the root global function (not an eval's global function)
  5597. // - this is an eval's global function that is not in strict mode (see else block)
  5598. evalEnv = funcInfo->GetEnvRegister();
  5599. }
  5600. else
  5601. {
  5602. // Use the frame display as the environment for the function being called when:
  5603. // - this is not a global function and thus it will have its own scope
  5604. // - this is an eval's global function that is in strict mode, since in strict mode the eval's global function
  5605. // has its own scope
  5606. evalEnv = funcInfo->frameDisplayRegister;
  5607. }
  5608. evalEnv = byteCodeGenerator->PrependLocalScopes(evalEnv, evalLocation, funcInfo);
  5609. Js::ModuleID moduleID = byteCodeGenerator->GetModuleID();
  5610. if (moduleID != kmodGlobal)
  5611. {
  5612. // Pass both the module root and the environment.
  5613. fEvalInModule = true;
  5614. byteCodeGenerator->Writer()->ArgOut<true>(argSlotIndex + 1, ByteCodeGenerator::RootObjectRegister, callSiteId);
  5615. evalIndex = argSlotIndex + 2;
  5616. }
  5617. else
  5618. {
  5619. // Just pass the environment.
  5620. evalIndex = argSlotIndex + 1;
  5621. }
  5622. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  5623. {
  5624. byteCodeGenerator->Writer()->ArgOutEnv(evalIndex);
  5625. }
  5626. else
  5627. {
  5628. byteCodeGenerator->Writer()->ArgOut<false>(evalIndex, evalEnv, callSiteId);
  5629. }
  5630. }
  5631. if (fHasNewTarget)
  5632. {
  5633. Assert(!fIsEval);
  5634. byteCodeGenerator->Writer()->ArgOut<true>(argSlotIndex + 1, newTargetLocation, callSiteId);
  5635. }
  5636. Js::ArgSlot argIntCount = argSlotIndex + 1 + (Js::ArgSlot)fIsEval + (Js::ArgSlot)fEvalInModule + (Js::ArgSlot)fHasNewTarget;
  5637. // eval and no args passed, return 1 as argument count
  5638. if (fIsEval && pnode == nullptr)
  5639. {
  5640. return 1;
  5641. }
  5642. return argIntCount;
  5643. }
  5644. Js::ArgSlot EmitArgList(
  5645. ParseNode *pnode,
  5646. Js::RegSlot rhsLocation,
  5647. Js::RegSlot thisLocation,
  5648. Js::RegSlot newTargetLocation,
  5649. BOOL fIsEval,
  5650. BOOL fAssignRegs,
  5651. ByteCodeGenerator *byteCodeGenerator,
  5652. FuncInfo *funcInfo,
  5653. Js::ProfileId callSiteId,
  5654. uint16 spreadArgCount = 0,
  5655. Js::AuxArray<uint32> **spreadIndices = nullptr)
  5656. {
  5657. // This function emits the arguments for a call.
  5658. // ArgOut's with uses immediately following defs.
  5659. EmitArgListStart(thisLocation, byteCodeGenerator, funcInfo, callSiteId);
  5660. Js::RegSlot evalLocation = Js::Constants::NoRegister;
  5661. //
  5662. // If Emitting arguments for eval and assigning registers, get a tmpLocation for eval.
  5663. // This would be used while generating frameDisplay in EmitArgListEnd.
  5664. //
  5665. if (fIsEval)
  5666. {
  5667. evalLocation = funcInfo->AcquireTmpRegister();
  5668. }
  5669. if (spreadArgCount > 0)
  5670. {
  5671. const size_t extraAlloc = spreadArgCount * sizeof(uint32);
  5672. Assert(spreadIndices != nullptr);
  5673. *spreadIndices = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<uint32>, spreadArgCount);
  5674. }
  5675. size_t argIndex = EmitArgs(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, spreadIndices == nullptr ? nullptr : *spreadIndices);
  5676. Js::ArgSlot argumentsCount = EmitArgListEnd(pnode, rhsLocation, thisLocation, evalLocation, newTargetLocation, byteCodeGenerator, funcInfo, argIndex, callSiteId);
  5677. if (fIsEval)
  5678. {
  5679. funcInfo->ReleaseTmpRegister(evalLocation);
  5680. }
  5681. return argumentsCount;
  5682. }
  5683. void EmitConstantArgsToVarArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) Js::Var *vars, ParseNode *args, uint argCount)
  5684. {
  5685. uint index = 0;
  5686. while (args->nop == knopList && index < argCount)
  5687. {
  5688. if (args->sxBin.pnode1->nop == knopInt)
  5689. {
  5690. int value = args->sxBin.pnode1->sxInt.lw;
  5691. vars[index++] = Js::TaggedInt::ToVarUnchecked(value);
  5692. }
  5693. else if (args->sxBin.pnode1->nop == knopFlt)
  5694. {
  5695. Js::Var number = Js::JavascriptNumber::New(args->sxBin.pnode1->sxFlt.dbl, byteCodeGenerator->GetScriptContext());
  5696. #if ! FLOATVAR
  5697. byteCodeGenerator->GetScriptContext()->BindReference(number);
  5698. #endif
  5699. vars[index++] = number;
  5700. }
  5701. else
  5702. {
  5703. AnalysisAssert(false);
  5704. }
  5705. args = args->sxBin.pnode2;
  5706. }
  5707. if (index == argCount)
  5708. {
  5709. Assert(false);
  5710. Js::Throw::InternalError();
  5711. return;
  5712. }
  5713. if (args->nop == knopInt)
  5714. {
  5715. int value = args->sxInt.lw;
  5716. vars[index++] = Js::TaggedInt::ToVarUnchecked(value);
  5717. }
  5718. else if (args->nop == knopFlt)
  5719. {
  5720. Js::Var number = Js::JavascriptNumber::New(args->sxFlt.dbl, byteCodeGenerator->GetScriptContext());
  5721. #if ! FLOATVAR
  5722. byteCodeGenerator->GetScriptContext()->BindReference(number);
  5723. #endif
  5724. vars[index++] = number;
  5725. }
  5726. else
  5727. {
  5728. AnalysisAssert(false);
  5729. }
  5730. }
  5731. void EmitConstantArgsToIntArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) int32 *vars, ParseNode *args, uint argCount)
  5732. {
  5733. uint index = 0;
  5734. while (args->nop == knopList && index < argCount)
  5735. {
  5736. Assert(args->sxBin.pnode1->nop == knopInt);
  5737. vars[index++] = args->sxBin.pnode1->sxInt.lw;
  5738. args = args->sxBin.pnode2;
  5739. }
  5740. if (index == argCount)
  5741. {
  5742. Assert(false);
  5743. Js::Throw::InternalError();
  5744. return;
  5745. }
  5746. Assert(args->nop == knopInt);
  5747. vars[index++] = args->sxInt.lw;
  5748. Assert(index == argCount);
  5749. }
  5750. void EmitConstantArgsToFltArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) double *vars, ParseNode *args, uint argCount)
  5751. {
  5752. uint index = 0;
  5753. while (args->nop == knopList && index < argCount)
  5754. {
  5755. OpCode nop = args->sxBin.pnode1->nop;
  5756. if (nop == knopInt)
  5757. {
  5758. vars[index++] = (double)args->sxBin.pnode1->sxInt.lw;
  5759. }
  5760. else
  5761. {
  5762. Assert(nop == knopFlt);
  5763. vars[index++] = args->sxBin.pnode1->sxFlt.dbl;
  5764. }
  5765. args = args->sxBin.pnode2;
  5766. }
  5767. if (index == argCount)
  5768. {
  5769. Assert(false);
  5770. Js::Throw::InternalError();
  5771. return;
  5772. }
  5773. if (args->nop == knopInt)
  5774. {
  5775. vars[index++] = (double)args->sxInt.lw;
  5776. }
  5777. else
  5778. {
  5779. Assert(args->nop == knopFlt);
  5780. vars[index++] = args->sxFlt.dbl;
  5781. }
  5782. Assert(index == argCount);
  5783. }
  5784. //
  5785. // Called when we have new Ctr(constant, constant...)
  5786. //
  5787. Js::ArgSlot EmitNewObjectOfConstants(
  5788. ParseNode *pnode,
  5789. ByteCodeGenerator *byteCodeGenerator,
  5790. FuncInfo *funcInfo,
  5791. unsigned int argCount)
  5792. {
  5793. EmitArgListStart(Js::Constants::NoRegister, byteCodeGenerator, funcInfo, Js::Constants::NoProfileId);
  5794. // Create the vars array
  5795. Js::VarArrayVarCount *vars = AnewPlus(byteCodeGenerator->GetAllocator(), (argCount - 1) * sizeof(Js::Var), Js::VarArrayVarCount, Js::TaggedInt::ToVarUnchecked(argCount - 1));
  5796. // Emit all constants to the vars array
  5797. EmitConstantArgsToVarArray(byteCodeGenerator, vars->elements, pnode->sxCall.pnodeArgs, argCount - 1);
  5798. // Finish the arg list
  5799. Js::ArgSlot actualArgCount = EmitArgListEnd(
  5800. pnode->sxCall.pnodeArgs,
  5801. Js::Constants::NoRegister,
  5802. Js::Constants::NoRegister,
  5803. Js::Constants::NoRegister,
  5804. Js::Constants::NoRegister,
  5805. byteCodeGenerator,
  5806. funcInfo,
  5807. argCount - 1,
  5808. Js::Constants::NoProfileId);
  5809. // Make sure the cacheId to regSlot map in the ByteCodeWriter is left in a consistent state after writing NewScObject_A
  5810. byteCodeGenerator->Writer()->RemoveEntryForRegSlotFromCacheIdMap(pnode->sxCall.pnodeTarget->location);
  5811. // Generate the opcode with vars
  5812. byteCodeGenerator->Writer()->AuxiliaryContext(
  5813. Js::OpCode::NewScObject_A,
  5814. funcInfo->AcquireLoc(pnode),
  5815. vars,
  5816. sizeof(Js::VarArray) + (argCount - 1) * sizeof(Js::Var),
  5817. pnode->sxCall.pnodeTarget->location);
  5818. AdeletePlus(byteCodeGenerator->GetAllocator(), (argCount - 1) * sizeof(Js::VarArrayVarCount), vars);
  5819. return actualArgCount;
  5820. }
  5821. void EmitMethodFld(bool isRoot, bool isScoped, Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, bool registerCacheIdForCall = true)
  5822. {
  5823. Js::OpCode opcode;
  5824. if (!isRoot)
  5825. {
  5826. if (callObjLocation == funcInfo->frameObjRegister)
  5827. {
  5828. opcode = Js::OpCode::LdLocalMethodFld;
  5829. }
  5830. else
  5831. {
  5832. opcode = Js::OpCode::LdMethodFld;
  5833. }
  5834. }
  5835. else if (isScoped)
  5836. {
  5837. opcode = Js::OpCode::ScopedLdMethodFld;
  5838. }
  5839. else
  5840. {
  5841. opcode = Js::OpCode::LdRootMethodFld;
  5842. }
  5843. if (isScoped || !isRoot)
  5844. {
  5845. Assert(isScoped || !isRoot || callObjLocation == ByteCodeGenerator::RootObjectRegister);
  5846. uint cacheId = funcInfo->FindOrAddInlineCacheId(callObjLocation, propertyId, true, false);
  5847. if (callObjLocation == funcInfo->frameObjRegister)
  5848. {
  5849. byteCodeGenerator->Writer()->ElementP(opcode, location, cacheId, false /*isCtor*/, registerCacheIdForCall);
  5850. }
  5851. else
  5852. {
  5853. byteCodeGenerator->Writer()->PatchableProperty(opcode, location, callObjLocation, cacheId, false /*isCtor*/, registerCacheIdForCall);
  5854. }
  5855. }
  5856. else
  5857. {
  5858. uint cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, true, false);
  5859. byteCodeGenerator->Writer()->PatchableRootProperty(opcode, location, cacheId, true, false, registerCacheIdForCall);
  5860. }
  5861. }
  5862. void EmitMethodFld(ParseNode *pnode, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, bool registerCacheIdForCall = true)
  5863. {
  5864. // Load a call target of the form x.y(). (Call target may be a plain knopName if we're getting it from
  5865. // the global object, etc.)
  5866. bool isRoot = pnode->nop == knopName && (pnode->sxPid.sym == nullptr || pnode->sxPid.sym->GetIsGlobal());
  5867. bool isScoped = (byteCodeGenerator->GetFlags() & fscrEval) != 0 ||
  5868. (isRoot && callObjLocation != ByteCodeGenerator::RootObjectRegister);
  5869. EmitMethodFld(isRoot, isScoped, pnode->location, callObjLocation, propertyId, byteCodeGenerator, funcInfo, registerCacheIdForCall);
  5870. }
  5871. // lhs.apply(this, arguments);
  5872. void EmitApplyCall(ParseNode* pnode, Js::RegSlot rhsLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue, BOOL fAssignRegs)
  5873. {
  5874. ParseNode* applyNode = pnode->sxCall.pnodeTarget;
  5875. ParseNode* thisNode = pnode->sxCall.pnodeArgs->sxBin.pnode1;
  5876. Assert(applyNode->nop == knopDot);
  5877. ParseNode* funcNode = applyNode->sxBin.pnode1;
  5878. Js::ByteCodeLabel slowPath = byteCodeGenerator->Writer()->DefineLabel();
  5879. Js::ByteCodeLabel afterSlowPath = byteCodeGenerator->Writer()->DefineLabel();
  5880. Js::ByteCodeLabel argsAlreadyCreated = byteCodeGenerator->Writer()->DefineLabel();
  5881. Assert(applyNode->nop == knopDot);
  5882. Emit(funcNode, byteCodeGenerator, funcInfo, false);
  5883. funcInfo->AcquireLoc(applyNode);
  5884. Js::PropertyId propertyId = applyNode->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  5885. // As we won't be emitting a call instruction for apply, no need to register the cacheId for apply
  5886. // load to be associated with the call. This is also required, as in the absence of a corresponding
  5887. // call for apply, we won't remove the entry for "apply" cacheId from
  5888. // ByteCodeWriter::callRegToLdFldCacheIndexMap, which is contrary to our assumption that we would
  5889. // have removed an entry from a map upon seeing its corresponding call.
  5890. EmitMethodFld(applyNode, funcNode->location, propertyId, byteCodeGenerator, funcInfo, false /*registerCacheIdForCall*/);
  5891. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  5892. Assert(argSym && argSym->GetIsArguments());
  5893. Js::RegSlot argumentsLoc = argSym->GetLocation();
  5894. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdArgumentsFromFrame, argumentsLoc);
  5895. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrNotNull_A, argsAlreadyCreated, argumentsLoc);
  5896. // If apply is overridden, bail to slow path.
  5897. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFncNeqApply, slowPath, applyNode->location);
  5898. // Note: acquire and release a temp register for this stack arg pointer instead of trying to stash it
  5899. // in funcInfo->stackArgReg. Otherwise, we'll needlessly load and store it in jitted loop bodies and
  5900. // may crash if we try to unbox it on the store.
  5901. Js::RegSlot stackArgReg = funcInfo->AcquireTmpRegister();
  5902. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdStackArgPtr, stackArgReg);
  5903. Js::RegSlot argCountLocation = funcInfo->AcquireTmpRegister();
  5904. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdArgCnt, argCountLocation);
  5905. byteCodeGenerator->Writer()->Reg5(Js::OpCode::ApplyArgs, funcNode->location, funcNode->location, thisNode->location, stackArgReg, argCountLocation);
  5906. funcInfo->ReleaseTmpRegister(argCountLocation);
  5907. funcInfo->ReleaseTmpRegister(stackArgReg);
  5908. funcInfo->ReleaseLoc(applyNode);
  5909. funcInfo->ReleaseLoc(funcNode);
  5910. // Clear these nodes as they are going to be used to re-generate the slow path.
  5911. VisitClearTmpRegs(applyNode, byteCodeGenerator, funcInfo);
  5912. VisitClearTmpRegs(funcNode, byteCodeGenerator, funcInfo);
  5913. byteCodeGenerator->Writer()->Br(afterSlowPath);
  5914. // slow path
  5915. byteCodeGenerator->Writer()->MarkLabel(slowPath);
  5916. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  5917. {
  5918. byteCodeGenerator->EmitScopeObjectInit(funcInfo);
  5919. }
  5920. byteCodeGenerator->LoadHeapArguments(funcInfo);
  5921. byteCodeGenerator->Writer()->MarkLabel(argsAlreadyCreated);
  5922. EmitCall(pnode, rhsLocation, byteCodeGenerator, funcInfo, fReturnValue, fAssignRegs,/*fHasNewTarget*/false);
  5923. byteCodeGenerator->Writer()->MarkLabel(afterSlowPath);
  5924. }
  5925. void EmitMethodElem(ParseNode *pnode, Js::RegSlot callObjLocation, Js::RegSlot indexLocation, ByteCodeGenerator *byteCodeGenerator)
  5926. {
  5927. // Load a call target of the form x[y]().
  5928. byteCodeGenerator->Writer()->Element(Js::OpCode::LdMethodElem, pnode->location, callObjLocation, indexLocation);
  5929. }
  5930. void EmitCallTargetNoEvalComponents(
  5931. ParseNode *pnodeTarget,
  5932. BOOL fSideEffectArgs,
  5933. Js::RegSlot *thisLocation,
  5934. Js::RegSlot *callObjLocation,
  5935. ByteCodeGenerator *byteCodeGenerator,
  5936. FuncInfo *funcInfo)
  5937. {
  5938. // We first get a reference to the call target, then evaluate the arguments, then
  5939. // evaluate the call target.
  5940. // - emit reference to target
  5941. // - copy instance to scratch reg if necessary.
  5942. // - assign this
  5943. // - assign instance for dynamic/global name
  5944. // - emit args
  5945. // - do call (CallFld/Elem/I)
  5946. switch (pnodeTarget->nop)
  5947. {
  5948. case knopDot:
  5949. *thisLocation = pnodeTarget->sxBin.pnode1->location;
  5950. *callObjLocation = pnodeTarget->sxBin.pnode1->location;
  5951. break;
  5952. case knopIndex:
  5953. *thisLocation = pnodeTarget->sxBin.pnode1->location;
  5954. *callObjLocation = pnodeTarget->sxBin.pnode1->location;
  5955. break;
  5956. case knopName:
  5957. // If the call target is a name, do some extra work to get its instance and the "this" pointer.
  5958. byteCodeGenerator->EmitLoadInstance(pnodeTarget->sxPid.sym, pnodeTarget->sxPid.pid, thisLocation, callObjLocation, funcInfo);
  5959. if (*thisLocation == Js::Constants::NoRegister)
  5960. {
  5961. *thisLocation = funcInfo->undefinedConstantRegister;
  5962. }
  5963. if (byteCodeGenerator->GetScriptContext()->GetConfig()->IsLetAndConstEnabled())
  5964. {
  5965. EmitUseBeforeDeclaration(pnodeTarget, byteCodeGenerator, funcInfo);
  5966. }
  5967. break;
  5968. default:
  5969. *thisLocation = funcInfo->undefinedConstantRegister;
  5970. break;
  5971. }
  5972. }
  5973. void EmitSuperMethodBegin(
  5974. ParseNode *pnodeTarget,
  5975. ByteCodeGenerator *byteCodeGenerator,
  5976. FuncInfo *funcInfo)
  5977. {
  5978. FuncInfo *parentFuncInfo = funcInfo;
  5979. if (parentFuncInfo->IsLambda())
  5980. {
  5981. parentFuncInfo = byteCodeGenerator->FindEnclosingNonLambda();
  5982. }
  5983. if (pnodeTarget->sxBin.pnode1->nop == knopSuper && parentFuncInfo->IsClassConstructor() && !parentFuncInfo->IsBaseClassConstructor())
  5984. {
  5985. byteCodeGenerator->EmitScopeSlotLoadThis(funcInfo, funcInfo->thisPointerRegister, /*chkUndecl*/ true);
  5986. }
  5987. }
  5988. void EmitCallTarget(
  5989. ParseNode *pnodeTarget,
  5990. BOOL fSideEffectArgs,
  5991. Js::RegSlot *thisLocation,
  5992. Js::RegSlot *callObjLocation,
  5993. ByteCodeGenerator *byteCodeGenerator,
  5994. FuncInfo *funcInfo)
  5995. {
  5996. // - emit target
  5997. // - assign this
  5998. // - emit args
  5999. // - do call
  6000. // The call target is fully evaluated before the argument list. Note that we're not handling
  6001. // put-call cases here currently, as such cases only apply to host objects
  6002. // and are very unlikely to behave differently depending on the order of evaluation.
  6003. switch (pnodeTarget->nop)
  6004. {
  6005. case knopDot:
  6006. {
  6007. funcInfo->AcquireLoc(pnodeTarget);
  6008. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6009. // them from side-effects.
  6010. if (fSideEffectArgs)
  6011. {
  6012. // Though we're done with target evaluation after this point, still protect opnd1 from
  6013. // arg side-effects as it's the "this" pointer.
  6014. SaveOpndValue(pnodeTarget->sxBin.pnode1, funcInfo);
  6015. }
  6016. if ((pnodeTarget->sxBin.pnode2->nop == knopName) && ((pnodeTarget->sxBin.pnode2->sxPid.PropertyIdFromNameNode() == Js::PropertyIds::apply) || (pnodeTarget->sxBin.pnode2->sxPid.PropertyIdFromNameNode() == Js::PropertyIds::call)))
  6017. {
  6018. pnodeTarget->sxBin.pnode1->SetIsCallApplyTargetLoad();
  6019. }
  6020. Emit(pnodeTarget->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  6021. Js::PropertyId propertyId = pnodeTarget->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  6022. Js::RegSlot callObjLocation = pnodeTarget->sxBin.pnode1->location;
  6023. Js::RegSlot protoLocation = callObjLocation;
  6024. EmitSuperMethodBegin(pnodeTarget, byteCodeGenerator, funcInfo);
  6025. EmitMethodFld(pnodeTarget, protoLocation, propertyId, byteCodeGenerator, funcInfo);
  6026. // Function calls on the 'super' object should maintain current 'this' pointer
  6027. *thisLocation = (pnodeTarget->sxBin.pnode1->nop == knopSuper) ? funcInfo->thisPointerRegister : pnodeTarget->sxBin.pnode1->location;
  6028. break;
  6029. }
  6030. case knopIndex:
  6031. {
  6032. funcInfo->AcquireLoc(pnodeTarget);
  6033. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6034. // them from side-effects.
  6035. if (fSideEffectArgs || !(ParseNode::Grfnop(pnodeTarget->sxBin.pnode2->nop) & fnopLeaf))
  6036. {
  6037. // Though we're done with target evaluation after this point, still protect opnd1 from
  6038. // arg or opnd2 side-effects as it's the "this" pointer.
  6039. SaveOpndValue(pnodeTarget->sxBin.pnode1, funcInfo);
  6040. }
  6041. Emit(pnodeTarget->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  6042. Emit(pnodeTarget->sxBin.pnode2, byteCodeGenerator, funcInfo, false);
  6043. Js::RegSlot indexLocation = pnodeTarget->sxBin.pnode2->location;
  6044. Js::RegSlot callObjLocation = pnodeTarget->sxBin.pnode1->location;
  6045. Js::RegSlot protoLocation = callObjLocation;
  6046. EmitSuperMethodBegin(pnodeTarget, byteCodeGenerator, funcInfo);
  6047. EmitMethodElem(pnodeTarget, protoLocation, indexLocation, byteCodeGenerator);
  6048. funcInfo->ReleaseLoc(pnodeTarget->sxBin.pnode2); // don't release indexLocation until after we use it.
  6049. // Function calls on the 'super' object should maintain current 'this' pointer
  6050. *thisLocation = (pnodeTarget->sxBin.pnode1->nop == knopSuper) ? funcInfo->thisPointerRegister : pnodeTarget->sxBin.pnode1->location;
  6051. break;
  6052. }
  6053. case knopClassDecl:
  6054. {
  6055. Emit(pnodeTarget, byteCodeGenerator, funcInfo, false);
  6056. // We won't always have an assigned this register (e.g. class expression calls.) We need undefined in this case.
  6057. *thisLocation = funcInfo->thisPointerRegister == Js::Constants::NoRegister ? funcInfo->undefinedConstantRegister : funcInfo->thisPointerRegister;
  6058. break;
  6059. }
  6060. case knopSuper:
  6061. {
  6062. Emit(pnodeTarget, byteCodeGenerator, funcInfo, false, /*isConstructorCall*/ true); // reuse isConstructorCall ("new super()" is illegal)
  6063. // Super calls should always use the new.target register unless we don't have one.
  6064. // That could happen if we have an eval('super()') outside of a class constructor.
  6065. if (funcInfo->newTargetRegister != Js::Constants::NoRegister)
  6066. {
  6067. *thisLocation = funcInfo->newTargetRegister;
  6068. }
  6069. else
  6070. {
  6071. *thisLocation = funcInfo->thisPointerRegister;
  6072. }
  6073. break;
  6074. }
  6075. case knopName:
  6076. {
  6077. funcInfo->AcquireLoc(pnodeTarget);
  6078. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6079. // them from side-effects.
  6080. if (fSideEffectArgs)
  6081. {
  6082. SaveOpndValue(pnodeTarget, funcInfo);
  6083. }
  6084. byteCodeGenerator->EmitLoadInstance(pnodeTarget->sxPid.sym, pnodeTarget->sxPid.pid, thisLocation, callObjLocation, funcInfo);
  6085. if (*callObjLocation != Js::Constants::NoRegister)
  6086. {
  6087. // Load the call target as a property of the instance.
  6088. Js::PropertyId propertyId = pnodeTarget->sxPid.PropertyIdFromNameNode();
  6089. EmitMethodFld(pnodeTarget, *callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6090. break;
  6091. }
  6092. // FALL THROUGH to evaluate call target.
  6093. }
  6094. default:
  6095. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6096. // them from side-effects.
  6097. Emit(pnodeTarget, byteCodeGenerator, funcInfo, false);
  6098. *thisLocation = funcInfo->undefinedConstantRegister;
  6099. break;
  6100. }
  6101. // "This" pointer should have been assigned by the above.
  6102. Assert(*thisLocation != Js::Constants::NoRegister);
  6103. }
  6104. void EmitCallI(
  6105. ParseNode *pnode,
  6106. BOOL fEvaluateComponents,
  6107. BOOL fIsPut,
  6108. BOOL fIsEval,
  6109. BOOL fHasNewTarget,
  6110. uint32 actualArgCount,
  6111. ByteCodeGenerator *byteCodeGenerator,
  6112. FuncInfo *funcInfo,
  6113. Js::ProfileId callSiteId,
  6114. Js::AuxArray<uint32> *spreadIndices = nullptr)
  6115. {
  6116. // Emit a call where the target is in a register, because it's either a local name or an expression we've
  6117. // already evaluated.
  6118. ParseNode *pnodeTarget = pnode->sxBin.pnode1;
  6119. Js::OpCode op;
  6120. Js::CallFlags callFlags = Js::CallFlags::CallFlags_None;
  6121. uint spreadExtraAlloc = 0;
  6122. Js::ArgSlot actualArgSlotCount = (Js::ArgSlot) actualArgCount;
  6123. // check for integer overflow
  6124. if ((size_t)actualArgSlotCount != actualArgCount)
  6125. {
  6126. Js::Throw::OutOfMemory();
  6127. }
  6128. if (fIsPut)
  6129. {
  6130. if (pnode->sxCall.spreadArgCount > 0)
  6131. {
  6132. // TODO(tcare): We are disallowing spread with CallIPut for the moment. See DEVDIV2: 876387
  6133. // When CallIPut is migrated to the CallIExtended layout, this can be removed.
  6134. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAsgCall));
  6135. }
  6136. // Grab a tmp register for the call result.
  6137. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  6138. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallIFlags, tmpReg, pnodeTarget->location, actualArgSlotCount, callSiteId, Js::CallFlags::CallFlags_NewTarget);
  6139. funcInfo->ReleaseTmpRegister(tmpReg);
  6140. }
  6141. else
  6142. {
  6143. if (fEvaluateComponents)
  6144. {
  6145. // Release the call target operands we assigned above. If we didn't assign them here,
  6146. // we'll need them later, so we can't re-use them for the result of the call.
  6147. funcInfo->ReleaseLoc(pnodeTarget);
  6148. }
  6149. // Grab a register for the call result.
  6150. if (pnode->isUsed)
  6151. {
  6152. funcInfo->AcquireLoc(pnode);
  6153. }
  6154. if (fIsEval)
  6155. {
  6156. op = Js::OpCode::CallIExtendedFlags;
  6157. callFlags = Js::CallFlags::CallFlags_ExtraArg;
  6158. }
  6159. else
  6160. {
  6161. bool isSuperCall = pnodeTarget->nop == knopSuper;
  6162. if (isSuperCall)
  6163. {
  6164. callFlags = Js::CallFlags_New;
  6165. }
  6166. if (fHasNewTarget)
  6167. {
  6168. callFlags = (Js::CallFlags) (callFlags | Js::CallFlags::CallFlags_ExtraArg | Js::CallFlags::CallFlags_NewTarget);
  6169. }
  6170. if (pnode->sxCall.spreadArgCount > 0)
  6171. {
  6172. op = (isSuperCall || fHasNewTarget) ? Js::OpCode::CallIExtendedFlags : Js::OpCode::CallIExtended;
  6173. }
  6174. else
  6175. {
  6176. op = (isSuperCall || fHasNewTarget) ? Js::OpCode::CallIFlags : Js::OpCode::CallI;
  6177. }
  6178. }
  6179. if (op == Js::OpCode::CallI || op == Js::OpCode::CallIFlags)
  6180. {
  6181. byteCodeGenerator->Writer()->CallI(op, pnode->location, pnodeTarget->location, actualArgSlotCount, callSiteId, callFlags);
  6182. }
  6183. else
  6184. {
  6185. uint spreadIndicesSize = 0;
  6186. Js::CallIExtendedOptions options = Js::CallIExtended_None;
  6187. if (pnode->sxCall.spreadArgCount > 0)
  6188. {
  6189. Assert(spreadIndices != nullptr);
  6190. spreadExtraAlloc = spreadIndices->count * sizeof(uint32);
  6191. spreadIndicesSize = sizeof(*spreadIndices) + spreadExtraAlloc;
  6192. options = Js::CallIExtended_SpreadArgs;
  6193. }
  6194. byteCodeGenerator->Writer()->CallIExtended(op, pnode->location, pnodeTarget->location, actualArgSlotCount, options, spreadIndices, spreadIndicesSize, callSiteId, callFlags);
  6195. }
  6196. if (pnode->sxCall.spreadArgCount > 0)
  6197. {
  6198. Assert(spreadExtraAlloc != 0);
  6199. AdeletePlus(byteCodeGenerator->GetAllocator(), spreadExtraAlloc, spreadIndices);
  6200. }
  6201. }
  6202. }
  6203. void EmitCallInstrNoEvalComponents(
  6204. ParseNode *pnode,
  6205. BOOL fIsPut,
  6206. BOOL fIsEval,
  6207. Js::RegSlot thisLocation,
  6208. Js::RegSlot callObjLocation,
  6209. uint32 actualArgCount,
  6210. ByteCodeGenerator *byteCodeGenerator,
  6211. FuncInfo *funcInfo,
  6212. Js::ProfileId callSiteId,
  6213. Js::AuxArray<uint32> *spreadIndices = nullptr)
  6214. {
  6215. // Emit the call instruction. The call target is a reference at this point, and we evaluate
  6216. // it as part of doing the actual call.
  6217. // Note that we don't handle the (fEvaluateComponents == TRUE) case in this function.
  6218. // (This function is only called on the !fEvaluateComponents branch in EmitCall.)
  6219. ParseNode *pnodeTarget = pnode->sxBin.pnode1;
  6220. switch (pnodeTarget->nop)
  6221. {
  6222. case knopDot:
  6223. {
  6224. Assert(pnodeTarget->sxBin.pnode2->nop == knopName);
  6225. Js::PropertyId propertyId = pnodeTarget->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  6226. EmitMethodFld(pnodeTarget, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6227. EmitCallI(pnode, /*fEvaluateComponents*/ FALSE, fIsPut, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6228. }
  6229. break;
  6230. case knopIndex:
  6231. {
  6232. EmitMethodElem(pnodeTarget, pnodeTarget->sxBin.pnode1->location, pnodeTarget->sxBin.pnode2->location, byteCodeGenerator);
  6233. EmitCallI(pnode, /*fEvaluateComponents*/ FALSE, fIsPut, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6234. }
  6235. break;
  6236. case knopName:
  6237. {
  6238. if (callObjLocation != Js::Constants::NoRegister)
  6239. {
  6240. // We still have to get the property from its instance, so emit CallFld.
  6241. if (thisLocation != callObjLocation)
  6242. {
  6243. funcInfo->ReleaseTmpRegister(thisLocation);
  6244. }
  6245. funcInfo->ReleaseTmpRegister(callObjLocation);
  6246. Js::PropertyId propertyId = pnodeTarget->sxPid.PropertyIdFromNameNode();
  6247. EmitMethodFld(pnodeTarget, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6248. EmitCallI(pnode, /*fEvaluateComponents*/ FALSE, fIsPut, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6249. break;
  6250. }
  6251. }
  6252. // FALL THROUGH
  6253. default:
  6254. EmitCallI(pnode, /*fEvaluateComponents*/ FALSE, fIsPut, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6255. break;
  6256. }
  6257. }
  6258. void EmitCallInstr(
  6259. ParseNode *pnode,
  6260. BOOL fIsPut,
  6261. BOOL fIsEval,
  6262. BOOL fHasNewTarget,
  6263. Js::RegSlot thisLocation,
  6264. Js::RegSlot callObjLocation,
  6265. uint32 actualArgCount,
  6266. ByteCodeGenerator *byteCodeGenerator,
  6267. FuncInfo *funcInfo,
  6268. Js::ProfileId callSiteId,
  6269. Js::AuxArray<uint32> *spreadIndices = nullptr)
  6270. {
  6271. // Emit a call instruction. The call target has been fully evaluated already, so we always
  6272. // emit a CallI through the register that holds the target value.
  6273. // Note that we don't handle !fEvaluateComponents cases at this point.
  6274. // (This function is only called on the fEvaluateComponents branch in EmitCall.)
  6275. if (thisLocation != Js::Constants::NoRegister)
  6276. {
  6277. funcInfo->ReleaseTmpRegister(thisLocation);
  6278. }
  6279. if (callObjLocation != Js::Constants::NoRegister &&
  6280. callObjLocation != thisLocation)
  6281. {
  6282. funcInfo->ReleaseTmpRegister(callObjLocation);
  6283. }
  6284. EmitCallI(pnode, /*fEvaluateComponents*/ TRUE, fIsPut, fIsEval, fHasNewTarget, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6285. }
  6286. void EmitCall(
  6287. ParseNode* pnode,
  6288. Js::RegSlot rhsLocation,
  6289. ByteCodeGenerator* byteCodeGenerator,
  6290. FuncInfo* funcInfo,
  6291. BOOL fReturnValue,
  6292. BOOL fEvaluateComponents,
  6293. BOOL fHasNewTarget,
  6294. Js::RegSlot overrideThisLocation)
  6295. {
  6296. BOOL fIsPut = (rhsLocation != Js::Constants::NoRegister);
  6297. // If the call returns a float, we'll note this in the byte code.
  6298. Js::RegSlot thisLocation = Js::Constants::NoRegister;
  6299. Js::RegSlot callObjLocation = Js::Constants::NoRegister;
  6300. Js::RegSlot newTargetLocation = Js::Constants::NoRegister;
  6301. BOOL fSideEffectArgs = FALSE;
  6302. ParseNode *pnodeTarget = pnode->sxCall.pnodeTarget;
  6303. ParseNode *pnodeArgs = pnode->sxCall.pnodeArgs;
  6304. uint16 spreadArgCount = pnode->sxCall.spreadArgCount;
  6305. unsigned int argCount = CountArguments(pnode->sxCall.pnodeArgs, &fSideEffectArgs) + (unsigned int)fIsPut;
  6306. BOOL fIsEval = !fIsPut && pnode->sxCall.isEvalCall;
  6307. if (fIsEval)
  6308. {
  6309. Assert(!fHasNewTarget);
  6310. //
  6311. // "eval" takes the closure environment as an extra argument
  6312. // Pass the closure env only if some argument is passed
  6313. // For just eval(), don't pass the closure environment
  6314. //
  6315. if (argCount > 1)
  6316. {
  6317. // Check the module ID as well. If it's not the global (default) module,
  6318. // we need to pass the root to eval so it can do the right global lookups.
  6319. // (Passing the module root is the least disruptive way to get the module ID
  6320. // to the helper, given the current set of byte codes. Once we have a full set
  6321. // of byte code ops taking immediate opnds, passing the ID is more intuitive.)
  6322. Js::ModuleID moduleID = byteCodeGenerator->GetModuleID();
  6323. if (moduleID == kmodGlobal)
  6324. {
  6325. argCount++;
  6326. }
  6327. else
  6328. {
  6329. // Module ID must be passed
  6330. argCount += 2;
  6331. }
  6332. }
  6333. }
  6334. if (fHasNewTarget)
  6335. {
  6336. Assert(!fIsEval);
  6337. // When we need to pass new.target explicitly, it is passed as an extra argument.
  6338. // This is similar to how eval passes an extra argument for the frame display and is
  6339. // used to support cases where we need to pass both 'this' and new.target as part of
  6340. // a function call.
  6341. // OpCode::LdNewTarget knows how to look at the call flags and fetch this argument.
  6342. argCount++;
  6343. newTargetLocation = funcInfo->newTargetRegister;
  6344. Assert(newTargetLocation != Js::Constants::NoRegister);
  6345. }
  6346. Js::ArgSlot argSlotCount = (Js::ArgSlot)argCount;
  6347. if (argCount != (unsigned int)argSlotCount)
  6348. {
  6349. Js::Throw::OutOfMemory();
  6350. }
  6351. if (fReturnValue)
  6352. {
  6353. pnode->isUsed = true;
  6354. }
  6355. //
  6356. // Set up the call.
  6357. //
  6358. if (!fEvaluateComponents)
  6359. {
  6360. EmitCallTargetNoEvalComponents(pnodeTarget, fSideEffectArgs, &thisLocation, &callObjLocation, byteCodeGenerator, funcInfo);
  6361. }
  6362. else
  6363. {
  6364. EmitCallTarget(pnodeTarget, fSideEffectArgs, &thisLocation, &callObjLocation, byteCodeGenerator, funcInfo);
  6365. }
  6366. bool releaseThisLocation = true;
  6367. // If we are strictly overriding the this location, ignore what the call target set this location to.
  6368. if (overrideThisLocation != Js::Constants::NoRegister)
  6369. {
  6370. thisLocation = overrideThisLocation;
  6371. releaseThisLocation = false;
  6372. }
  6373. // Evaluate the arguments (nothing mode-specific here).
  6374. // Start call, allocate out param space
  6375. funcInfo->StartRecordingOutArgs(argSlotCount);
  6376. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  6377. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argSlotCount);
  6378. Js::AuxArray<uint32> *spreadIndices;
  6379. Js::ArgSlot actualArgCount = EmitArgList(pnodeArgs, rhsLocation, thisLocation, newTargetLocation, fIsEval, fEvaluateComponents, byteCodeGenerator, funcInfo, callSiteId, spreadArgCount, &spreadIndices);
  6380. Assert(argSlotCount == actualArgCount);
  6381. if (!fEvaluateComponents)
  6382. {
  6383. EmitCallInstrNoEvalComponents(pnode, fIsPut, fIsEval, thisLocation, callObjLocation, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6384. }
  6385. else
  6386. {
  6387. EmitCallInstr(pnode, fIsPut, fIsEval, fHasNewTarget, releaseThisLocation ? thisLocation : Js::Constants::NoRegister, callObjLocation, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6388. }
  6389. // End call, pop param space
  6390. funcInfo->EndRecordingOutArgs(argSlotCount);
  6391. }
  6392. void EmitInvoke(
  6393. Js::RegSlot location,
  6394. Js::RegSlot callObjLocation,
  6395. Js::PropertyId propertyId,
  6396. ByteCodeGenerator* byteCodeGenerator,
  6397. FuncInfo* funcInfo)
  6398. {
  6399. EmitMethodFld(false, false, location, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6400. funcInfo->StartRecordingOutArgs(1);
  6401. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  6402. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, 1);
  6403. EmitArgListStart(callObjLocation, byteCodeGenerator, funcInfo, callSiteId);
  6404. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallI, location, location, 1, callSiteId);
  6405. }
  6406. void EmitInvoke(
  6407. Js::RegSlot location,
  6408. Js::RegSlot callObjLocation,
  6409. Js::PropertyId propertyId,
  6410. ByteCodeGenerator* byteCodeGenerator,
  6411. FuncInfo* funcInfo,
  6412. Js::RegSlot arg1Location)
  6413. {
  6414. EmitMethodFld(false, false, location, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6415. funcInfo->StartRecordingOutArgs(2);
  6416. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  6417. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, 2);
  6418. EmitArgListStart(callObjLocation, byteCodeGenerator, funcInfo, callSiteId);
  6419. byteCodeGenerator->Writer()->ArgOut<true>(1, arg1Location, callSiteId);
  6420. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallI, location, location, 2, callSiteId);
  6421. }
  6422. void EmitComputedFunctionNameVar(ParseNode *nameNode, ParseNode *exprNode, ByteCodeGenerator *byteCodeGenerator)
  6423. {
  6424. AssertMsg(exprNode != nullptr, "callers of this function should pass in a valid expression Node");
  6425. if (nameNode == nullptr)
  6426. {
  6427. return;
  6428. }
  6429. if ((exprNode->nop == knopFncDecl && (exprNode->sxFnc.pnodeName == nullptr || exprNode->sxFnc.pnodeName->nop != knopVarDecl)))
  6430. {
  6431. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SetComputedNameVar, exprNode->location, nameNode->location);
  6432. }
  6433. }
  6434. void EmitMemberNode(ParseNode *memberNode, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, ParseNode* parentNode, bool useStore, bool* isObjectEmpty = nullptr)
  6435. {
  6436. ParseNode *nameNode = memberNode->sxBin.pnode1;
  6437. ParseNode *exprNode = memberNode->sxBin.pnode2;
  6438. bool isFncDecl = exprNode->nop == knopFncDecl;
  6439. bool isClassMember = isFncDecl && exprNode->sxFnc.IsClassMember();
  6440. // Moved SetComputedNameVar before LdFld of prototype because loading the prototype undefers the function TypeHandler
  6441. // which makes this bytecode too late to influence the function.name.
  6442. if (nameNode->nop == knopComputedName)
  6443. {
  6444. // Computed property name
  6445. // Transparently pass the name expr
  6446. // The Emit will replace this with a temp register if necessary to preserve the value.
  6447. nameNode->location = nameNode->sxUni.pnode1->location;
  6448. EmitBinaryOpnds(nameNode, exprNode, byteCodeGenerator, funcInfo);
  6449. if (isFncDecl && !exprNode->sxFnc.IsClassConstructor())
  6450. {
  6451. EmitComputedFunctionNameVar(nameNode, exprNode, byteCodeGenerator);
  6452. }
  6453. }
  6454. // Classes allocates a RegSlot as part of Instance Methods EmitClassInitializers,
  6455. // but if we don't have any members then we don't need to load the prototype.
  6456. Assert(isClassMember == (isObjectEmpty != nullptr));
  6457. if (isClassMember && *isObjectEmpty)
  6458. {
  6459. *isObjectEmpty = false;
  6460. int cacheId = funcInfo->FindOrAddInlineCacheId(parentNode->location, Js::PropertyIds::prototype, false, false);
  6461. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, objectLocation, parentNode->location, cacheId);
  6462. }
  6463. if (nameNode->nop == knopComputedName)
  6464. {
  6465. Assert(memberNode->nop == knopGetMember || memberNode->nop == knopSetMember || memberNode->nop == knopMember);
  6466. Js::OpCode setOp = memberNode->nop == knopGetMember ?
  6467. (isClassMember ? Js::OpCode::InitClassMemberGetComputedName : Js::OpCode::InitGetElemI) :
  6468. memberNode->nop == knopSetMember ?
  6469. (isClassMember ? Js::OpCode::InitClassMemberSetComputedName : Js::OpCode::InitSetElemI) :
  6470. (isClassMember ? Js::OpCode::InitClassMemberComputedName : Js::OpCode::InitComputedProperty);
  6471. byteCodeGenerator->Writer()->Element(setOp, exprNode->location, objectLocation, nameNode->location, true);
  6472. // Class and object members need a reference back to the class.
  6473. if (isFncDecl)
  6474. {
  6475. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SetHomeObj, exprNode->location, objectLocation);
  6476. }
  6477. funcInfo->ReleaseLoc(exprNode);
  6478. funcInfo->ReleaseLoc(nameNode);
  6479. return;
  6480. }
  6481. Js::OpCode stFldOpCode = (Js::OpCode)0;
  6482. if (useStore)
  6483. {
  6484. stFldOpCode = ByteCodeGenerator::GetStFldOpCode(funcInfo, false, false, false, isClassMember);
  6485. }
  6486. Emit(exprNode, byteCodeGenerator, funcInfo, false);
  6487. Js::PropertyId propertyId = nameNode->sxPid.PropertyIdFromNameNode();
  6488. if (Js::PropertyIds::name == propertyId
  6489. && exprNode->nop == knopFncDecl
  6490. && exprNode->sxFnc.IsStaticMember()
  6491. && parentNode != nullptr && parentNode->nop == knopClassDecl
  6492. && parentNode->sxClass.pnodeConstructor != nullptr)
  6493. {
  6494. Js::ParseableFunctionInfo* nameFunc = parentNode->sxClass.pnodeConstructor->sxFnc.funcInfo->byteCodeFunction->GetParseableFunctionInfo();
  6495. nameFunc->SetIsStaticNameFunction(true);
  6496. }
  6497. if (memberNode->nop == knopMember || memberNode->nop == knopMemberShort)
  6498. {
  6499. // The internal prototype should be set only if the production is of the form PropertyDefinition : PropertyName : AssignmentExpression
  6500. if (propertyId == Js::PropertyIds::__proto__ && memberNode->nop != knopMemberShort && (exprNode->nop != knopFncDecl || !exprNode->sxFnc.IsMethod()))
  6501. {
  6502. byteCodeGenerator->Writer()->Property(Js::OpCode::InitProto, exprNode->location, objectLocation,
  6503. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  6504. }
  6505. else
  6506. {
  6507. uint cacheId = funcInfo->FindOrAddInlineCacheId(objectLocation, propertyId, false, true);
  6508. Js::OpCode patchablePropertyOpCode;
  6509. if (useStore)
  6510. {
  6511. patchablePropertyOpCode = stFldOpCode;
  6512. }
  6513. else if (isClassMember)
  6514. {
  6515. patchablePropertyOpCode = Js::OpCode::InitClassMember;
  6516. }
  6517. else
  6518. {
  6519. patchablePropertyOpCode = Js::OpCode::InitFld;
  6520. }
  6521. byteCodeGenerator->Writer()->PatchableProperty(patchablePropertyOpCode, exprNode->location, objectLocation, cacheId);
  6522. }
  6523. }
  6524. else
  6525. {
  6526. Assert(memberNode->nop == knopGetMember || memberNode->nop == knopSetMember);
  6527. Js::OpCode setOp = memberNode->nop == knopGetMember ?
  6528. (isClassMember ? Js::OpCode::InitClassMemberGet : Js::OpCode::InitGetFld) :
  6529. (isClassMember ? Js::OpCode::InitClassMemberSet : Js::OpCode::InitSetFld);
  6530. byteCodeGenerator->Writer()->Property(setOp, exprNode->location, objectLocation, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  6531. }
  6532. // Class and object members need a reference back to the class.
  6533. if (isFncDecl)
  6534. {
  6535. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SetHomeObj, exprNode->location, objectLocation);
  6536. }
  6537. funcInfo->ReleaseLoc(exprNode);
  6538. if (propertyId == Js::PropertyIds::valueOf)
  6539. {
  6540. byteCodeGenerator->GetScriptContext()->optimizationOverrides.SetSideEffects(Js::SideEffects_ValueOf);
  6541. }
  6542. else if (propertyId == Js::PropertyIds::toString)
  6543. {
  6544. byteCodeGenerator->GetScriptContext()->optimizationOverrides.SetSideEffects(Js::SideEffects_ToString);
  6545. }
  6546. }
  6547. void EmitClassInitializers(ParseNode *memberList, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, ParseNode* parentNode, bool isObjectEmpty)
  6548. {
  6549. if (memberList != nullptr)
  6550. {
  6551. while (memberList->nop == knopList)
  6552. {
  6553. ParseNode *memberNode = memberList->sxBin.pnode1;
  6554. EmitMemberNode(memberNode, objectLocation, byteCodeGenerator, funcInfo, parentNode, /*useStore*/ false, &isObjectEmpty);
  6555. memberList = memberList->sxBin.pnode2;
  6556. }
  6557. EmitMemberNode(memberList, objectLocation, byteCodeGenerator, funcInfo, parentNode, /*useStore*/ false, &isObjectEmpty);
  6558. }
  6559. }
  6560. void EmitObjectInitializers(ParseNode *memberList, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  6561. {
  6562. ParseNode *pmemberList = memberList;
  6563. unsigned int argCount = 0;
  6564. uint32 value;
  6565. Js::PropertyId propertyId;
  6566. //
  6567. // 1. Add all non-int property ids to a dictionary propertyIds with value true
  6568. // 2. Get the count of propertyIds
  6569. // 3. Create a propertyId array of size count
  6570. // 4. Put the propIds in the auxiliary area
  6571. // 5. Get the objectLiteralCacheId
  6572. // 6. Generate propId inits with values
  6573. //
  6574. // Handle propertyId collision
  6575. typedef JsUtil::BaseHashSet<Js::PropertyId, ArenaAllocator, PowerOf2SizePolicy> PropertyIdSet;
  6576. PropertyIdSet* propertyIds = Anew(byteCodeGenerator->GetAllocator(), PropertyIdSet, byteCodeGenerator->GetAllocator(), 17);
  6577. bool hasComputedName = false;
  6578. if (memberList != nullptr)
  6579. {
  6580. while (memberList->nop == knopList)
  6581. {
  6582. if (memberList->sxBin.pnode1->sxBin.pnode1->nop == knopComputedName)
  6583. {
  6584. hasComputedName = true;
  6585. break;
  6586. }
  6587. propertyId = memberList->sxBin.pnode1->sxBin.pnode1->sxPid.PropertyIdFromNameNode();
  6588. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value))
  6589. {
  6590. propertyIds->Item(propertyId);
  6591. }
  6592. memberList = memberList->sxBin.pnode2;
  6593. }
  6594. if (memberList->sxBin.pnode1->nop != knopComputedName && !hasComputedName)
  6595. {
  6596. propertyId = memberList->sxBin.pnode1->sxPid.PropertyIdFromNameNode();
  6597. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value))
  6598. {
  6599. propertyIds->Item(propertyId);
  6600. }
  6601. }
  6602. }
  6603. argCount = propertyIds->Count();
  6604. memberList = pmemberList;
  6605. if ((memberList == nullptr) || (argCount == 0))
  6606. {
  6607. // Empty literal or numeric property only object literal
  6608. byteCodeGenerator->Writer()->Reg1(Js::OpCode::NewScObjectSimple, objectLocation);
  6609. }
  6610. else
  6611. {
  6612. Js::PropertyIdArray *propIds = AnewPlus(byteCodeGenerator->GetAllocator(), argCount * sizeof(Js::PropertyId), Js::PropertyIdArray, argCount);
  6613. if (propertyIds->ContainsKey(Js::PropertyIds::__proto__))
  6614. {
  6615. // Always record whether the initializer contains __proto__ no matter if current environment has it enabled
  6616. // or not, in case the bytecode is later run with __proto__ enabled.
  6617. propIds->has__proto__ = true;
  6618. }
  6619. unsigned int argIndex = 0;
  6620. while (memberList->nop == knopList)
  6621. {
  6622. if (memberList->sxBin.pnode1->sxBin.pnode1->nop == knopComputedName)
  6623. {
  6624. break;
  6625. }
  6626. propertyId = memberList->sxBin.pnode1->sxBin.pnode1->sxPid.PropertyIdFromNameNode();
  6627. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value) && propertyIds->Remove(propertyId))
  6628. {
  6629. propIds->elements[argIndex] = propertyId;
  6630. argIndex++;
  6631. }
  6632. memberList = memberList->sxBin.pnode2;
  6633. }
  6634. if (memberList->sxBin.pnode1->nop != knopComputedName && !hasComputedName)
  6635. {
  6636. propertyId = memberList->sxBin.pnode1->sxPid.PropertyIdFromNameNode();
  6637. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value) && propertyIds->Remove(propertyId))
  6638. {
  6639. propIds->elements[argIndex] = propertyId;
  6640. argIndex++;
  6641. }
  6642. }
  6643. uint32 literalObjectId = funcInfo->GetParsedFunctionBody()->NewObjectLiteral();
  6644. // Generate the opcode with propIds and cacheId
  6645. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::NewScObjectLiteral, objectLocation, propIds, sizeof(Js::PropertyIdArray) + argCount * sizeof(Js::PropertyId), literalObjectId);
  6646. Adelete(byteCodeGenerator->GetAllocator(), propertyIds);
  6647. AdeletePlus(byteCodeGenerator->GetAllocator(), argCount * sizeof(Js::PropertyId), propIds);
  6648. }
  6649. memberList = pmemberList;
  6650. bool useStore = false;
  6651. // Generate the actual assignment to those properties
  6652. if (memberList != nullptr)
  6653. {
  6654. while (memberList->nop == knopList)
  6655. {
  6656. ParseNode *memberNode = memberList->sxBin.pnode1;
  6657. if (memberNode->sxBin.pnode1->nop == knopComputedName)
  6658. {
  6659. useStore = true;
  6660. }
  6661. byteCodeGenerator->StartSubexpression(memberNode);
  6662. EmitMemberNode(memberNode, objectLocation, byteCodeGenerator, funcInfo, nullptr, useStore);
  6663. byteCodeGenerator->EndSubexpression(memberNode);
  6664. memberList = memberList->sxBin.pnode2;
  6665. }
  6666. byteCodeGenerator->StartSubexpression(memberList);
  6667. EmitMemberNode(memberList, objectLocation, byteCodeGenerator, funcInfo, nullptr, useStore);
  6668. byteCodeGenerator->EndSubexpression(memberList);
  6669. }
  6670. }
  6671. void EmitStringTemplate(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  6672. {
  6673. Assert(pnode->sxStrTemplate.pnodeStringLiterals);
  6674. // For a tagged string template, we will create the callsite constant object as part of the FunctionBody constants table.
  6675. // We only need to emit code for non-tagged string templates here.
  6676. if (!pnode->sxStrTemplate.isTaggedTemplate)
  6677. {
  6678. // If we have no substitutions and this is not a tagged template, we can emit just the single cooked string.
  6679. if (pnode->sxStrTemplate.pnodeSubstitutionExpressions == nullptr)
  6680. {
  6681. Assert(pnode->sxStrTemplate.pnodeStringLiterals->nop != knopList);
  6682. funcInfo->AcquireLoc(pnode);
  6683. Emit(pnode->sxStrTemplate.pnodeStringLiterals, byteCodeGenerator, funcInfo, false);
  6684. Assert(pnode->location != pnode->sxStrTemplate.pnodeStringLiterals->location);
  6685. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxStrTemplate.pnodeStringLiterals->location);
  6686. funcInfo->ReleaseLoc(pnode->sxStrTemplate.pnodeStringLiterals);
  6687. }
  6688. else
  6689. {
  6690. // If we have substitutions but no tag function, we can skip the callSite object construction (and also ignore raw strings).
  6691. funcInfo->AcquireLoc(pnode);
  6692. // First string must be a list node since we have substitutions.
  6693. AssertMsg(pnode->sxStrTemplate.pnodeStringLiterals->nop == knopList, "First string in the list must be a knopList node.");
  6694. ParseNode* stringNodeList = pnode->sxStrTemplate.pnodeStringLiterals;
  6695. // Emit the first string and load that into the pnode location.
  6696. Emit(stringNodeList->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  6697. Assert(pnode->location != stringNodeList->sxBin.pnode1->location);
  6698. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, stringNodeList->sxBin.pnode1->location);
  6699. funcInfo->ReleaseLoc(stringNodeList->sxBin.pnode1);
  6700. ParseNode* expressionNodeList = pnode->sxStrTemplate.pnodeSubstitutionExpressions;
  6701. ParseNode* stringNode;
  6702. ParseNode* expressionNode;
  6703. // Now append the substitution expressions and remaining string constants via normal add operator
  6704. // We will always have one more string constant than substitution expression
  6705. // `strcon1 ${expr1} strcon2 ${expr2} strcon3` = strcon1 + expr1 + strcon2 + expr2 + strcon3
  6706. //
  6707. // strcon1 --- step 1 (above)
  6708. // expr1 \__ step 2
  6709. // strcon2 /
  6710. // expr2 \__ step 3
  6711. // strcon3 /
  6712. while (stringNodeList->nop == knopList)
  6713. {
  6714. // If the current head of the expression list is a list, fetch the node and walk the list.
  6715. if (expressionNodeList->nop == knopList)
  6716. {
  6717. expressionNode = expressionNodeList->sxBin.pnode1;
  6718. expressionNodeList = expressionNodeList->sxBin.pnode2;
  6719. }
  6720. else
  6721. {
  6722. // This is the last element of the expression list.
  6723. expressionNode = expressionNodeList;
  6724. }
  6725. // Emit the expression and append it to the string we're building.
  6726. Emit(expressionNode, byteCodeGenerator, funcInfo, false);
  6727. Js::RegSlot toStringLocation = funcInfo->AcquireTmpRegister();
  6728. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Str, toStringLocation, expressionNode->location);
  6729. byteCodeGenerator->Writer()->Reg3(Js::OpCode::Add_A, pnode->location, pnode->location, toStringLocation);
  6730. funcInfo->ReleaseTmpRegister(toStringLocation);
  6731. funcInfo->ReleaseLoc(expressionNode);
  6732. // Move to the next string in the list - we already got ahead of the expressions in the first string literal above.
  6733. stringNodeList = stringNodeList->sxBin.pnode2;
  6734. // If the current head of the string literal list is also a list node, need to fetch the actual string literal node.
  6735. if (stringNodeList->nop == knopList)
  6736. {
  6737. stringNode = stringNodeList->sxBin.pnode1;
  6738. }
  6739. else
  6740. {
  6741. // This is the last element of the string literal list.
  6742. stringNode = stringNodeList;
  6743. }
  6744. // Emit the string node following the previous expression and append it to the string.
  6745. // This is either just some string in the list or it is the last string.
  6746. Emit(stringNode, byteCodeGenerator, funcInfo, false);
  6747. byteCodeGenerator->Writer()->Reg3(Js::OpCode::Add_A, pnode->location, pnode->location, stringNode->location);
  6748. funcInfo->ReleaseLoc(stringNode);
  6749. }
  6750. }
  6751. }
  6752. }
  6753. void SetNewArrayElements(ParseNode *pnode, Js::RegSlot arrayLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  6754. {
  6755. ParseNode *args = pnode->sxUni.pnode1;
  6756. uint argCount = pnode->sxArrLit.count;
  6757. uint spreadCount = pnode->sxArrLit.spreadCount;
  6758. bool nativeArrays = CreateNativeArrays(byteCodeGenerator, funcInfo);
  6759. bool arrayIntOpt = nativeArrays && pnode->sxArrLit.arrayOfInts;
  6760. if (arrayIntOpt)
  6761. {
  6762. int extraAlloc = argCount * sizeof(int32);
  6763. Js::AuxArray<int> *ints = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<int32>, argCount);
  6764. EmitConstantArgsToIntArray(byteCodeGenerator, ints->elements, args, argCount);
  6765. Assert(!pnode->sxArrLit.hasMissingValues);
  6766. byteCodeGenerator->Writer()->Auxiliary(
  6767. Js::OpCode::NewScIntArray,
  6768. pnode->location,
  6769. ints,
  6770. sizeof(Js::AuxArray<int>) + extraAlloc,
  6771. argCount);
  6772. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, ints);
  6773. return;
  6774. }
  6775. bool arrayNumOpt = nativeArrays && pnode->sxArrLit.arrayOfNumbers;
  6776. if (arrayNumOpt)
  6777. {
  6778. int extraAlloc = argCount * sizeof(double);
  6779. Js::AuxArray<double> *doubles = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<double>, argCount);
  6780. EmitConstantArgsToFltArray(byteCodeGenerator, doubles->elements, args, argCount);
  6781. Assert(!pnode->sxArrLit.hasMissingValues);
  6782. byteCodeGenerator->Writer()->Auxiliary(
  6783. Js::OpCode::NewScFltArray,
  6784. pnode->location,
  6785. doubles,
  6786. sizeof(Js::AuxArray<double>) + extraAlloc,
  6787. argCount);
  6788. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, doubles);
  6789. return;
  6790. }
  6791. bool arrayLitOpt = pnode->sxArrLit.arrayOfTaggedInts && pnode->sxArrLit.count > 1;
  6792. Assert(!arrayLitOpt || !nativeArrays);
  6793. Js::RegSlot spreadArrLoc = arrayLocation;
  6794. Js::AuxArray<uint32> *spreadIndices = nullptr;
  6795. const uint extraAlloc = spreadCount * sizeof(uint32);
  6796. if (pnode->sxArrLit.spreadCount > 0)
  6797. {
  6798. arrayLocation = funcInfo->AcquireTmpRegister();
  6799. spreadIndices = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<uint32>, spreadCount);
  6800. }
  6801. byteCodeGenerator->Writer()->Reg1Unsigned1(
  6802. pnode->sxArrLit.hasMissingValues ? Js::OpCode::NewScArrayWithMissingValues : Js::OpCode::NewScArray,
  6803. arrayLocation,
  6804. argCount);
  6805. if (args != nullptr)
  6806. {
  6807. Js::OpCode opcode;
  6808. Js::RegSlot arrLoc;
  6809. if (argCount == 1 && !byteCodeGenerator->Writer()->DoProfileNewScArrayOp(Js::OpCode::NewScArray))
  6810. {
  6811. opcode = Js::OpCode::StArrItemC_CI4;
  6812. arrLoc = arrayLocation;
  6813. }
  6814. else if (arrayLitOpt)
  6815. {
  6816. opcode = Js::OpCode::StArrSegItem_A;
  6817. arrLoc = funcInfo->AcquireTmpRegister();
  6818. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdArrHead, arrLoc, arrayLocation);
  6819. }
  6820. else if (Js::JavascriptArray::HasInlineHeadSegment(argCount))
  6821. {
  6822. // The head segment will be allocated inline as an interior pointer. To keep the array alive, the set operation
  6823. // should be done relative to the array header to keep it alive (instead of the array segment).
  6824. opcode = Js::OpCode::StArrInlineItem_CI4;
  6825. arrLoc = arrayLocation;
  6826. }
  6827. else if (argCount <= Js::JavascriptArray::MaxInitialDenseLength)
  6828. {
  6829. opcode = Js::OpCode::StArrSegItem_CI4;
  6830. arrLoc = funcInfo->AcquireTmpRegister();
  6831. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdArrHead, arrLoc, arrayLocation);
  6832. }
  6833. else
  6834. {
  6835. opcode = Js::OpCode::StArrItemI_CI4;
  6836. arrLoc = arrayLocation;
  6837. }
  6838. if (arrayLitOpt)
  6839. {
  6840. Js::VarArray *vars = AnewPlus(byteCodeGenerator->GetAllocator(), argCount * sizeof(Js::Var), Js::VarArray, argCount);
  6841. EmitConstantArgsToVarArray(byteCodeGenerator, vars->elements, args, argCount);
  6842. // Generate the opcode with vars
  6843. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::StArrSegItem_A, arrLoc, vars, sizeof(Js::VarArray) + argCount * sizeof(Js::Var), argCount);
  6844. AdeletePlus(byteCodeGenerator->GetAllocator(), argCount * sizeof(Js::Var), vars);
  6845. }
  6846. else
  6847. {
  6848. uint i = 0;
  6849. unsigned spreadIndex = 0;
  6850. Js::RegSlot rhsLocation;
  6851. while (args->nop == knopList)
  6852. {
  6853. if (args->sxBin.pnode1->nop != knopEmpty)
  6854. {
  6855. Emit(args->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  6856. rhsLocation = args->sxBin.pnode1->location;
  6857. Js::RegSlot regVal = rhsLocation;
  6858. if (args->sxBin.pnode1->nop == knopEllipsis)
  6859. {
  6860. AnalysisAssert(spreadIndices);
  6861. regVal = funcInfo->AcquireTmpRegister();
  6862. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, rhsLocation);
  6863. spreadIndices->elements[spreadIndex++] = i;
  6864. }
  6865. byteCodeGenerator->Writer()->ElementUnsigned1(opcode, regVal, arrLoc, i);
  6866. if (args->sxBin.pnode1->nop == knopEllipsis)
  6867. {
  6868. funcInfo->ReleaseTmpRegister(regVal);
  6869. }
  6870. funcInfo->ReleaseLoc(args->sxBin.pnode1);
  6871. }
  6872. args = args->sxBin.pnode2;
  6873. i++;
  6874. }
  6875. if (args->nop != knopEmpty)
  6876. {
  6877. Emit(args, byteCodeGenerator, funcInfo, false);
  6878. rhsLocation = args->location;
  6879. Js::RegSlot regVal = rhsLocation;
  6880. if (args->nop == knopEllipsis)
  6881. {
  6882. regVal = funcInfo->AcquireTmpRegister();
  6883. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, rhsLocation);
  6884. AnalysisAssert(spreadIndices);
  6885. spreadIndices->elements[spreadIndex] = i;
  6886. }
  6887. byteCodeGenerator->Writer()->ElementUnsigned1(opcode, regVal, arrLoc, i);
  6888. if (args->nop == knopEllipsis)
  6889. {
  6890. funcInfo->ReleaseTmpRegister(regVal);
  6891. }
  6892. funcInfo->ReleaseLoc(args);
  6893. i++;
  6894. }
  6895. Assert(i <= argCount);
  6896. }
  6897. if (arrLoc != arrayLocation)
  6898. {
  6899. funcInfo->ReleaseTmpRegister(arrLoc);
  6900. }
  6901. }
  6902. if (pnode->sxArrLit.spreadCount > 0)
  6903. {
  6904. byteCodeGenerator->Writer()->Reg2Aux(Js::OpCode::SpreadArrayLiteral, spreadArrLoc, arrayLocation, spreadIndices, sizeof(Js::AuxArray<uint32>) + extraAlloc, extraAlloc);
  6905. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, spreadIndices);
  6906. funcInfo->ReleaseTmpRegister(arrayLocation);
  6907. }
  6908. }
  6909. // FIX: TODO: mixed-mode expressions (arithmetic expressions mixed with boolean expressions); current solution
  6910. // will not short-circuit in some cases and is not complete (for example: var i=(x==y))
  6911. // This uses Aho and Ullman style double-branch generation (p. 494 ASU); we will need to peephole optimize or replace
  6912. // with special case for single-branch style.
  6913. void EmitBooleanExpression(ParseNode *expr, Js::ByteCodeLabel trueLabel, Js::ByteCodeLabel falseLabel, ByteCodeGenerator *byteCodeGenerator,
  6914. FuncInfo *funcInfo)
  6915. {
  6916. switch (expr->nop)
  6917. {
  6918. case knopLogOr:
  6919. {
  6920. byteCodeGenerator->StartStatement(expr);
  6921. Js::ByteCodeLabel leftFalse = byteCodeGenerator->Writer()->DefineLabel();
  6922. EmitBooleanExpression(expr->sxBin.pnode1, trueLabel, leftFalse, byteCodeGenerator, funcInfo);
  6923. funcInfo->ReleaseLoc(expr->sxBin.pnode1);
  6924. byteCodeGenerator->Writer()->MarkLabel(leftFalse);
  6925. EmitBooleanExpression(expr->sxBin.pnode2, trueLabel, falseLabel, byteCodeGenerator, funcInfo);
  6926. funcInfo->ReleaseLoc(expr->sxBin.pnode2);
  6927. byteCodeGenerator->EndStatement(expr);
  6928. break;
  6929. }
  6930. case knopLogAnd:
  6931. {
  6932. byteCodeGenerator->StartStatement(expr);
  6933. Js::ByteCodeLabel leftTrue = byteCodeGenerator->Writer()->DefineLabel();
  6934. EmitBooleanExpression(expr->sxBin.pnode1, leftTrue, falseLabel, byteCodeGenerator, funcInfo);
  6935. funcInfo->ReleaseLoc(expr->sxBin.pnode1);
  6936. byteCodeGenerator->Writer()->MarkLabel(leftTrue);
  6937. EmitBooleanExpression(expr->sxBin.pnode2, trueLabel, falseLabel, byteCodeGenerator, funcInfo);
  6938. funcInfo->ReleaseLoc(expr->sxBin.pnode2);
  6939. byteCodeGenerator->EndStatement(expr);
  6940. break;
  6941. }
  6942. case knopLogNot:
  6943. byteCodeGenerator->StartStatement(expr);
  6944. EmitBooleanExpression(expr->sxUni.pnode1, falseLabel, trueLabel, byteCodeGenerator, funcInfo);
  6945. funcInfo->ReleaseLoc(expr->sxUni.pnode1);
  6946. byteCodeGenerator->EndStatement(expr);
  6947. break;
  6948. case knopEq:
  6949. case knopEqv:
  6950. case knopNEqv:
  6951. case knopNe:
  6952. case knopLt:
  6953. case knopLe:
  6954. case knopGe:
  6955. case knopGt:
  6956. byteCodeGenerator->StartStatement(expr);
  6957. EmitBinaryOpnds(expr->sxBin.pnode1, expr->sxBin.pnode2, byteCodeGenerator, funcInfo);
  6958. funcInfo->ReleaseLoc(expr->sxBin.pnode2);
  6959. funcInfo->ReleaseLoc(expr->sxBin.pnode1);
  6960. byteCodeGenerator->Writer()->BrReg2(nopToOp[expr->nop], trueLabel, expr->sxBin.pnode1->location,
  6961. expr->sxBin.pnode2->location);
  6962. byteCodeGenerator->Writer()->Br(falseLabel);
  6963. byteCodeGenerator->EndStatement(expr);
  6964. break;
  6965. case knopTrue:
  6966. byteCodeGenerator->StartStatement(expr);
  6967. byteCodeGenerator->Writer()->Br(trueLabel);
  6968. byteCodeGenerator->EndStatement(expr);
  6969. break;
  6970. case knopFalse:
  6971. byteCodeGenerator->StartStatement(expr);
  6972. byteCodeGenerator->Writer()->Br(falseLabel);
  6973. byteCodeGenerator->EndStatement(expr);
  6974. break;
  6975. default:
  6976. // Note: we usually release the temp assigned to a node after we Emit it.
  6977. // But in this case, EmitBooleanExpression is just a wrapper around a normal Emit call,
  6978. // and the caller of EmitBooleanExpression expects to be able to release this register.
  6979. // For diagnostics purposes, register the name and dot to the statement list.
  6980. if (expr->nop == knopName || expr->nop == knopDot)
  6981. {
  6982. byteCodeGenerator->StartStatement(expr);
  6983. Emit(expr, byteCodeGenerator, funcInfo, false);
  6984. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  6985. byteCodeGenerator->Writer()->Br(falseLabel);
  6986. byteCodeGenerator->EndStatement(expr);
  6987. }
  6988. else
  6989. {
  6990. Emit(expr, byteCodeGenerator, funcInfo, false);
  6991. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  6992. byteCodeGenerator->Writer()->Br(falseLabel);
  6993. }
  6994. break;
  6995. }
  6996. }
  6997. // used by while and for loops
  6998. void EmitLoop(
  6999. ParseNode *loopNode,
  7000. ParseNode *cond,
  7001. ParseNode *body,
  7002. ParseNode *incr,
  7003. ByteCodeGenerator *byteCodeGenerator,
  7004. FuncInfo *funcInfo,
  7005. BOOL fReturnValue,
  7006. BOOL doWhile = FALSE,
  7007. ParseNode *forLoopBlock = nullptr)
  7008. {
  7009. // Need to increment loop count whether we are going to profile or not for HasLoop()
  7010. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  7011. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  7012. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  7013. loopNode->sxLoop.loopId = loopId;
  7014. if (doWhile)
  7015. {
  7016. Emit(body, byteCodeGenerator, funcInfo, fReturnValue);
  7017. funcInfo->ReleaseLoc(body);
  7018. if (loopNode->emitLabels)
  7019. {
  7020. byteCodeGenerator->Writer()->MarkLabel(loopNode->sxStmt.continueLabel);
  7021. }
  7022. if (!ByteCodeGenerator::IsFalse(cond) ||
  7023. byteCodeGenerator->IsInDebugMode())
  7024. {
  7025. EmitBooleanExpression(cond, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo);
  7026. }
  7027. funcInfo->ReleaseLoc(cond);
  7028. }
  7029. else
  7030. {
  7031. if (cond)
  7032. {
  7033. if (!(cond->nop == knopInt &&
  7034. cond->sxInt.lw != 0))
  7035. {
  7036. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  7037. EmitBooleanExpression(cond, trueLabel, continuePastLoop, byteCodeGenerator, funcInfo);
  7038. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  7039. }
  7040. funcInfo->ReleaseLoc(cond);
  7041. }
  7042. Emit(body, byteCodeGenerator, funcInfo, fReturnValue);
  7043. funcInfo->ReleaseLoc(body);
  7044. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled() &&
  7045. forLoopBlock != nullptr)
  7046. {
  7047. CloneEmitBlock(forLoopBlock, byteCodeGenerator, funcInfo);
  7048. }
  7049. if (loopNode->emitLabels)
  7050. {
  7051. byteCodeGenerator->Writer()->MarkLabel(loopNode->sxStmt.continueLabel);
  7052. }
  7053. if (incr != nullptr)
  7054. {
  7055. Emit(incr, byteCodeGenerator, funcInfo, false);
  7056. funcInfo->ReleaseLoc(incr);
  7057. }
  7058. byteCodeGenerator->Writer()->Br(loopEntrance);
  7059. }
  7060. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  7061. if (loopNode->emitLabels)
  7062. {
  7063. byteCodeGenerator->Writer()->MarkLabel(loopNode->sxStmt.breakLabel);
  7064. }
  7065. byteCodeGenerator->Writer()->ExitLoop(loopId);
  7066. }
  7067. void ByteCodeGenerator::EmitInvertedLoop(ParseNode* outerLoop, ParseNode* invertedLoop, FuncInfo* funcInfo)
  7068. {
  7069. Js::ByteCodeLabel invertedLoopLabel = this->m_writer.DefineLabel();
  7070. Js::ByteCodeLabel afterInvertedLoop = this->m_writer.DefineLabel();
  7071. // emit branch around original
  7072. Emit(outerLoop->sxFor.pnodeInit, this, funcInfo, false);
  7073. funcInfo->ReleaseLoc(outerLoop->sxFor.pnodeInit);
  7074. this->m_writer.BrS(Js::OpCode::BrNotHasSideEffects, invertedLoopLabel, Js::SideEffects_Any);
  7075. // emit original
  7076. EmitLoop(outerLoop, outerLoop->sxFor.pnodeCond, outerLoop->sxFor.pnodeBody,
  7077. outerLoop->sxFor.pnodeIncr, this, funcInfo, false);
  7078. // clear temporary registers since inverted loop may share nodes with
  7079. // emitted original loop
  7080. VisitClearTmpRegs(outerLoop, this, funcInfo);
  7081. // emit branch around inverted
  7082. this->m_writer.Br(afterInvertedLoop);
  7083. this->m_writer.MarkLabel(invertedLoopLabel);
  7084. // Emit a zero trip test for the original outer-loop
  7085. Js::ByteCodeLabel zeroTrip = this->m_writer.DefineLabel();
  7086. ParseNode* testNode = this->GetParser()->CopyPnode(outerLoop->sxFor.pnodeCond);
  7087. EmitBooleanExpression(testNode, zeroTrip, afterInvertedLoop, this, funcInfo);
  7088. this->m_writer.MarkLabel(zeroTrip);
  7089. funcInfo->ReleaseLoc(testNode);
  7090. // emit inverted
  7091. Emit(invertedLoop->sxFor.pnodeInit, this, funcInfo, false);
  7092. funcInfo->ReleaseLoc(invertedLoop->sxFor.pnodeInit);
  7093. EmitLoop(invertedLoop, invertedLoop->sxFor.pnodeCond, invertedLoop->sxFor.pnodeBody,
  7094. invertedLoop->sxFor.pnodeIncr, this, funcInfo, false);
  7095. this->m_writer.MarkLabel(afterInvertedLoop);
  7096. }
  7097. void EmitGetIterator(Js::RegSlot iteratorLocation, Js::RegSlot iterableLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  7098. {
  7099. // get iterator object from the iterable
  7100. EmitInvoke(iteratorLocation, iterableLocation, Js::PropertyIds::_symbolIterator, byteCodeGenerator, funcInfo);
  7101. // throw TypeError if the result is not an object
  7102. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  7103. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, skipThrow, iteratorLocation);
  7104. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_NeedObject));
  7105. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  7106. }
  7107. void EmitIteratorNext(Js::RegSlot itemLocation, Js::RegSlot iteratorLocation, Js::RegSlot nextInputLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  7108. {
  7109. // invoke next() on the iterator
  7110. if (nextInputLocation == Js::Constants::NoRegister)
  7111. {
  7112. EmitInvoke(itemLocation, iteratorLocation, Js::PropertyIds::next, byteCodeGenerator, funcInfo);
  7113. }
  7114. else
  7115. {
  7116. EmitInvoke(itemLocation, iteratorLocation, Js::PropertyIds::next, byteCodeGenerator, funcInfo, nextInputLocation);
  7117. }
  7118. // throw TypeError if the result is not an object
  7119. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  7120. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, skipThrow, itemLocation);
  7121. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_NeedObject));
  7122. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  7123. }
  7124. void EmitIteratorComplete(Js::RegSlot doneLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  7125. {
  7126. // get the iterator result's "done" property
  7127. uint cacheId = funcInfo->FindOrAddInlineCacheId(iteratorResultLocation, Js::PropertyIds::done, false, false);
  7128. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, doneLocation, iteratorResultLocation, cacheId);
  7129. // Do not need to do ToBoolean explicitly with current uses of EmitIteratorComplete since BrTrue_A does this.
  7130. // Add a ToBoolean controlled by template flag if needed for new uses later on.
  7131. }
  7132. void EmitIteratorValue(Js::RegSlot valueLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  7133. {
  7134. // get the iterator result's "value" property
  7135. uint cacheId = funcInfo->FindOrAddInlineCacheId(iteratorResultLocation, Js::PropertyIds::value, false, false);
  7136. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, valueLocation, iteratorResultLocation, cacheId);
  7137. }
  7138. void EmitForInOrForOf(ParseNode *loopNode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue)
  7139. {
  7140. bool isForIn = (loopNode->nop == knopForIn);
  7141. Assert(isForIn || loopNode->nop == knopForOf);
  7142. BeginEmitBlock(loopNode->sxForInOrForOf.pnodeBlock, byteCodeGenerator, funcInfo);
  7143. byteCodeGenerator->StartStatement(loopNode);
  7144. funcInfo->AcquireLoc(loopNode);
  7145. // Record the branch bytecode offset.
  7146. // This is used for "ignore exception" and "set next stmt" scenarios. See ProbeContainer::GetNextUserStatementOffsetForAdvance:
  7147. // If there is a branch recorded between current offset and next stmt offset, we'll use offset of the branch recorded,
  7148. // otherwise use offset of next stmt.
  7149. // The idea here is that when we bail out after ignore exception, we need to bail out to the beginning of the ForIn,
  7150. // but currently ForIn stmt starts at the condition part, which is needed for correct handling of break point on ForIn
  7151. // (break every time on the loop back edge) and correct display of current statement under debugger.
  7152. // See WinBlue 231880 for details.
  7153. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_All);
  7154. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled() &&
  7155. loopNode->sxForInOrForOf.pnodeBlock->sxBlock.HasBlockScopedContent())
  7156. {
  7157. byteCodeGenerator->Writer()->RecordForInOrOfCollectionScope();
  7158. }
  7159. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  7160. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  7161. Js::ByteCodeLabel skipPastLoop = byteCodeGenerator->Writer()->DefineLabel();
  7162. if (loopNode->sxForInOrForOf.pnodeLval->nop == knopVarDecl)
  7163. {
  7164. EmitReference(loopNode->sxForInOrForOf.pnodeLval, byteCodeGenerator, funcInfo);
  7165. }
  7166. Emit(loopNode->sxForInOrForOf.pnodeObj, byteCodeGenerator, funcInfo, false); // evaluate collection expression
  7167. funcInfo->ReleaseLoc(loopNode->sxForInOrForOf.pnodeObj);
  7168. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  7169. {
  7170. EndEmitBlock(loopNode->sxForInOrForOf.pnodeBlock, byteCodeGenerator, funcInfo);
  7171. if (loopNode->sxForInOrForOf.pnodeBlock->sxBlock.scope != nullptr)
  7172. {
  7173. loopNode->sxForInOrForOf.pnodeBlock->sxBlock.scope->ForEachSymbol([](Symbol *sym) {
  7174. sym->SetIsTrackedForDebugger(false);
  7175. });
  7176. }
  7177. }
  7178. // Grab registers for the enumerator and for the current enumerated item.
  7179. // The enumerator register will be released after this call returns.
  7180. loopNode->sxForInOrForOf.itemLocation = funcInfo->AcquireTmpRegister();
  7181. if (isForIn)
  7182. {
  7183. // get enumerator from the collection
  7184. byteCodeGenerator->Writer()->Reg2(Js::OpCode::GetForInEnumerator, loopNode->location, loopNode->sxForInOrForOf.pnodeObj->location);
  7185. }
  7186. else
  7187. {
  7188. // We want call profile information on the @@iterator call, so instead of adding a GetForOfIterator bytecode op
  7189. // to do all the following work in a helper do it explicitly in bytecode so that the @@iterator call is exposed
  7190. // to the profiler and JIT.
  7191. // If collection is null or undefined, don't enter the loop.
  7192. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, skipPastLoop, loopNode->sxForInOrForOf.pnodeObj->location, funcInfo->nullConstantRegister);
  7193. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, skipPastLoop, loopNode->sxForInOrForOf.pnodeObj->location, funcInfo->undefinedConstantRegister);
  7194. // do a ToObject on the collection
  7195. Js::RegSlot tmpObj = funcInfo->AcquireTmpRegister();
  7196. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Obj, tmpObj, loopNode->sxForInOrForOf.pnodeObj->location);
  7197. EmitGetIterator(loopNode->location, tmpObj, byteCodeGenerator, funcInfo);
  7198. funcInfo->ReleaseTmpRegister(tmpObj);
  7199. }
  7200. byteCodeGenerator->EndStatement(loopNode);
  7201. // Need to increment loop count whether we are going into profile or not for HasLoop()
  7202. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  7203. loopNode->sxForInOrForOf.loopId = loopId;
  7204. byteCodeGenerator->StartStatement(loopNode->sxForInOrForOf.pnodeLval);
  7205. if (isForIn)
  7206. {
  7207. // branch past loop when GetCurrentAndMoveNext returns nullptr
  7208. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrOnEmpty, continuePastLoop, loopNode->sxForInOrForOf.itemLocation, loopNode->location);
  7209. }
  7210. else
  7211. {
  7212. EmitIteratorNext(loopNode->sxForInOrForOf.itemLocation, loopNode->location, Js::Constants::NoRegister, byteCodeGenerator, funcInfo);
  7213. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  7214. EmitIteratorComplete(doneLocation, loopNode->sxForInOrForOf.itemLocation, byteCodeGenerator, funcInfo);
  7215. // branch past loop if the result's done property is truthy
  7216. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, continuePastLoop, doneLocation);
  7217. funcInfo->ReleaseTmpRegister(doneLocation);
  7218. // otherwise put result's value property in itemLocation
  7219. EmitIteratorValue(loopNode->sxForInOrForOf.itemLocation, loopNode->sxForInOrForOf.itemLocation, byteCodeGenerator, funcInfo);
  7220. }
  7221. if (loopNode->sxForInOrForOf.pnodeLval->nop != knopVarDecl &&
  7222. loopNode->sxForInOrForOf.pnodeLval->nop != knopLetDecl)
  7223. {
  7224. EmitReference(loopNode->sxForInOrForOf.pnodeLval, byteCodeGenerator, funcInfo);
  7225. }
  7226. else
  7227. {
  7228. Symbol * sym = loopNode->sxForInOrForOf.pnodeLval->sxVar.sym;
  7229. sym->SetNeedDeclaration(false);
  7230. }
  7231. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  7232. {
  7233. BeginEmitBlock(loopNode->sxForInOrForOf.pnodeBlock, byteCodeGenerator, funcInfo);
  7234. }
  7235. EmitAssignment(nullptr, loopNode->sxForInOrForOf.pnodeLval, loopNode->sxForInOrForOf.itemLocation, byteCodeGenerator, funcInfo);
  7236. byteCodeGenerator->EndStatement(loopNode->sxForInOrForOf.pnodeLval);
  7237. funcInfo->ReleaseReference(loopNode->sxForInOrForOf.pnodeLval);
  7238. Emit(loopNode->sxForInOrForOf.pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  7239. funcInfo->ReleaseLoc(loopNode->sxForInOrForOf.pnodeBody);
  7240. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  7241. {
  7242. EndEmitBlock(loopNode->sxForInOrForOf.pnodeBlock, byteCodeGenerator, funcInfo);
  7243. }
  7244. funcInfo->ReleaseTmpRegister(loopNode->sxForInOrForOf.itemLocation);
  7245. if (loopNode->emitLabels)
  7246. {
  7247. byteCodeGenerator->Writer()->MarkLabel(loopNode->sxForInOrForOf.continueLabel);
  7248. }
  7249. byteCodeGenerator->Writer()->Br(loopEntrance);
  7250. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  7251. if (loopNode->emitLabels)
  7252. {
  7253. byteCodeGenerator->Writer()->MarkLabel(loopNode->sxForInOrForOf.breakLabel);
  7254. }
  7255. byteCodeGenerator->Writer()->ExitLoop(loopId);
  7256. if (isForIn)
  7257. {
  7258. byteCodeGenerator->Writer()->Reg1(Js::OpCode::ReleaseForInEnumerator, loopNode->location);
  7259. }
  7260. else
  7261. {
  7262. byteCodeGenerator->Writer()->MarkLabel(skipPastLoop);
  7263. }
  7264. if (!byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  7265. {
  7266. EndEmitBlock(loopNode->sxForInOrForOf.pnodeBlock, byteCodeGenerator, funcInfo);
  7267. }
  7268. }
  7269. void EmitArrayLiteral(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7270. {
  7271. funcInfo->AcquireLoc(pnode);
  7272. ParseNode *args = pnode->sxUni.pnode1;
  7273. if (args == nullptr)
  7274. {
  7275. byteCodeGenerator->Writer()->Reg1Unsigned1(
  7276. pnode->sxArrLit.hasMissingValues ? Js::OpCode::NewScArrayWithMissingValues : Js::OpCode::NewScArray,
  7277. pnode->location,
  7278. ByteCodeGenerator::DefaultArraySize);
  7279. }
  7280. else
  7281. {
  7282. SetNewArrayElements(pnode, pnode->location, byteCodeGenerator, funcInfo);
  7283. }
  7284. }
  7285. void EmitJumpCleanup(ParseNode *pnode, ParseNode *pnodeTarget, ByteCodeGenerator *byteCodeGenerator, FuncInfo * funcInfo)
  7286. {
  7287. for (; pnode != pnodeTarget; pnode = pnode->sxStmt.pnodeOuter)
  7288. {
  7289. switch (pnode->nop)
  7290. {
  7291. case knopTry:
  7292. case knopCatch:
  7293. case knopFinally:
  7294. // We insert OpCode::Leave when there is a 'return' inside try/catch/finally.
  7295. // This is for flow control and does not participate in identifying boundaries of try/catch blocks,
  7296. // thus we shouldn't call RecordCrossFrameEntryExitRecord() here.
  7297. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  7298. break;
  7299. #if ENABLE_PROFILE_INFO
  7300. case knopWhile:
  7301. case knopDoWhile:
  7302. case knopFor:
  7303. case knopForIn:
  7304. case knopForOf:
  7305. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(funcInfo->GetParsedFunctionBody()))
  7306. {
  7307. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::ProfiledLoopEnd, pnode->sxLoop.loopId);
  7308. }
  7309. #endif
  7310. }
  7311. }
  7312. }
  7313. void EmitBinaryOpnds(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7314. {
  7315. // If opnd2 can overwrite opnd1, make sure the value of opnd1 is stashed away.
  7316. if (MayHaveSideEffectOnNode(pnode1, pnode2))
  7317. {
  7318. SaveOpndValue(pnode1, funcInfo);
  7319. }
  7320. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  7321. if (pnode1->nop == knopComputedName && pnode2->nop == knopClassDecl &&
  7322. (pnode2->sxClass.pnodeConstructor == nullptr || pnode2->sxClass.pnodeConstructor->nop != knopVarDecl))
  7323. {
  7324. Emit(pnode2, byteCodeGenerator, funcInfo, false, false, pnode1);
  7325. }
  7326. else
  7327. {
  7328. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  7329. }
  7330. }
  7331. void EmitBinaryReference(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fLoadLhs)
  7332. {
  7333. // Make sure that the RHS of an assignment doesn't kill the opnd's of the expression on the LHS.
  7334. switch (pnode1->nop)
  7335. {
  7336. case knopName:
  7337. if (fLoadLhs && MayHaveSideEffectOnNode(pnode1, pnode2))
  7338. {
  7339. // Given x op y, y may kill x, so stash x.
  7340. // Note that this only matters if we're loading x prior to the op.
  7341. SaveOpndValue(pnode1, funcInfo);
  7342. }
  7343. break;
  7344. case knopDot:
  7345. if (fLoadLhs)
  7346. {
  7347. // We're loading the value of the LHS before the RHS, so make sure the LHS gets a register first.
  7348. funcInfo->AcquireLoc(pnode1);
  7349. }
  7350. if (MayHaveSideEffectOnNode(pnode1->sxBin.pnode1, pnode2))
  7351. {
  7352. // Given x.y op z, z may kill x, so stash x away.
  7353. SaveOpndValue(pnode1->sxBin.pnode1, funcInfo);
  7354. }
  7355. break;
  7356. case knopIndex:
  7357. if (fLoadLhs)
  7358. {
  7359. // We're loading the value of the LHS before the RHS, so make sure the LHS gets a register first.
  7360. funcInfo->AcquireLoc(pnode1);
  7361. }
  7362. if (MayHaveSideEffectOnNode(pnode1->sxBin.pnode1, pnode2) ||
  7363. MayHaveSideEffectOnNode(pnode1->sxBin.pnode1, pnode1->sxBin.pnode2))
  7364. {
  7365. // Given x[y] op z, y or z may kill x, so stash x away.
  7366. SaveOpndValue(pnode1->sxBin.pnode1, funcInfo);
  7367. }
  7368. if (MayHaveSideEffectOnNode(pnode1->sxBin.pnode2, pnode2))
  7369. {
  7370. // Given x[y] op z, z may kill y, so stash y away.
  7371. // But make sure that x gets a register before y.
  7372. funcInfo->AcquireLoc(pnode1->sxBin.pnode1);
  7373. SaveOpndValue(pnode1->sxBin.pnode2, funcInfo);
  7374. }
  7375. break;
  7376. }
  7377. if (fLoadLhs)
  7378. {
  7379. // Emit code to load the value of the LHS.
  7380. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  7381. }
  7382. else
  7383. {
  7384. // Emit code to evaluate the LHS opnds, but don't load the LHS's value.
  7385. EmitReference(pnode1, byteCodeGenerator, funcInfo);
  7386. }
  7387. // Evaluate the RHS.
  7388. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  7389. }
  7390. void EmitUseBeforeDeclarationRuntimeError(ByteCodeGenerator * byteCodeGenerator, Js::RegSlot location, bool fLoadUndef)
  7391. {
  7392. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_UseBeforeDeclaration));
  7393. // Load something into register in order to do not confuse IRBuilder. This value will never be used.
  7394. if (fLoadUndef)
  7395. {
  7396. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, location);
  7397. }
  7398. }
  7399. bool EmitUseBeforeDeclaration(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7400. {
  7401. Symbol *sym = nullptr;
  7402. bool fAcquireLoc = true;
  7403. if (pnode->nop == knopName)
  7404. {
  7405. sym = pnode->sxPid.sym;
  7406. }
  7407. else if (pnode->nop == knopVarDecl)
  7408. {
  7409. fAcquireLoc = false;
  7410. sym = pnode->sxVar.sym;
  7411. }
  7412. else if ((ParseNode::Grfnop(pnode->nop) & fnopAsg) != 0)
  7413. {
  7414. if ((ParseNode::Grfnop(pnode->nop) & fnopBin) != 0 && pnode->sxBin.pnode1->nop == knopName)
  7415. {
  7416. sym = pnode->sxBin.pnode1->sxPid.sym;
  7417. }
  7418. if ((ParseNode::Grfnop(pnode->nop) & fnopUni) != 0 && pnode->sxUni.pnode1->nop == knopName)
  7419. {
  7420. sym = pnode->sxUni.pnode1->sxPid.sym;
  7421. }
  7422. }
  7423. // Don't emit static use-before-declaration error in a closure or dynamic scope case. We detect such cases with dynamic checks,
  7424. // if necessary.
  7425. if (sym != nullptr && sym->GetNeedDeclaration() && byteCodeGenerator->GetCurrentScope()->HasStaticPathToAncestor(sym->GetScope()) && sym->GetScope()->GetFunc() == funcInfo)
  7426. {
  7427. if (fAcquireLoc)
  7428. {
  7429. funcInfo->AcquireLoc(pnode);
  7430. }
  7431. EmitUseBeforeDeclarationRuntimeError(byteCodeGenerator, pnode->location, fAcquireLoc);
  7432. return true;
  7433. }
  7434. return false;
  7435. }
  7436. void EmitBinary(Js::OpCode opcode, ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7437. {
  7438. byteCodeGenerator->StartStatement(pnode);
  7439. EmitBinaryOpnds(pnode->sxBin.pnode1, pnode->sxBin.pnode2, byteCodeGenerator, funcInfo);
  7440. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  7441. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  7442. funcInfo->AcquireLoc(pnode);
  7443. byteCodeGenerator->Writer()->Reg3(opcode,
  7444. pnode->location,
  7445. pnode->sxBin.pnode1->location,
  7446. pnode->sxBin.pnode2->location);
  7447. byteCodeGenerator->EndStatement(pnode);
  7448. }
  7449. bool CollectConcat(ParseNode *pnodeAdd, DListCounted<ParseNode *, ArenaAllocator>& concatOpnds, ArenaAllocator *arenaAllocator)
  7450. {
  7451. Assert(pnodeAdd->nop == knopAdd);
  7452. Assert(pnodeAdd->CanFlattenConcatExpr());
  7453. bool doConcatString = false;
  7454. DList<ParseNode*, ArenaAllocator> pnodeStack(arenaAllocator);
  7455. pnodeStack.Prepend(pnodeAdd->sxBin.pnode2);
  7456. ParseNode * pnode = pnodeAdd->sxBin.pnode1;
  7457. while (true)
  7458. {
  7459. if (!pnode->CanFlattenConcatExpr())
  7460. {
  7461. concatOpnds.Append(pnode);
  7462. }
  7463. else if (pnode->nop == knopStr)
  7464. {
  7465. concatOpnds.Append(pnode);
  7466. // Detect if there are any string larger then the append size limit.
  7467. // If there are, we can do concat; otherwise, still use add so we will not lose the AddLeftDead opportunities.
  7468. doConcatString = doConcatString || !Js::CompoundString::ShouldAppendChars(pnode->sxPid.pid->Cch());
  7469. }
  7470. else
  7471. {
  7472. Assert(pnode->nop == knopAdd);
  7473. pnodeStack.Prepend(pnode->sxBin.pnode2);
  7474. pnode = pnode->sxBin.pnode1;
  7475. continue;
  7476. }
  7477. if (pnodeStack.Empty())
  7478. {
  7479. break;
  7480. }
  7481. pnode = pnodeStack.Head();
  7482. pnodeStack.RemoveHead();
  7483. }
  7484. return doConcatString;
  7485. }
  7486. void EmitConcat3(ParseNode *pnode, ParseNode *pnode1, ParseNode *pnode2, ParseNode *pnode3, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7487. {
  7488. byteCodeGenerator->StartStatement(pnode);
  7489. if (MayHaveSideEffectOnNode(pnode1, pnode2) || MayHaveSideEffectOnNode(pnode1, pnode3))
  7490. {
  7491. SaveOpndValue(pnode1, funcInfo);
  7492. }
  7493. if (MayHaveSideEffectOnNode(pnode2, pnode3))
  7494. {
  7495. SaveOpndValue(pnode2, funcInfo);
  7496. }
  7497. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  7498. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  7499. Emit(pnode3, byteCodeGenerator, funcInfo, false);
  7500. funcInfo->ReleaseLoc(pnode3);
  7501. funcInfo->ReleaseLoc(pnode2);
  7502. funcInfo->ReleaseLoc(pnode1);
  7503. funcInfo->AcquireLoc(pnode);
  7504. byteCodeGenerator->Writer()->Reg4(Js::OpCode::Concat3,
  7505. pnode->location,
  7506. pnode1->location,
  7507. pnode2->location,
  7508. pnode3->location);
  7509. byteCodeGenerator->EndStatement(pnode);
  7510. }
  7511. void EmitNewConcatStrMulti(ParseNode *pnode, uint8 count, ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7512. {
  7513. EmitBinaryOpnds(pnode1, pnode2, byteCodeGenerator, funcInfo);
  7514. funcInfo->ReleaseLoc(pnode2);
  7515. funcInfo->ReleaseLoc(pnode1);
  7516. funcInfo->AcquireLoc(pnode);
  7517. byteCodeGenerator->Writer()->Reg3B1(Js::OpCode::NewConcatStrMulti,
  7518. pnode->location,
  7519. pnode1->location,
  7520. pnode2->location,
  7521. count);
  7522. }
  7523. void EmitAdd(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7524. {
  7525. Assert(pnode->nop == knopAdd);
  7526. if (pnode->CanFlattenConcatExpr())
  7527. {
  7528. // We should only have a string concat if the feature is on.
  7529. Assert(!PHASE_OFF1(Js::ByteCodeConcatExprOptPhase));
  7530. DListCounted<ParseNode*, ArenaAllocator> concatOpnds(byteCodeGenerator->GetAllocator());
  7531. bool doConcatString = CollectConcat(pnode, concatOpnds, byteCodeGenerator->GetAllocator());
  7532. if (doConcatString)
  7533. {
  7534. uint concatCount = concatOpnds.Count();
  7535. Assert(concatCount >= 2);
  7536. // Don't do concatN if the number is too high
  7537. // CONSIDER: although we could have done multiple ConcatNs
  7538. if (concatCount > 2 && concatCount <= UINT8_MAX)
  7539. {
  7540. #if DBG
  7541. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  7542. #endif
  7543. ParseNode * pnode1 = concatOpnds.Head();
  7544. concatOpnds.RemoveHead();
  7545. ParseNode * pnode2 = concatOpnds.Head();
  7546. concatOpnds.RemoveHead();
  7547. if (concatCount == 3)
  7548. {
  7549. OUTPUT_TRACE_DEBUGONLY(Js::ByteCodeConcatExprOptPhase, L"%s(%s) offset:#%d : Concat3\n",
  7550. funcInfo->GetParsedFunctionBody()->GetDisplayName(),
  7551. funcInfo->GetParsedFunctionBody()->GetDebugNumberSet(debugStringBuffer),
  7552. byteCodeGenerator->Writer()->ByteCodeDataSize());
  7553. EmitConcat3(pnode, pnode1, pnode2, concatOpnds.Head(), byteCodeGenerator, funcInfo);
  7554. return;
  7555. }
  7556. OUTPUT_TRACE_DEBUGONLY(Js::ByteCodeConcatExprOptPhase, L"%s(%s) offset:#%d: ConcatMulti %d\n",
  7557. funcInfo->GetParsedFunctionBody()->GetDisplayName(),
  7558. funcInfo->GetParsedFunctionBody()->GetDebugNumberSet(debugStringBuffer),
  7559. byteCodeGenerator->Writer()->ByteCodeDataSize(), concatCount);
  7560. byteCodeGenerator->StartStatement(pnode);
  7561. funcInfo->AcquireLoc(pnode);
  7562. // CONSIDER: this may cause the backend not able CSE repeating pattern within the concat.
  7563. EmitNewConcatStrMulti(pnode, (uint8)concatCount, pnode1, pnode2, byteCodeGenerator, funcInfo);
  7564. uint i = 2;
  7565. do
  7566. {
  7567. ParseNode * currNode = concatOpnds.Head();
  7568. concatOpnds.RemoveHead();
  7569. ParseNode * currNode2 = concatOpnds.Head();
  7570. concatOpnds.RemoveHead();
  7571. EmitBinaryOpnds(currNode, currNode2, byteCodeGenerator, funcInfo);
  7572. funcInfo->ReleaseLoc(currNode2);
  7573. funcInfo->ReleaseLoc(currNode);
  7574. byteCodeGenerator->Writer()->Reg3B1(
  7575. Js::OpCode::SetConcatStrMultiItem2, pnode->location, currNode->location, currNode2->location, (uint8)i);
  7576. i += 2;
  7577. }
  7578. while (concatOpnds.Count() > 1);
  7579. if (!concatOpnds.Empty())
  7580. {
  7581. ParseNode * currNode = concatOpnds.Head();
  7582. Emit(currNode, byteCodeGenerator, funcInfo, false);
  7583. funcInfo->ReleaseLoc(currNode);
  7584. byteCodeGenerator->Writer()->Reg2B1(
  7585. Js::OpCode::SetConcatStrMultiItem, pnode->location, currNode->location, (uint8)i);
  7586. i++;
  7587. }
  7588. Assert(concatCount == i);
  7589. byteCodeGenerator->EndStatement(pnode);
  7590. return;
  7591. }
  7592. }
  7593. // Since we collected all the node already, let's just emit them instead of doing it recursively.
  7594. byteCodeGenerator->StartStatement(pnode);
  7595. ParseNode * currNode = concatOpnds.Head();
  7596. concatOpnds.RemoveHead();
  7597. ParseNode * currNode2 = concatOpnds.Head();
  7598. concatOpnds.RemoveHead();
  7599. EmitBinaryOpnds(currNode, currNode2, byteCodeGenerator, funcInfo);
  7600. funcInfo->ReleaseLoc(currNode2);
  7601. funcInfo->ReleaseLoc(currNode);
  7602. Js::RegSlot dstReg = funcInfo->AcquireLoc(pnode);
  7603. byteCodeGenerator->Writer()->Reg3(
  7604. Js::OpCode::Add_A, dstReg, currNode->location, currNode2->location);
  7605. while (!concatOpnds.Empty())
  7606. {
  7607. currNode = concatOpnds.Head();
  7608. concatOpnds.RemoveHead();
  7609. Emit(currNode, byteCodeGenerator, funcInfo, false);
  7610. funcInfo->ReleaseLoc(currNode);
  7611. byteCodeGenerator->Writer()->Reg3(
  7612. Js::OpCode::Add_A, dstReg, dstReg, currNode->location);
  7613. }
  7614. byteCodeGenerator->EndStatement(pnode);
  7615. }
  7616. else
  7617. {
  7618. EmitBinary(Js::OpCode::Add_A, pnode, byteCodeGenerator, funcInfo);
  7619. }
  7620. }
  7621. void EmitSuperFieldPatch(FuncInfo* funcInfo, ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator)
  7622. {
  7623. ParseNodePtr propFuncNode = funcInfo->root;
  7624. if (byteCodeGenerator->GetFlags() & fscrEval)
  7625. {
  7626. // If we are inside an eval, ScopedLdSuper will take care of the patch.
  7627. return;
  7628. }
  7629. if (funcInfo->IsLambda())
  7630. {
  7631. FuncInfo *parent = byteCodeGenerator->FindEnclosingNonLambda();
  7632. propFuncNode = parent->root;
  7633. }
  7634. // No need to emit a LdFld for the constructor.
  7635. if (propFuncNode->sxFnc.IsClassConstructor())
  7636. {
  7637. return;
  7638. }
  7639. if (!propFuncNode->sxFnc.IsClassMember() || propFuncNode->sxFnc.pid == nullptr)
  7640. {
  7641. // Non-methods will fail lookup.
  7642. return;
  7643. }
  7644. if (propFuncNode->sxFnc.pid->GetPropertyId() == Js::Constants::NoProperty)
  7645. {
  7646. byteCodeGenerator->AssignPropertyId(propFuncNode->sxFnc.pid);
  7647. }
  7648. // Load the current method's property ID from super instead of using super directly.
  7649. Js::RegSlot superLoc = funcInfo->superRegister;
  7650. pnode->sxCall.pnodeTarget->location = Js::Constants::NoRegister;
  7651. Js::RegSlot superPropLoc = funcInfo->AcquireLoc(pnode->sxCall.pnodeTarget);
  7652. Js::PropertyId propertyId = propFuncNode->sxFnc.pid->GetPropertyId();
  7653. uint cacheId = funcInfo->FindOrAddInlineCacheId(superLoc, propertyId, true, false);
  7654. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdMethodFld, superPropLoc, superLoc, cacheId);
  7655. propFuncNode->sxFnc.pnodeName = nullptr;
  7656. }
  7657. struct ByteCodeGenerator::TryScopeRecord : public JsUtil::DoublyLinkedListElement<TryScopeRecord>
  7658. {
  7659. Js::OpCode op;
  7660. Js::ByteCodeLabel label;
  7661. Js::RegSlot reg1;
  7662. Js::RegSlot reg2;
  7663. TryScopeRecord(Js::OpCode op, Js::ByteCodeLabel label) : op(op), label(label), reg1(Js::Constants::NoRegister), reg2(Js::Constants::NoRegister) { }
  7664. TryScopeRecord(Js::OpCode op, Js::ByteCodeLabel label, Js::RegSlot r1, Js::RegSlot r2) : op(op), label(label), reg1(r1), reg2(r2) { }
  7665. };
  7666. void ByteCodeGenerator::EmitLeaveOpCodesBeforeYield()
  7667. {
  7668. for (TryScopeRecord* node = this->tryScopeRecordsList.Tail(); node != nullptr; node = node->Previous())
  7669. {
  7670. switch (node->op)
  7671. {
  7672. case Js::OpCode::TryFinallyWithYield:
  7673. this->Writer()->Empty(Js::OpCode::LeaveNull);
  7674. break;
  7675. case Js::OpCode::TryCatch:
  7676. case Js::OpCode::ResumeFinally:
  7677. case Js::OpCode::ResumeCatch:
  7678. this->Writer()->Empty(Js::OpCode::Leave);
  7679. break;
  7680. default:
  7681. AssertMsg(false, "Unexpected OpCode before Yield in the Try-Catch-Finally cache for generator!");
  7682. break;
  7683. }
  7684. }
  7685. }
  7686. void ByteCodeGenerator::EmitTryBlockHeadersAfterYield()
  7687. {
  7688. for (TryScopeRecord* node = this->tryScopeRecordsList.Head(); node != nullptr; node = node->Next())
  7689. {
  7690. switch (node->op)
  7691. {
  7692. case Js::OpCode::TryCatch:
  7693. this->Writer()->Br(node->op, node->label);
  7694. break;
  7695. case Js::OpCode::TryFinallyWithYield:
  7696. case Js::OpCode::ResumeFinally:
  7697. this->Writer()->BrReg2(node->op, node->label, node->reg1, node->reg2);
  7698. break;
  7699. case Js::OpCode::ResumeCatch:
  7700. this->Writer()->Empty(node->op);
  7701. break;
  7702. default:
  7703. AssertMsg(false, "Unexpected OpCode after yield in the Try-Catch-Finally cache for generator!");
  7704. break;
  7705. }
  7706. }
  7707. }
  7708. void EmitYield(Js::RegSlot inputLocation, Js::RegSlot resultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo,
  7709. Js::RegSlot yieldStarIterator = Js::Constants::NoRegister)
  7710. {
  7711. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, funcInfo->yieldRegister, inputLocation);
  7712. byteCodeGenerator->EmitLeaveOpCodesBeforeYield();
  7713. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Yield, funcInfo->yieldRegister, funcInfo->yieldRegister);
  7714. byteCodeGenerator->EmitTryBlockHeadersAfterYield();
  7715. if (yieldStarIterator == Js::Constants::NoRegister)
  7716. {
  7717. byteCodeGenerator->Writer()->Reg2(Js::OpCode::ResumeYield, resultLocation, funcInfo->yieldRegister);
  7718. }
  7719. else
  7720. {
  7721. byteCodeGenerator->Writer()->Reg3(Js::OpCode::ResumeYieldStar, resultLocation, funcInfo->yieldRegister, yieldStarIterator);
  7722. }
  7723. }
  7724. void EmitYieldStar(ParseNode* yieldStarNode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  7725. {
  7726. funcInfo->AcquireLoc(yieldStarNode);
  7727. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  7728. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  7729. Js::RegSlot iteratorLocation = funcInfo->AcquireTmpRegister();
  7730. // Evaluate operand
  7731. Emit(yieldStarNode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  7732. funcInfo->ReleaseLoc(yieldStarNode->sxUni.pnode1);
  7733. EmitGetIterator(iteratorLocation, yieldStarNode->sxUni.pnode1->location, byteCodeGenerator, funcInfo);
  7734. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  7735. // since a yield* doesn't have a user defined body, we cannot return from this loop
  7736. // which means we don't need to support EmitJumpCleanup() and there do not need to
  7737. // remember the loopId like the loop statements do.
  7738. // Get a temporary to hold the input for the next() calls. Initialize it to undefined for the first call.
  7739. Js::RegSlot nextInputLocation = funcInfo->AcquireTmpRegister();
  7740. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, nextInputLocation, funcInfo->undefinedConstantRegister);
  7741. // Call the iterator's next()
  7742. EmitIteratorNext(yieldStarNode->location, iteratorLocation, nextInputLocation, byteCodeGenerator, funcInfo);
  7743. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  7744. EmitIteratorComplete(doneLocation, yieldStarNode->location, byteCodeGenerator, funcInfo);
  7745. // Put the iterator result's value in yieldStarNode->location regardless of the done property value. The value will
  7746. // be used as the result value of the yield* operator expression in the case when done is true.
  7747. EmitIteratorValue(yieldStarNode->location, yieldStarNode->location, byteCodeGenerator, funcInfo);
  7748. // branch past the loop if the done property is truthy
  7749. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, continuePastLoop, doneLocation);
  7750. funcInfo->ReleaseTmpRegister(doneLocation);
  7751. EmitYield(yieldStarNode->location, nextInputLocation, byteCodeGenerator, funcInfo, iteratorLocation);
  7752. funcInfo->ReleaseTmpRegister(nextInputLocation);
  7753. funcInfo->ReleaseTmpRegister(iteratorLocation);
  7754. byteCodeGenerator->Writer()->Br(loopEntrance);
  7755. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  7756. byteCodeGenerator->Writer()->ExitLoop(loopId);
  7757. }
  7758. void TrackIntConstantsOnGlobalUserObject(ByteCodeGenerator *byteCodeGenerator, bool isSymGlobalAndSingleAssignment, Js::PropertyId propertyId)
  7759. {
  7760. if (isSymGlobalAndSingleAssignment)
  7761. {
  7762. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalUserObject(propertyId);
  7763. }
  7764. }
  7765. void TrackIntConstantsOnGlobalObject(ByteCodeGenerator *byteCodeGenerator, bool isSymGlobalAndSingleAssignment, Js::PropertyId propertyId)
  7766. {
  7767. if (isSymGlobalAndSingleAssignment)
  7768. {
  7769. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalObject(propertyId);
  7770. }
  7771. }
  7772. void TrackIntConstantsOnGlobalObject(ByteCodeGenerator *byteCodeGenerator, Symbol *sym)
  7773. {
  7774. if (sym && sym->GetIsGlobal() && sym->IsAssignedOnce())
  7775. {
  7776. Js::PropertyId propertyId = sym->EnsurePosition(byteCodeGenerator);
  7777. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalObject(propertyId);
  7778. }
  7779. }
  7780. void TrackMemberNodesInObjectForIntConstants(ByteCodeGenerator *byteCodeGenerator, ParseNodePtr objNode)
  7781. {
  7782. Assert(objNode->nop == knopObject);
  7783. Assert(ParseNode::Grfnop(objNode->nop) & fnopUni);
  7784. ParseNodePtr memberList = objNode->sxUni.pnode1;
  7785. if (memberList != nullptr)
  7786. {
  7787. // Iterate through all the member nodes
  7788. while (memberList->nop == knopList)
  7789. {
  7790. ParseNodePtr memberNode = memberList->sxBin.pnode1;
  7791. ParseNodePtr memberNameNode = memberNode->sxBin.pnode1;
  7792. ParseNodePtr memberValNode = memberNode->sxBin.pnode2;
  7793. if (memberNameNode->nop != knopComputedName && memberValNode->nop == knopInt)
  7794. {
  7795. Js::PropertyId propertyId = memberNameNode->sxPid.PropertyIdFromNameNode();
  7796. TrackIntConstantsOnGlobalUserObject(byteCodeGenerator, true, propertyId);
  7797. }
  7798. memberList = memberList->sxBin.pnode2;
  7799. }
  7800. ParseNode *memberNameNode = memberList->sxBin.pnode1;
  7801. ParseNode *memberValNode = memberList->sxBin.pnode2;
  7802. if (memberNameNode->nop != knopComputedName && memberValNode->nop == knopInt)
  7803. {
  7804. Js::PropertyId propertyId = memberNameNode->sxPid.PropertyIdFromNameNode();
  7805. TrackIntConstantsOnGlobalUserObject(byteCodeGenerator, true, propertyId);
  7806. }
  7807. }
  7808. }
  7809. void TrackGlobalIntAssignmentsForknopDotProps(ParseNodePtr knopDotNode, ByteCodeGenerator * byteCodeGenerator)
  7810. {
  7811. Assert(knopDotNode->nop == knopDot);
  7812. ParseNodePtr objectNode = knopDotNode->sxBin.pnode1;
  7813. ParseNodePtr propertyNode = knopDotNode->sxBin.pnode2;
  7814. bool isSymGlobalAndSingleAssignment = false;
  7815. if (objectNode->nop == knopName)
  7816. {
  7817. Symbol * sym = objectNode->sxVar.sym;
  7818. isSymGlobalAndSingleAssignment = sym && sym->GetIsGlobal() && sym->IsAssignedOnce() && propertyNode->sxPid.pid->IsSingleAssignment();
  7819. Js::PropertyId propertyId = propertyNode->sxPid.PropertyIdFromNameNode();
  7820. TrackIntConstantsOnGlobalUserObject(byteCodeGenerator, isSymGlobalAndSingleAssignment, propertyId);
  7821. }
  7822. else if (objectNode->nop == knopThis)
  7823. {
  7824. // Assume knopThis always refer to GlobalObject
  7825. // Cases like "this.a = "
  7826. isSymGlobalAndSingleAssignment = propertyNode->sxPid.pid->IsSingleAssignment();
  7827. Js::PropertyId propertyId = propertyNode->sxPid.PropertyIdFromNameNode();
  7828. TrackIntConstantsOnGlobalObject(byteCodeGenerator, isSymGlobalAndSingleAssignment, propertyId);
  7829. }
  7830. }
  7831. void TrackGlobalIntAssignments(ParseNodePtr pnode, ByteCodeGenerator * byteCodeGenerator)
  7832. {
  7833. // Track the Global Int Constant properties' assignments here.
  7834. uint nodeType = ParseNode::Grfnop(pnode->nop);
  7835. if (nodeType & fnopAsg)
  7836. {
  7837. if (nodeType & fnopBin)
  7838. {
  7839. ParseNodePtr lhs = pnode->sxBin.pnode1;
  7840. ParseNodePtr rhs = pnode->sxBin.pnode2;
  7841. Assert(lhs && rhs);
  7842. // Don't track other than integers and objects with member nodes.
  7843. if (rhs->nop == knopObject && (ParseNode::Grfnop(rhs->nop) & fnopUni))
  7844. {
  7845. TrackMemberNodesInObjectForIntConstants(byteCodeGenerator, rhs);
  7846. }
  7847. else if (rhs->nop != knopInt &&
  7848. ((rhs->nop != knopLsh && rhs->nop != knopRsh) || (rhs->sxBin.pnode1->nop != knopInt || rhs->sxBin.pnode2->nop != knopInt)))
  7849. {
  7850. return;
  7851. }
  7852. if (lhs->nop == knopName)
  7853. {
  7854. // Handle "a = <Integer>" cases here
  7855. Symbol * sym = lhs->sxVar.sym;
  7856. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  7857. }
  7858. else if (lhs->nop == knopDot && lhs->sxBin.pnode2->nop == knopName)
  7859. {
  7860. // Cases like "obj.a = <Integer>"
  7861. TrackGlobalIntAssignmentsForknopDotProps(lhs, byteCodeGenerator);
  7862. }
  7863. }
  7864. else if (nodeType & fnopUni)
  7865. {
  7866. ParseNodePtr lhs = pnode->sxUni.pnode1;
  7867. if (lhs->nop == knopName)
  7868. {
  7869. // Cases like "a++"
  7870. Symbol * sym = lhs->sxVar.sym;
  7871. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  7872. }
  7873. else if (lhs->nop == knopDot && lhs->sxBin.pnode2->nop == knopName)
  7874. {
  7875. // Cases like "obj.a++"
  7876. TrackGlobalIntAssignmentsForknopDotProps(lhs, byteCodeGenerator);
  7877. }
  7878. }
  7879. }
  7880. }
  7881. void Emit(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue, bool isConstructorCall, ParseNode * bindPnode)
  7882. {
  7883. if (pnode == nullptr)
  7884. {
  7885. return;
  7886. }
  7887. if (EmitUseBeforeDeclaration(pnode, byteCodeGenerator, funcInfo))
  7888. {
  7889. if (fReturnValue && IsExpressionStatement(pnode, byteCodeGenerator->GetScriptContext()))
  7890. {
  7891. // If this statement may produce the global function's return value, make sure we load something to the
  7892. // return register for the JIT.
  7893. // fReturnValue implies global function, which implies that "return" is a parse error.
  7894. Assert(funcInfo->IsGlobalFunction());
  7895. Assert(pnode->nop != knopReturn);
  7896. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, ByteCodeGenerator::ReturnRegister);
  7897. }
  7898. return;
  7899. }
  7900. ThreadContext::ProbeCurrentStackNoDispose(Js::Constants::MinStackByteCodeVisitor, byteCodeGenerator->GetScriptContext());
  7901. TrackGlobalIntAssignments(pnode, byteCodeGenerator);
  7902. // printNop(pnode->nop);
  7903. switch (pnode->nop)
  7904. {
  7905. case knopList:
  7906. EmitList(pnode, byteCodeGenerator, funcInfo);
  7907. break;
  7908. case knopInt:
  7909. // currently, these are loaded at the top
  7910. break;
  7911. // PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  7912. case knopFlt:
  7913. // currently, these are loaded at the top
  7914. break;
  7915. // PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  7916. case knopStr:
  7917. // TODO: protocol for combining string constants
  7918. break;
  7919. // PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  7920. case knopRegExp:
  7921. funcInfo->GetParsedFunctionBody()->SetLiteralRegex(pnode->sxPid.regexPatternIndex, pnode->sxPid.regexPattern);
  7922. byteCodeGenerator->Writer()->Reg1Unsigned1(Js::OpCode::NewRegEx, funcInfo->AcquireLoc(pnode), pnode->sxPid.regexPatternIndex);
  7923. break; // PTNODE(knopThis , "this" ,None ,None ,fnopLeaf)
  7924. case knopThis:
  7925. // enregistered
  7926. // Try to load 'this' from a scope slot if we are in a derived class constructor with scope slots. Otherwise, this is a nop.
  7927. byteCodeGenerator->EmitScopeSlotLoadThis(funcInfo, funcInfo->thisPointerRegister);
  7928. break;
  7929. // PTNODE(knopNewTarget , "new.target" ,None , None , fnopLeaf)
  7930. case knopNewTarget:
  7931. break;
  7932. // PTNODE(knopSuper , "super" ,None , None , fnopLeaf)
  7933. case knopSuper:
  7934. if (!funcInfo->IsClassMember())
  7935. {
  7936. FuncInfo* nonLambdaFunc = funcInfo;
  7937. if (funcInfo->IsLambda())
  7938. {
  7939. nonLambdaFunc = byteCodeGenerator->FindEnclosingNonLambda();
  7940. }
  7941. if (nonLambdaFunc->IsGlobalFunction())
  7942. {
  7943. if ((byteCodeGenerator->GetFlags() & fscrEval))
  7944. {
  7945. byteCodeGenerator->Writer()->Reg1(isConstructorCall ? Js::OpCode::ScopedLdSuperCtor : Js::OpCode::ScopedLdSuper, funcInfo->AcquireLoc(pnode));
  7946. }
  7947. else
  7948. {
  7949. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_BadSuperReference));
  7950. }
  7951. }
  7952. else
  7953. {
  7954. Js::ByteCodeLabel errLabel = byteCodeGenerator->Writer()->DefineLabel();
  7955. Js::ByteCodeLabel skipLabel = byteCodeGenerator->Writer()->DefineLabel();
  7956. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrEq_A, errLabel, funcInfo->superRegister, funcInfo->undefinedConstantRegister);
  7957. byteCodeGenerator->Writer()->Br(Js::OpCode::Br, skipLabel);
  7958. byteCodeGenerator->Writer()->MarkLabel(errLabel);
  7959. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_BadSuperReference));
  7960. byteCodeGenerator->Writer()->MarkLabel(skipLabel);
  7961. }
  7962. }
  7963. break;
  7964. // PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  7965. case knopNull:
  7966. // enregistered
  7967. break;
  7968. // PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  7969. case knopFalse:
  7970. // enregistered
  7971. break;
  7972. // PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  7973. case knopTrue:
  7974. // enregistered
  7975. break;
  7976. // PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  7977. case knopEmpty:
  7978. break;
  7979. // Unary operators.
  7980. // PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  7981. case knopNot:
  7982. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  7983. funcInfo->ReleaseLoc(pnode->sxUni.pnode1);
  7984. byteCodeGenerator->Writer()->Reg2(
  7985. Js::OpCode::Not_A, funcInfo->AcquireLoc(pnode), pnode->sxUni.pnode1->location);
  7986. break;
  7987. // PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  7988. case knopNeg:
  7989. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  7990. funcInfo->ReleaseLoc(pnode->sxUni.pnode1);
  7991. funcInfo->AcquireLoc(pnode);
  7992. byteCodeGenerator->Writer()->Reg2(
  7993. Js::OpCode::Neg_A, pnode->location, pnode->sxUni.pnode1->location);
  7994. break;
  7995. // PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  7996. case knopPos:
  7997. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  7998. funcInfo->ReleaseLoc(pnode->sxUni.pnode1);
  7999. byteCodeGenerator->Writer()->Reg2(
  8000. Js::OpCode::Conv_Num, funcInfo->AcquireLoc(pnode), pnode->sxUni.pnode1->location);
  8001. break;
  8002. // PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  8003. case knopLogNot:
  8004. {
  8005. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  8006. // For boolean expressions that compute a result, we have to burn a register for the result
  8007. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  8008. // full-on renaming in the back end.
  8009. funcInfo->AcquireLoc(pnode);
  8010. if (pnode->sxUni.pnode1->nop == knopInt)
  8011. {
  8012. long value = pnode->sxUni.pnode1->sxInt.lw;
  8013. Js::OpCode op = value ? Js::OpCode::LdFalse : Js::OpCode::LdTrue;
  8014. byteCodeGenerator->Writer()->Reg1(op, pnode->location);
  8015. }
  8016. else
  8017. {
  8018. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  8019. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, pnode->location);
  8020. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, doneLabel, pnode->sxUni.pnode1->location);
  8021. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, pnode->location);
  8022. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  8023. }
  8024. funcInfo->ReleaseLoc(pnode->sxUni.pnode1);
  8025. break;
  8026. }
  8027. // PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  8028. case knopEllipsis:
  8029. {
  8030. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  8031. // Transparently pass the location of the array.
  8032. pnode->location = pnode->sxUni.pnode1->location;
  8033. break;
  8034. }
  8035. // PTNODE(knopIncPost , "post++" ,Inc ,Uni ,fnopUni|fnopAsg)
  8036. case knopIncPost:
  8037. case knopDecPost:
  8038. // FALL THROUGH to the faster pre-inc/dec case if the result of the expression is not needed.
  8039. if (pnode->isUsed || fReturnValue)
  8040. {
  8041. byteCodeGenerator->StartStatement(pnode);
  8042. Js::OpCode op = Js::OpCode::Add_A;
  8043. if (pnode->nop == knopDecPost)
  8044. {
  8045. op = Js::OpCode::Sub_A;
  8046. }
  8047. // Grab a register for the expression result.
  8048. funcInfo->AcquireLoc(pnode);
  8049. // Load the initial value, convert it (this is the expression result), and increment it.
  8050. EmitLoad(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo);
  8051. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Num, pnode->location, pnode->sxUni.pnode1->location);
  8052. Js::RegSlot incDecResult = pnode->sxUni.pnode1->location;
  8053. if (funcInfo->RegIsConst(incDecResult))
  8054. {
  8055. // Avoid letting the add/sub overwrite a constant reg, as this may actually change the
  8056. // contents of the constant table.
  8057. incDecResult = funcInfo->AcquireTmpRegister();
  8058. }
  8059. Js::RegSlot oneReg = funcInfo->constantToRegister.LookupWithKey(1, Js::Constants::NoRegister);
  8060. Assert(oneReg != Js::Constants::NoRegister);
  8061. byteCodeGenerator->Writer()->Reg3(op, incDecResult, pnode->location, oneReg);
  8062. // Store the incremented value.
  8063. EmitAssignment(nullptr, pnode->sxUni.pnode1, incDecResult, byteCodeGenerator, funcInfo);
  8064. // Release the incremented value and the l-value.
  8065. if (incDecResult != pnode->sxUni.pnode1->location)
  8066. {
  8067. funcInfo->ReleaseTmpRegister(incDecResult);
  8068. }
  8069. funcInfo->ReleaseLoad(pnode->sxUni.pnode1);
  8070. byteCodeGenerator->EndStatement(pnode);
  8071. break;
  8072. }
  8073. else
  8074. {
  8075. pnode->nop = (pnode->nop == knopIncPost) ? knopIncPre : knopDecPre;
  8076. }
  8077. // FALL THROUGH to the fast pre-inc/dec case if the result of the expression is not needed.
  8078. // PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  8079. case knopIncPre:
  8080. case knopDecPre:
  8081. {
  8082. byteCodeGenerator->StartStatement(pnode);
  8083. Js::OpCode op = Js::OpCode::Incr_A;
  8084. if (pnode->nop == knopDecPre)
  8085. {
  8086. op = Js::OpCode::Decr_A;
  8087. }
  8088. // Assign a register for the result only if the result is used or the operand can't be assigned to
  8089. // (i.e., is a constant).
  8090. if (pnode->isUsed || fReturnValue)
  8091. {
  8092. funcInfo->AcquireLoc(pnode);
  8093. // Load the initial value and increment it (this is the expression result).
  8094. EmitLoad(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo);
  8095. byteCodeGenerator->Writer()->Reg2(op, pnode->location, pnode->sxUni.pnode1->location);
  8096. // Store the incremented value and release the l-value.
  8097. EmitAssignment(nullptr, pnode->sxUni.pnode1, pnode->location, byteCodeGenerator, funcInfo);
  8098. funcInfo->ReleaseLoad(pnode->sxUni.pnode1);
  8099. }
  8100. else
  8101. {
  8102. // Load the initial value and increment it (this is the expression result).
  8103. EmitLoad(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo);
  8104. Js::RegSlot incDecResult = pnode->sxUni.pnode1->location;
  8105. if (funcInfo->RegIsConst(incDecResult))
  8106. {
  8107. // Avoid letting the add/sub overwrite a constant reg, as this may actually change the
  8108. // contents of the constant table.
  8109. incDecResult = funcInfo->AcquireTmpRegister();
  8110. }
  8111. byteCodeGenerator->Writer()->Reg2(op, incDecResult, pnode->sxUni.pnode1->location);
  8112. // Store the incremented value and release the l-value.
  8113. EmitAssignment(nullptr, pnode->sxUni.pnode1, incDecResult, byteCodeGenerator, funcInfo);
  8114. if (incDecResult != pnode->sxUni.pnode1->location)
  8115. {
  8116. funcInfo->ReleaseTmpRegister(incDecResult);
  8117. }
  8118. funcInfo->ReleaseLoad(pnode->sxUni.pnode1);
  8119. }
  8120. byteCodeGenerator->EndStatement(pnode);
  8121. break;
  8122. }
  8123. // PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  8124. case knopTypeof:
  8125. {
  8126. ParseNode* pnodeOpnd = pnode->sxUni.pnode1;
  8127. switch (pnodeOpnd->nop)
  8128. {
  8129. case knopDot:
  8130. {
  8131. Emit(pnodeOpnd->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  8132. Js::PropertyId propertyId = pnodeOpnd->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  8133. Assert(pnodeOpnd->sxBin.pnode2->nop == knopName);
  8134. funcInfo->ReleaseLoc(pnodeOpnd->sxBin.pnode1);
  8135. funcInfo->AcquireLoc(pnode);
  8136. byteCodeGenerator->EmitTypeOfFld(funcInfo, propertyId, pnode->location, pnodeOpnd->sxBin.pnode1->location, Js::OpCode::LdFldForTypeOf);
  8137. break;
  8138. }
  8139. case knopIndex:
  8140. {
  8141. EmitBinaryOpnds(pnodeOpnd->sxBin.pnode1, pnodeOpnd->sxBin.pnode2, byteCodeGenerator, funcInfo);
  8142. funcInfo->ReleaseLoc(pnodeOpnd->sxBin.pnode2);
  8143. funcInfo->ReleaseLoc(pnodeOpnd->sxBin.pnode1);
  8144. funcInfo->AcquireLoc(pnode);
  8145. byteCodeGenerator->Writer()->Element(Js::OpCode::TypeofElem, pnode->location, pnodeOpnd->sxBin.pnode1->location, pnodeOpnd->sxBin.pnode2->location);
  8146. break;
  8147. }
  8148. case knopName:
  8149. {
  8150. funcInfo->AcquireLoc(pnode);
  8151. byteCodeGenerator->EmitPropTypeof(pnode->location, pnodeOpnd->sxPid.sym, pnodeOpnd->sxPid.pid, funcInfo);
  8152. break;
  8153. }
  8154. default:
  8155. Emit(pnodeOpnd, byteCodeGenerator, funcInfo, false);
  8156. funcInfo->ReleaseLoc(pnodeOpnd);
  8157. byteCodeGenerator->Writer()->Reg2(
  8158. Js::OpCode::Typeof, funcInfo->AcquireLoc(pnode), pnodeOpnd->location);
  8159. break;
  8160. }
  8161. break;
  8162. }
  8163. // PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  8164. case knopVoid:
  8165. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  8166. funcInfo->ReleaseLoc(pnode->sxUni.pnode1);
  8167. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, funcInfo->AcquireLoc(pnode));
  8168. break;
  8169. // PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  8170. case knopArray:
  8171. EmitArrayLiteral(pnode, byteCodeGenerator, funcInfo);
  8172. break;
  8173. // PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  8174. case knopObject:
  8175. funcInfo->AcquireLoc(pnode);
  8176. EmitObjectInitializers(pnode->sxUni.pnode1, pnode->location, byteCodeGenerator, funcInfo);
  8177. break;
  8178. // PTNODE(knopComputedName, "[name]" ,None ,Uni ,fnopUni)
  8179. case knopComputedName:
  8180. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  8181. if (pnode->location == Js::Constants::NoRegister)
  8182. {
  8183. // The name is some expression with no home location. We can just re-use the register.
  8184. pnode->location = pnode->sxUni.pnode1->location;
  8185. }
  8186. else if (pnode->location != pnode->sxUni.pnode1->location)
  8187. {
  8188. // The name had to be protected from side-effects of the RHS.
  8189. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxUni.pnode1->location);
  8190. }
  8191. break;
  8192. // Binary and Ternary Operators
  8193. case knopAdd:
  8194. EmitAdd(pnode, byteCodeGenerator, funcInfo);
  8195. break;
  8196. case knopSub:
  8197. case knopMul:
  8198. case knopExpo:
  8199. case knopDiv:
  8200. case knopMod:
  8201. case knopOr:
  8202. case knopXor:
  8203. case knopAnd:
  8204. case knopLsh:
  8205. case knopRsh:
  8206. case knopRs2:
  8207. case knopIn:
  8208. EmitBinary(nopToOp[pnode->nop], pnode, byteCodeGenerator, funcInfo);
  8209. break;
  8210. case knopInstOf:
  8211. {
  8212. byteCodeGenerator->StartStatement(pnode);
  8213. EmitBinaryOpnds(pnode->sxBin.pnode1, pnode->sxBin.pnode2, byteCodeGenerator, funcInfo);
  8214. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  8215. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  8216. funcInfo->AcquireLoc(pnode);
  8217. uint cacheId = funcInfo->NewIsInstInlineCache();
  8218. byteCodeGenerator->Writer()->Reg3C(nopToOp[pnode->nop], pnode->location, pnode->sxBin.pnode1->location,
  8219. pnode->sxBin.pnode2->location, cacheId);
  8220. byteCodeGenerator->EndStatement(pnode);
  8221. }
  8222. break;
  8223. case knopEq:
  8224. case knopEqv:
  8225. case knopNEqv:
  8226. case knopNe:
  8227. case knopLt:
  8228. case knopLe:
  8229. case knopGe:
  8230. case knopGt:
  8231. byteCodeGenerator->StartStatement(pnode);
  8232. EmitBinaryOpnds(pnode->sxBin.pnode1, pnode->sxBin.pnode2, byteCodeGenerator, funcInfo);
  8233. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  8234. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  8235. funcInfo->AcquireLoc(pnode);
  8236. byteCodeGenerator->Writer()->Reg3(nopToCMOp[pnode->nop], pnode->location, pnode->sxBin.pnode1->location,
  8237. pnode->sxBin.pnode2->location);
  8238. byteCodeGenerator->EndStatement(pnode);
  8239. break;
  8240. case knopNew:
  8241. {
  8242. Js::ArgSlot argCount = pnode->sxCall.argCount;
  8243. argCount++; // include "this"
  8244. BOOL fSideEffectArgs = FALSE;
  8245. unsigned int tmpCount = CountArguments(pnode->sxCall.pnodeArgs, &fSideEffectArgs);
  8246. Assert(argCount == tmpCount);
  8247. if (argCount != (Js::ArgSlot)argCount)
  8248. {
  8249. Js::Throw::OutOfMemory();
  8250. }
  8251. byteCodeGenerator->StartStatement(pnode);
  8252. // Start call, allocate out param space
  8253. funcInfo->StartRecordingOutArgs(argCount);
  8254. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  8255. // them from side-effects.
  8256. if (fSideEffectArgs)
  8257. {
  8258. SaveOpndValue(pnode->sxCall.pnodeTarget, funcInfo);
  8259. }
  8260. if (pnode->sxCall.pnodeTarget->nop == knopSuper)
  8261. {
  8262. EmitSuperFieldPatch(funcInfo, pnode, byteCodeGenerator);
  8263. }
  8264. Emit(pnode->sxCall.pnodeTarget, byteCodeGenerator, funcInfo, false, true);
  8265. if (pnode->sxCall.pnodeArgs == nullptr)
  8266. {
  8267. funcInfo->ReleaseLoc(pnode->sxCall.pnodeTarget);
  8268. Js::OpCode op = (CreateNativeArrays(byteCodeGenerator, funcInfo)
  8269. && CallTargetIsArray(pnode->sxCall.pnodeTarget))
  8270. ? Js::OpCode::NewScObjArray : Js::OpCode::NewScObject;
  8271. Assert(argCount == 1);
  8272. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(op);
  8273. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argCount);
  8274. byteCodeGenerator->Writer()->CallI(op, funcInfo->AcquireLoc(pnode),
  8275. pnode->sxCall.pnodeTarget->location, argCount, callSiteId);
  8276. }
  8277. else
  8278. {
  8279. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argCount);
  8280. uint32 actualArgCount = 0;
  8281. if (IsCallOfConstants(pnode))
  8282. {
  8283. funcInfo->ReleaseLoc(pnode->sxCall.pnodeTarget);
  8284. actualArgCount = EmitNewObjectOfConstants(pnode, byteCodeGenerator, funcInfo, argCount);
  8285. }
  8286. else
  8287. {
  8288. Js::OpCode op;
  8289. if ((CreateNativeArrays(byteCodeGenerator, funcInfo) && CallTargetIsArray(pnode->sxCall.pnodeTarget)))
  8290. {
  8291. op = pnode->sxCall.spreadArgCount > 0 ? Js::OpCode::NewScObjArraySpread : Js::OpCode::NewScObjArray;
  8292. }
  8293. else
  8294. {
  8295. op = pnode->sxCall.spreadArgCount > 0 ? Js::OpCode::NewScObjectSpread : Js::OpCode::NewScObject;
  8296. }
  8297. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(op);
  8298. Js::AuxArray<uint32> *spreadIndices = nullptr;
  8299. actualArgCount = EmitArgList(pnode->sxCall.pnodeArgs, Js::Constants::NoRegister, Js::Constants::NoRegister, Js::Constants::NoRegister,
  8300. false, true, byteCodeGenerator, funcInfo, callSiteId, pnode->sxCall.spreadArgCount, &spreadIndices);
  8301. funcInfo->ReleaseLoc(pnode->sxCall.pnodeTarget);
  8302. if (pnode->sxCall.spreadArgCount > 0)
  8303. {
  8304. Assert(spreadIndices != nullptr);
  8305. uint spreadExtraAlloc = spreadIndices->count * sizeof(uint32);
  8306. uint spreadIndicesSize = sizeof(*spreadIndices) + spreadExtraAlloc;
  8307. byteCodeGenerator->Writer()->CallIExtended(op, funcInfo->AcquireLoc(pnode), pnode->sxCall.pnodeTarget->location,
  8308. (uint16)actualArgCount, Js::CallIExtended_SpreadArgs,
  8309. spreadIndices, spreadIndicesSize, callSiteId);
  8310. }
  8311. else
  8312. {
  8313. byteCodeGenerator->Writer()->CallI(op, funcInfo->AcquireLoc(pnode), pnode->sxCall.pnodeTarget->location,
  8314. (uint16)actualArgCount, callSiteId);
  8315. }
  8316. }
  8317. Assert(argCount == actualArgCount);
  8318. }
  8319. // End call, pop param space
  8320. funcInfo->EndRecordingOutArgs(argCount);
  8321. byteCodeGenerator->EndStatement(pnode);
  8322. break;
  8323. }
  8324. case knopDelete:
  8325. {
  8326. ParseNode *pexpr = pnode->sxUni.pnode1;
  8327. byteCodeGenerator->StartStatement(pnode);
  8328. switch (pexpr->nop)
  8329. {
  8330. case knopName:
  8331. {
  8332. funcInfo->AcquireLoc(pnode);
  8333. byteCodeGenerator->EmitPropDelete(pnode->location, pexpr->sxPid.sym, pexpr->sxPid.pid, funcInfo);
  8334. break;
  8335. }
  8336. case knopDot:
  8337. {
  8338. Emit(pexpr->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  8339. Js::PropertyId propertyId = pexpr->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  8340. funcInfo->ReleaseLoc(pexpr->sxBin.pnode1);
  8341. funcInfo->AcquireLoc(pnode);
  8342. byteCodeGenerator->Writer()->Property(Js::OpCode::DeleteFld, pnode->location, pexpr->sxBin.pnode1->location,
  8343. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  8344. break;
  8345. }
  8346. case knopIndex:
  8347. {
  8348. EmitBinaryOpnds(pexpr->sxBin.pnode1, pexpr->sxBin.pnode2, byteCodeGenerator, funcInfo);
  8349. funcInfo->ReleaseLoc(pexpr->sxBin.pnode2);
  8350. funcInfo->ReleaseLoc(pexpr->sxBin.pnode1);
  8351. funcInfo->AcquireLoc(pnode);
  8352. byteCodeGenerator->Writer()->Element(Js::OpCode::DeleteElemI_A, pnode->location, pexpr->sxBin.pnode1->location, pexpr->sxBin.pnode2->location);
  8353. break;
  8354. }
  8355. case knopThis:
  8356. {
  8357. funcInfo->AcquireLoc(pnode);
  8358. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, pnode->location);
  8359. break;
  8360. }
  8361. default:
  8362. {
  8363. Emit(pexpr, byteCodeGenerator, funcInfo, false);
  8364. funcInfo->ReleaseLoc(pexpr);
  8365. byteCodeGenerator->Writer()->Reg2(
  8366. Js::OpCode::Delete_A, funcInfo->AcquireLoc(pnode), pexpr->location);
  8367. break;
  8368. }
  8369. }
  8370. byteCodeGenerator->EndStatement(pnode);
  8371. break;
  8372. }
  8373. case knopCall:
  8374. {
  8375. byteCodeGenerator->StartStatement(pnode);
  8376. if (pnode->sxCall.pnodeTarget->nop == knopSuper)
  8377. {
  8378. byteCodeGenerator->EmitSuperCall(funcInfo, pnode, fReturnValue);
  8379. }
  8380. else
  8381. {
  8382. if (pnode->sxCall.isApplyCall && funcInfo->GetApplyEnclosesArgs())
  8383. {
  8384. // TODO[ianhall]: Can we remove the ApplyCall bytecode gen time optimization?
  8385. EmitApplyCall(pnode, Js::Constants::NoRegister, byteCodeGenerator, funcInfo, fReturnValue, true);
  8386. }
  8387. else
  8388. {
  8389. EmitCall(pnode, Js::Constants::NoRegister, byteCodeGenerator, funcInfo, fReturnValue, /*fEvaluateComponents*/ true, /*fHasNewTarget*/ false);
  8390. }
  8391. }
  8392. byteCodeGenerator->EndStatement(pnode);
  8393. break;
  8394. }
  8395. case knopIndex:
  8396. {
  8397. byteCodeGenerator->StartStatement(pnode);
  8398. EmitBinaryOpnds(pnode->sxBin.pnode1, pnode->sxBin.pnode2, byteCodeGenerator, funcInfo);
  8399. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  8400. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  8401. funcInfo->AcquireLoc(pnode);
  8402. Js::RegSlot callObjLocation = pnode->sxBin.pnode1->location;
  8403. Js::RegSlot protoLocation = callObjLocation;
  8404. EmitSuperMethodBegin(pnode, byteCodeGenerator, funcInfo);
  8405. byteCodeGenerator->Writer()->Element(
  8406. Js::OpCode::LdElemI_A, pnode->location, protoLocation, pnode->sxBin.pnode2->location);
  8407. byteCodeGenerator->EndStatement(pnode);
  8408. break;
  8409. }
  8410. // this is MemberExpression as rvalue
  8411. case knopDot:
  8412. {
  8413. Emit(pnode->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  8414. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  8415. funcInfo->AcquireLoc(pnode);
  8416. Js::PropertyId propertyId = pnode->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  8417. Js::RegSlot callObjLocation = pnode->sxBin.pnode1->location;
  8418. Js::RegSlot protoLocation = callObjLocation;
  8419. EmitSuperMethodBegin(pnode, byteCodeGenerator, funcInfo);
  8420. if (propertyId == Js::PropertyIds::length)
  8421. {
  8422. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdLen_A, pnode->location, protoLocation);
  8423. }
  8424. else
  8425. {
  8426. uint cacheId = funcInfo->FindOrAddInlineCacheId(callObjLocation, propertyId, false, false);
  8427. if (pnode->IsCallApplyTargetLoad())
  8428. {
  8429. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFldForCallApplyTarget, pnode->location, protoLocation, cacheId);
  8430. }
  8431. else
  8432. {
  8433. if (pnode->sxBin.pnode1->nop == knopSuper)
  8434. {
  8435. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(Js::OpCode::LdSuperFld, pnode->location, protoLocation, funcInfo->thisPointerRegister, cacheId, isConstructorCall);
  8436. }
  8437. else
  8438. {
  8439. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, pnode->location, callObjLocation, cacheId, isConstructorCall);
  8440. }
  8441. }
  8442. }
  8443. break;
  8444. }
  8445. // PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  8446. case knopAsg:
  8447. {
  8448. ParseNode *lhs = pnode->sxBin.pnode1;
  8449. ParseNode *rhs = pnode->sxBin.pnode2;
  8450. byteCodeGenerator->StartStatement(pnode);
  8451. if (pnode->isUsed || fReturnValue)
  8452. {
  8453. // If the assignment result is used, grab a register to hold it and pass it to EmitAssignment,
  8454. // which will copy the assigned value there.
  8455. funcInfo->AcquireLoc(pnode);
  8456. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, false);
  8457. EmitAssignment(pnode, lhs, rhs->location, byteCodeGenerator, funcInfo);
  8458. }
  8459. else
  8460. {
  8461. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, false);
  8462. EmitAssignment(nullptr, lhs, rhs->location, byteCodeGenerator, funcInfo);
  8463. }
  8464. funcInfo->ReleaseLoc(rhs);
  8465. if (!(byteCodeGenerator->IsES6DestructuringEnabled() && (lhs->IsPattern())))
  8466. {
  8467. funcInfo->ReleaseReference(lhs);
  8468. }
  8469. byteCodeGenerator->EndStatement(pnode);
  8470. break;
  8471. }
  8472. case knopName:
  8473. funcInfo->AcquireLoc(pnode);
  8474. byteCodeGenerator->EmitPropLoad(pnode->location, pnode->sxPid.sym, pnode->sxPid.pid, funcInfo);
  8475. break;
  8476. case knopComma:
  8477. {
  8478. byteCodeGenerator->StartStatement(pnode);
  8479. // The parser marks binary opnd pnodes as used, but value of the first opnd of a comma is not used.
  8480. // Easier to correct this here than to check every binary op in the parser.
  8481. ParseNode *pnode1 = pnode->sxBin.pnode1;
  8482. pnode1->isUsed = false;
  8483. if (pnode1->nop == knopComma)
  8484. {
  8485. // Spot fix for giant comma expressions that send us into OOS if we use a simple recursive
  8486. // algorithm. Instead of recursing on comma LHS's, iterate over them, pushing the RHS's onto
  8487. // a stack. (This suggests a model for removing recursion from Emit altogether...)
  8488. ArenaAllocator *alloc = byteCodeGenerator->GetAllocator();
  8489. SList<ParseNode *> rhsStack(alloc);
  8490. do
  8491. {
  8492. rhsStack.Push(pnode1->sxBin.pnode2);
  8493. pnode1 = pnode1->sxBin.pnode1;
  8494. pnode1->isUsed = false;
  8495. }
  8496. while (pnode1->nop == knopComma);
  8497. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  8498. if (funcInfo->IsTmpReg(pnode1->location))
  8499. {
  8500. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Unused, pnode1->location);
  8501. }
  8502. while (!rhsStack.Empty())
  8503. {
  8504. ParseNode *pnodeRhs = rhsStack.Pop();
  8505. pnodeRhs->isUsed = false;
  8506. Emit(pnodeRhs, byteCodeGenerator, funcInfo, false);
  8507. if (funcInfo->IsTmpReg(pnodeRhs->location))
  8508. {
  8509. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Unused, pnodeRhs->location);
  8510. }
  8511. funcInfo->ReleaseLoc(pnodeRhs);
  8512. }
  8513. }
  8514. else
  8515. {
  8516. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  8517. if (funcInfo->IsTmpReg(pnode1->location))
  8518. {
  8519. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Unused, pnode1->location);
  8520. }
  8521. }
  8522. funcInfo->ReleaseLoc(pnode1);
  8523. pnode->sxBin.pnode2->isUsed = pnode->isUsed || fReturnValue;
  8524. Emit(pnode->sxBin.pnode2, byteCodeGenerator, funcInfo, false);
  8525. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  8526. funcInfo->AcquireLoc(pnode);
  8527. if (pnode->sxBin.pnode2->isUsed && pnode->location != pnode->sxBin.pnode2->location)
  8528. {
  8529. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxBin.pnode2->location);
  8530. }
  8531. byteCodeGenerator->EndStatement(pnode);
  8532. }
  8533. break;
  8534. // The binary logical ops && and || resolve to the value of the left-hand expression if its
  8535. // boolean value short-circuits the operation, and to the value of the right-hand expression
  8536. // otherwise. (In other words, the "truth" of the right-hand expression is never tested.)
  8537. // PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  8538. case knopLogOr:
  8539. {
  8540. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  8541. // For boolean expressions that compute a result, we have to burn a register for the result
  8542. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  8543. // full-on renaming in the back end.
  8544. funcInfo->AcquireLoc(pnode);
  8545. Emit(pnode->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  8546. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxBin.pnode1->location);
  8547. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, doneLabel, pnode->sxBin.pnode1->location);
  8548. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  8549. Emit(pnode->sxBin.pnode2, byteCodeGenerator, funcInfo, false);
  8550. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxBin.pnode2->location);
  8551. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  8552. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  8553. break;
  8554. }
  8555. // PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  8556. case knopLogAnd:
  8557. {
  8558. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  8559. // For boolean expressions that compute a result, we have to burn a register for the result
  8560. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  8561. // full-on renaming in the back end.
  8562. funcInfo->AcquireLoc(pnode);
  8563. Emit(pnode->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  8564. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxBin.pnode1->location);
  8565. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, doneLabel, pnode->sxBin.pnode1->location);
  8566. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  8567. Emit(pnode->sxBin.pnode2, byteCodeGenerator, funcInfo, false);
  8568. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxBin.pnode2->location);
  8569. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  8570. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  8571. break;
  8572. }
  8573. // PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  8574. case knopQmark:
  8575. {
  8576. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  8577. Js::ByteCodeLabel falseLabel = byteCodeGenerator->Writer()->DefineLabel();
  8578. Js::ByteCodeLabel skipLabel = byteCodeGenerator->Writer()->DefineLabel();
  8579. EmitBooleanExpression(pnode->sxTri.pnode1, trueLabel, falseLabel, byteCodeGenerator, funcInfo);
  8580. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  8581. funcInfo->ReleaseLoc(pnode->sxTri.pnode1);
  8582. // For boolean expressions that compute a result, we have to burn a register for the result
  8583. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  8584. // full-on renaming in the back end.
  8585. funcInfo->AcquireLoc(pnode);
  8586. Emit(pnode->sxTri.pnode2, byteCodeGenerator, funcInfo, false);
  8587. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxTri.pnode2->location);
  8588. funcInfo->ReleaseLoc(pnode->sxTri.pnode2);
  8589. // Record the branch bytecode offset
  8590. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_FromCurrentToNext);
  8591. byteCodeGenerator->Writer()->Br(skipLabel);
  8592. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  8593. Emit(pnode->sxTri.pnode3, byteCodeGenerator, funcInfo, false);
  8594. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxTri.pnode3->location);
  8595. funcInfo->ReleaseLoc(pnode->sxTri.pnode3);
  8596. byteCodeGenerator->Writer()->MarkLabel(skipLabel);
  8597. break;
  8598. }
  8599. case knopAsgAdd:
  8600. case knopAsgSub:
  8601. case knopAsgMul:
  8602. case knopAsgDiv:
  8603. case knopAsgExpo:
  8604. case knopAsgMod:
  8605. case knopAsgAnd:
  8606. case knopAsgXor:
  8607. case knopAsgOr:
  8608. case knopAsgLsh:
  8609. case knopAsgRsh:
  8610. case knopAsgRs2:
  8611. byteCodeGenerator->StartStatement(pnode);
  8612. // Assign a register for the result only if the result is used or the LHS can't be assigned to
  8613. // (i.e., is a constant).
  8614. if (pnode->isUsed || fReturnValue || funcInfo->RegIsConst(pnode->sxBin.pnode1->location))
  8615. {
  8616. // If the assign-op result is used, grab a register to hold it.
  8617. funcInfo->AcquireLoc(pnode);
  8618. // Grab a register for the initial value and load it.
  8619. EmitBinaryReference(pnode->sxBin.pnode1, pnode->sxBin.pnode2, byteCodeGenerator, funcInfo, true);
  8620. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  8621. // Do the arithmetic, store the result, and release the l-value.
  8622. byteCodeGenerator->Writer()->Reg3(nopToOp[pnode->nop], pnode->location, pnode->sxBin.pnode1->location,
  8623. pnode->sxBin.pnode2->location);
  8624. EmitAssignment(pnode, pnode->sxBin.pnode1, pnode->location, byteCodeGenerator, funcInfo);
  8625. }
  8626. else
  8627. {
  8628. // Grab a register for the initial value and load it.
  8629. EmitBinaryReference(pnode->sxBin.pnode1, pnode->sxBin.pnode2, byteCodeGenerator, funcInfo, true);
  8630. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  8631. // Do the arithmetic, store the result, and release the l-value.
  8632. byteCodeGenerator->Writer()->Reg3(nopToOp[pnode->nop], pnode->sxBin.pnode1->location, pnode->sxBin.pnode1->location,
  8633. pnode->sxBin.pnode2->location);
  8634. EmitAssignment(nullptr, pnode->sxBin.pnode1, pnode->sxBin.pnode1->location, byteCodeGenerator, funcInfo);
  8635. }
  8636. funcInfo->ReleaseLoad(pnode->sxBin.pnode1);
  8637. byteCodeGenerator->EndStatement(pnode);
  8638. break;
  8639. // General nodes.
  8640. // PTNODE(knopTempRef , "temp ref" ,None ,Uni ,fnopUni)
  8641. case knopTempRef:
  8642. // TODO: check whether mov is necessary
  8643. funcInfo->AcquireLoc(pnode);
  8644. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxUni.pnode1->location);
  8645. break;
  8646. // PTNODE(knopTemp , "temp" ,None ,None ,fnopLeaf)
  8647. case knopTemp:
  8648. // Emit initialization code
  8649. if (pnode->sxVar.pnodeInit != nullptr)
  8650. {
  8651. byteCodeGenerator->StartStatement(pnode);
  8652. Emit(pnode->sxVar.pnodeInit, byteCodeGenerator, funcInfo, false);
  8653. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxVar.pnodeInit->location);
  8654. funcInfo->ReleaseLoc(pnode->sxVar.pnodeInit);
  8655. byteCodeGenerator->EndStatement(pnode);
  8656. }
  8657. break;
  8658. // PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  8659. case knopVarDecl:
  8660. {
  8661. // Emit initialization code
  8662. ParseNodePtr initNode = pnode->sxVar.pnodeInit;
  8663. if (initNode != nullptr)
  8664. {
  8665. byteCodeGenerator->StartStatement(pnode);
  8666. Emit(pnode->sxVar.pnodeInit, byteCodeGenerator, funcInfo, false);
  8667. EmitAssignment(nullptr, pnode, pnode->sxVar.pnodeInit->location, byteCodeGenerator, funcInfo);
  8668. funcInfo->ReleaseLoc(pnode->sxVar.pnodeInit);
  8669. byteCodeGenerator->EndStatement(pnode);
  8670. Symbol *sym = pnode->sxVar.sym;
  8671. if (pnode->sxVar.pnodeInit->nop == knopObject && (ParseNode::Grfnop(pnode->sxVar.pnodeInit->nop) & fnopUni))
  8672. {
  8673. TrackMemberNodesInObjectForIntConstants(byteCodeGenerator, pnode->sxVar.pnodeInit);
  8674. }
  8675. else if (initNode->nop == knopInt)
  8676. {
  8677. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  8678. }
  8679. }
  8680. break;
  8681. }
  8682. case knopConstDecl:
  8683. {
  8684. ParseNodePtr initNode = pnode->sxVar.pnodeInit;
  8685. Symbol * sym = pnode->sxVar.sym;
  8686. byteCodeGenerator->StartStatement(pnode);
  8687. if (initNode)
  8688. {
  8689. Emit(initNode, byteCodeGenerator, funcInfo, false);
  8690. byteCodeGenerator->EmitPropStore(initNode->location, sym, nullptr, funcInfo, false, true);
  8691. funcInfo->ReleaseLoc(pnode->sxVar.pnodeInit);
  8692. if (initNode->nop == knopInt)
  8693. {
  8694. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  8695. }
  8696. }
  8697. byteCodeGenerator->EndStatement(pnode);
  8698. // Set NeedDeclaration to false AFTER emitting the initializer, otherwise we won't have "Use Before Declaration"
  8699. // errors reported in the initializer for code like this:
  8700. // { const a = a; }
  8701. sym->SetNeedDeclaration(false);
  8702. break;
  8703. }
  8704. case knopLetDecl:
  8705. {
  8706. ParseNodePtr initNode = pnode->sxVar.pnodeInit;
  8707. byteCodeGenerator->StartStatement(pnode);
  8708. Symbol * sym = pnode->sxVar.sym;
  8709. Js::RegSlot rhsLocation;
  8710. if (pnode->sxVar.pnodeInit != nullptr)
  8711. {
  8712. Emit(pnode->sxVar.pnodeInit, byteCodeGenerator, funcInfo, false);
  8713. rhsLocation = pnode->sxVar.pnodeInit->location;
  8714. if (initNode->nop == knopInt)
  8715. {
  8716. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  8717. }
  8718. }
  8719. else
  8720. {
  8721. rhsLocation = funcInfo->AcquireTmpRegister();
  8722. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, rhsLocation);
  8723. }
  8724. // Set NeedDeclaration to false AFTER emitting the initializer, otherwise we won't have "Use Before Declaration"
  8725. // errors reported in the initializer for code like this:
  8726. // { let a = a; }
  8727. sym->SetNeedDeclaration(false);
  8728. byteCodeGenerator->EmitPropStore(rhsLocation, sym, nullptr, funcInfo, true, false);
  8729. funcInfo->ReleaseTmpRegister(rhsLocation);
  8730. byteCodeGenerator->EndStatement(pnode);
  8731. break;
  8732. }
  8733. // PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  8734. case knopFncDecl:
  8735. // The "function declarations" were emitted in DefineFunctions()
  8736. if (!pnode->sxFnc.IsDeclaration())
  8737. {
  8738. byteCodeGenerator->DefineOneFunction(pnode, funcInfo, false);
  8739. }
  8740. break;
  8741. // PTNODE(knopClassDecl, "class" ,None ,None ,fnopLeaf)
  8742. case knopClassDecl:
  8743. {
  8744. funcInfo->AcquireLoc(pnode);
  8745. // Extends
  8746. if (pnode->sxClass.pnodeExtends)
  8747. {
  8748. Emit(pnode->sxClass.pnodeExtends, byteCodeGenerator, funcInfo, false);
  8749. }
  8750. Assert(pnode->sxClass.pnodeConstructor);
  8751. pnode->sxClass.pnodeConstructor->location = pnode->location;
  8752. BeginEmitBlock(pnode->sxClass.pnodeBlock, byteCodeGenerator, funcInfo);
  8753. // Constructor
  8754. Emit(pnode->sxClass.pnodeConstructor, byteCodeGenerator, funcInfo, false);
  8755. EmitComputedFunctionNameVar(bindPnode, pnode->sxClass.pnodeConstructor, byteCodeGenerator);
  8756. if (pnode->sxClass.pnodeExtends)
  8757. {
  8758. byteCodeGenerator->Writer()->InitClass(pnode->location, pnode->sxClass.pnodeExtends->location);
  8759. }
  8760. else
  8761. {
  8762. byteCodeGenerator->Writer()->InitClass(pnode->location);
  8763. }
  8764. Js::RegSlot protoLoc = funcInfo->AcquireTmpRegister(); //register set if we have Instance Methods
  8765. int cacheId = funcInfo->FindOrAddInlineCacheId(pnode->location, Js::PropertyIds::prototype, false, false);
  8766. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, protoLoc, pnode->location, cacheId);
  8767. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SetHomeObj, pnode->location, protoLoc);
  8768. // Static Methods
  8769. EmitClassInitializers(pnode->sxClass.pnodeStaticMembers, pnode->location, byteCodeGenerator, funcInfo, pnode, /*isObjectEmpty*/ false);
  8770. // Instance Methods
  8771. EmitClassInitializers(pnode->sxClass.pnodeMembers, protoLoc, byteCodeGenerator, funcInfo, pnode, /*isObjectEmpty*/ true);
  8772. funcInfo->ReleaseTmpRegister(protoLoc);
  8773. // Emit name binding.
  8774. if (pnode->sxClass.pnodeName)
  8775. {
  8776. Symbol * sym = pnode->sxClass.pnodeName->sxVar.sym;
  8777. sym->SetNeedDeclaration(false);
  8778. byteCodeGenerator->EmitPropStore(pnode->location, sym, nullptr, funcInfo, false, true);
  8779. }
  8780. EndEmitBlock(pnode->sxClass.pnodeBlock, byteCodeGenerator, funcInfo);
  8781. if (pnode->sxClass.pnodeExtends)
  8782. {
  8783. funcInfo->ReleaseLoc(pnode->sxClass.pnodeExtends);
  8784. }
  8785. if (pnode->sxClass.pnodeDeclName)
  8786. {
  8787. Symbol * sym = pnode->sxClass.pnodeDeclName->sxVar.sym;
  8788. sym->SetNeedDeclaration(false);
  8789. byteCodeGenerator->EmitPropStore(pnode->location, sym, nullptr, funcInfo, true, false);
  8790. }
  8791. break;
  8792. }
  8793. case knopStrTemplate:
  8794. EmitStringTemplate(pnode, byteCodeGenerator, funcInfo);
  8795. break;
  8796. case knopEndCode:
  8797. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_All);
  8798. // load undefined for the fallthrough case:
  8799. if (!funcInfo->IsGlobalFunction())
  8800. {
  8801. if (funcInfo->IsClassConstructor())
  8802. {
  8803. // For class constructors, we need to explicitly load 'this' into the return register.
  8804. byteCodeGenerator->EmitClassConstructorEndCode(funcInfo);
  8805. }
  8806. else
  8807. {
  8808. // In the global function, implicit return values are copied to the return register, and if
  8809. // necessary the return register is initialized at the top. Don't clobber the value here.
  8810. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, ByteCodeGenerator::ReturnRegister);
  8811. }
  8812. }
  8813. // Label for non-fall-through return
  8814. byteCodeGenerator->Writer()->MarkLabel(funcInfo->singleExit);
  8815. if (funcInfo->GetHasCachedScope())
  8816. {
  8817. byteCodeGenerator->Writer()->AuxNoReg(
  8818. Js::OpCode::CommitScope,
  8819. funcInfo->localPropIdOffset,
  8820. sizeof(Js::PropertyIdArray) + ((funcInfo->GetBodyScope()->GetScopeSlotCount() + 3) * sizeof(Js::PropertyId)));
  8821. }
  8822. byteCodeGenerator->StartStatement(pnode);
  8823. byteCodeGenerator->Writer()->Empty(Js::OpCode::Ret);
  8824. byteCodeGenerator->EndStatement(pnode);
  8825. break;
  8826. // PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  8827. case knopDebugger:
  8828. byteCodeGenerator->StartStatement(pnode);
  8829. byteCodeGenerator->Writer()->Empty(Js::OpCode::Break);
  8830. byteCodeGenerator->EndStatement(pnode);
  8831. break;
  8832. // PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  8833. case knopFor:
  8834. if (pnode->sxFor.pnodeInverted != nullptr)
  8835. {
  8836. byteCodeGenerator->EmitInvertedLoop(pnode, pnode->sxFor.pnodeInverted, funcInfo);
  8837. }
  8838. else
  8839. {
  8840. BeginEmitBlock(pnode->sxFor.pnodeBlock, byteCodeGenerator, funcInfo);
  8841. Emit(pnode->sxFor.pnodeInit, byteCodeGenerator, funcInfo, false);
  8842. funcInfo->ReleaseLoc(pnode->sxFor.pnodeInit);
  8843. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8844. {
  8845. CloneEmitBlock(pnode->sxFor.pnodeBlock, byteCodeGenerator, funcInfo);
  8846. }
  8847. EmitLoop(pnode,
  8848. pnode->sxFor.pnodeCond,
  8849. pnode->sxFor.pnodeBody,
  8850. pnode->sxFor.pnodeIncr,
  8851. byteCodeGenerator,
  8852. funcInfo,
  8853. fReturnValue,
  8854. FALSE,
  8855. pnode->sxFor.pnodeBlock);
  8856. EndEmitBlock(pnode->sxFor.pnodeBlock, byteCodeGenerator, funcInfo);
  8857. }
  8858. break;
  8859. // PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  8860. case knopIf:
  8861. {
  8862. byteCodeGenerator->StartStatement(pnode);
  8863. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  8864. Js::ByteCodeLabel falseLabel = byteCodeGenerator->Writer()->DefineLabel();
  8865. EmitBooleanExpression(pnode->sxIf.pnodeCond, trueLabel, falseLabel, byteCodeGenerator, funcInfo);
  8866. funcInfo->ReleaseLoc(pnode->sxIf.pnodeCond);
  8867. byteCodeGenerator->EndStatement(pnode);
  8868. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  8869. Emit(pnode->sxIf.pnodeTrue, byteCodeGenerator, funcInfo, fReturnValue);
  8870. funcInfo->ReleaseLoc(pnode->sxIf.pnodeTrue);
  8871. if (pnode->sxIf.pnodeFalse != nullptr)
  8872. {
  8873. // has else clause
  8874. Js::ByteCodeLabel skipLabel = byteCodeGenerator->Writer()->DefineLabel();
  8875. // Record the branch bytecode offset
  8876. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_FromCurrentToNext);
  8877. // then clause skips else clause
  8878. byteCodeGenerator->Writer()->Br(skipLabel);
  8879. // generate code for else clause
  8880. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  8881. Emit(pnode->sxIf.pnodeFalse, byteCodeGenerator, funcInfo, fReturnValue);
  8882. funcInfo->ReleaseLoc(pnode->sxIf.pnodeFalse);
  8883. byteCodeGenerator->Writer()->MarkLabel(skipLabel);
  8884. }
  8885. else
  8886. {
  8887. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  8888. }
  8889. if (pnode->emitLabels)
  8890. {
  8891. byteCodeGenerator->Writer()->MarkLabel(pnode->sxStmt.breakLabel);
  8892. }
  8893. break;
  8894. }
  8895. case knopWhile:
  8896. EmitLoop(pnode,
  8897. pnode->sxWhile.pnodeCond,
  8898. pnode->sxWhile.pnodeBody,
  8899. nullptr,
  8900. byteCodeGenerator,
  8901. funcInfo,
  8902. fReturnValue);
  8903. break;
  8904. // PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  8905. case knopDoWhile:
  8906. EmitLoop(pnode,
  8907. pnode->sxWhile.pnodeCond,
  8908. pnode->sxWhile.pnodeBody,
  8909. nullptr,
  8910. byteCodeGenerator,
  8911. funcInfo,
  8912. fReturnValue,
  8913. true);
  8914. break;
  8915. // PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  8916. case knopForIn:
  8917. EmitForInOrForOf(pnode, byteCodeGenerator, funcInfo, fReturnValue);
  8918. break;
  8919. case knopForOf:
  8920. EmitForInOrForOf(pnode, byteCodeGenerator, funcInfo, fReturnValue);
  8921. break;
  8922. // PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  8923. case knopReturn:
  8924. byteCodeGenerator->StartStatement(pnode);
  8925. if (pnode->sxReturn.pnodeExpr != nullptr)
  8926. {
  8927. if (pnode->sxReturn.pnodeExpr->location == Js::Constants::NoRegister)
  8928. {
  8929. // No need to burn a register for the return value. If we need a temp, use R0 directly.
  8930. pnode->sxReturn.pnodeExpr->location = ByteCodeGenerator::ReturnRegister;
  8931. }
  8932. Emit(pnode->sxReturn.pnodeExpr, byteCodeGenerator, funcInfo, fReturnValue);
  8933. if (pnode->sxReturn.pnodeExpr->location != ByteCodeGenerator::ReturnRegister)
  8934. {
  8935. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, pnode->sxReturn.pnodeExpr->location);
  8936. }
  8937. funcInfo->GetParsedFunctionBody()->SetHasNoExplicitReturnValue(false);
  8938. }
  8939. else
  8940. {
  8941. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, ByteCodeGenerator::ReturnRegister);
  8942. }
  8943. if (funcInfo->IsClassConstructor())
  8944. {
  8945. // return expr; // becomes like below:
  8946. //
  8947. // if (IsObject(expr)) {
  8948. // return expr;
  8949. // } else if (IsBaseClassConstructor) {
  8950. // return this;
  8951. // } else if (!IsUndefined(expr)) {
  8952. // throw TypeError;
  8953. // }
  8954. Js::ByteCodeLabel returnExprLabel = byteCodeGenerator->Writer()->DefineLabel();
  8955. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, returnExprLabel, ByteCodeGenerator::ReturnRegister);
  8956. if (funcInfo->IsBaseClassConstructor())
  8957. {
  8958. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, funcInfo->thisPointerRegister);
  8959. }
  8960. else
  8961. {
  8962. Js::ByteCodeLabel returnThisLabel = byteCodeGenerator->Writer()->DefineLabel();
  8963. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, returnThisLabel, ByteCodeGenerator::ReturnRegister, funcInfo->undefinedConstantRegister);
  8964. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ClassDerivedConstructorInvalidReturnType));
  8965. byteCodeGenerator->Writer()->MarkLabel(returnThisLabel);
  8966. byteCodeGenerator->EmitClassConstructorEndCode(funcInfo);
  8967. }
  8968. byteCodeGenerator->Writer()->MarkLabel(returnExprLabel);
  8969. }
  8970. if (pnode->sxStmt.grfnop & fnopCleanup)
  8971. {
  8972. EmitJumpCleanup(pnode, nullptr, byteCodeGenerator, funcInfo);
  8973. }
  8974. byteCodeGenerator->Writer()->Br(funcInfo->singleExit);
  8975. byteCodeGenerator->EndStatement(pnode);
  8976. break;
  8977. case knopLabel:
  8978. break;
  8979. // PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  8980. case knopBlock:
  8981. if (pnode->sxBlock.pnodeStmt != nullptr)
  8982. {
  8983. EmitBlock(pnode, byteCodeGenerator, funcInfo, fReturnValue);
  8984. if (pnode->emitLabels)
  8985. {
  8986. byteCodeGenerator->Writer()->MarkLabel(pnode->sxStmt.breakLabel);
  8987. }
  8988. }
  8989. break;
  8990. // PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  8991. case knopWith:
  8992. {
  8993. Assert(pnode->sxWith.pnodeObj != nullptr);
  8994. byteCodeGenerator->StartStatement(pnode);
  8995. // Copy the with object to a temp register (the location assigned to pnode) so that if the with object
  8996. // is overwritten in the body, the lookups are not affected.
  8997. funcInfo->AcquireLoc(pnode);
  8998. Emit(pnode->sxWith.pnodeObj, byteCodeGenerator, funcInfo, false);
  8999. Js::RegSlot regVal = (byteCodeGenerator->GetScriptContext()->GetConfig()->IsES6UnscopablesEnabled()) ? funcInfo->AcquireTmpRegister() : pnode->location;
  9000. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Obj, regVal, pnode->sxWith.pnodeObj->location);
  9001. if (byteCodeGenerator->GetScriptContext()->GetConfig()->IsES6UnscopablesEnabled())
  9002. {
  9003. byteCodeGenerator->Writer()->Reg2(Js::OpCode::NewWithObject, pnode->location, regVal);
  9004. }
  9005. byteCodeGenerator->EndStatement(pnode);
  9006. #ifdef PERF_HINT
  9007. if (PHASE_TRACE1(Js::PerfHintPhase))
  9008. {
  9009. WritePerfHint(PerfHints::HasWithBlock, funcInfo->byteCodeFunction->GetFunctionBody(), byteCodeGenerator->Writer()->GetCurrentOffset() - 1);
  9010. }
  9011. #endif
  9012. if (pnode->sxWith.pnodeBody != nullptr)
  9013. {
  9014. Scope *scope = pnode->sxWith.scope;
  9015. scope->SetLocation(pnode->location);
  9016. byteCodeGenerator->PushScope(scope);
  9017. Js::DebuggerScope *debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnode, Js::DiagExtraScopesType::DiagWithScope, regVal);
  9018. if (byteCodeGenerator->ShouldTrackDebuggerMetadata())
  9019. {
  9020. byteCodeGenerator->Writer()->AddPropertyToDebuggerScope(debuggerScope, regVal, Js::Constants::NoProperty, /*shouldConsumeRegister*/ true, Js::DebuggerScopePropertyFlags_WithObject);
  9021. }
  9022. Emit(pnode->sxWith.pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  9023. funcInfo->ReleaseLoc(pnode->sxWith.pnodeBody);
  9024. byteCodeGenerator->PopScope();
  9025. byteCodeGenerator->RecordEndScopeObject(pnode);
  9026. }
  9027. if (pnode->emitLabels)
  9028. {
  9029. byteCodeGenerator->Writer()->MarkLabel(pnode->sxStmt.breakLabel);
  9030. }
  9031. if (byteCodeGenerator->GetScriptContext()->GetConfig()->IsES6UnscopablesEnabled())
  9032. {
  9033. funcInfo->ReleaseTmpRegister(regVal);
  9034. }
  9035. funcInfo->ReleaseLoc(pnode->sxWith.pnodeObj);
  9036. break;
  9037. }
  9038. // PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  9039. case knopBreak:
  9040. Assert(pnode->sxJump.pnodeTarget->emitLabels);
  9041. byteCodeGenerator->StartStatement(pnode);
  9042. if (pnode->sxStmt.grfnop & fnopCleanup)
  9043. {
  9044. EmitJumpCleanup(pnode, pnode->sxJump.pnodeTarget, byteCodeGenerator, funcInfo);
  9045. }
  9046. byteCodeGenerator->Writer()->Br(pnode->sxJump.pnodeTarget->sxStmt.breakLabel);
  9047. if (pnode->emitLabels)
  9048. {
  9049. byteCodeGenerator->Writer()->MarkLabel(pnode->sxStmt.breakLabel);
  9050. }
  9051. byteCodeGenerator->EndStatement(pnode);
  9052. break;
  9053. case knopContinue:
  9054. Assert(pnode->sxJump.pnodeTarget->emitLabels);
  9055. byteCodeGenerator->StartStatement(pnode);
  9056. if (pnode->sxStmt.grfnop & fnopCleanup)
  9057. {
  9058. EmitJumpCleanup(pnode, pnode->sxJump.pnodeTarget, byteCodeGenerator, funcInfo);
  9059. }
  9060. byteCodeGenerator->Writer()->Br(pnode->sxJump.pnodeTarget->sxStmt.continueLabel);
  9061. byteCodeGenerator->EndStatement(pnode);
  9062. break;
  9063. // PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  9064. case knopSwitch:
  9065. {
  9066. BOOL fHasDefault = false;
  9067. Assert(pnode->sxSwitch.pnodeVal != nullptr);
  9068. byteCodeGenerator->StartStatement(pnode);
  9069. Emit(pnode->sxSwitch.pnodeVal, byteCodeGenerator, funcInfo, false);
  9070. Js::RegSlot regVal = funcInfo->AcquireTmpRegister();
  9071. byteCodeGenerator->Writer()->Reg2(Js::OpCode::BeginSwitch, regVal, pnode->sxSwitch.pnodeVal->location);
  9072. BeginEmitBlock(pnode->sxSwitch.pnodeBlock, byteCodeGenerator, funcInfo);
  9073. byteCodeGenerator->EndStatement(pnode);
  9074. // TODO: if all cases are compile-time constants, emit a switch statement in the byte
  9075. // code so the BE can optimize it.
  9076. ParseNode *pnodeCase;
  9077. for (pnodeCase = pnode->sxSwitch.pnodeCases; pnodeCase; pnodeCase = pnodeCase->sxCase.pnodeNext)
  9078. {
  9079. // Jump to the first case body if this one doesn't match. Make sure any side-effects of the case
  9080. // expression take place regardless.
  9081. pnodeCase->sxCase.labelCase = byteCodeGenerator->Writer()->DefineLabel();
  9082. if (pnodeCase == pnode->sxSwitch.pnodeDefault)
  9083. {
  9084. fHasDefault = true;
  9085. continue;
  9086. }
  9087. Emit(pnodeCase->sxCase.pnodeExpr, byteCodeGenerator, funcInfo, false);
  9088. byteCodeGenerator->Writer()->BrReg2(
  9089. Js::OpCode::Case, pnodeCase->sxCase.labelCase, regVal, pnodeCase->sxCase.pnodeExpr->location);
  9090. funcInfo->ReleaseLoc(pnodeCase->sxCase.pnodeExpr);
  9091. }
  9092. // No explicit case value matches. Jump to the default arm (if any) or break out altogether.
  9093. if (fHasDefault)
  9094. {
  9095. byteCodeGenerator->Writer()->Br(Js::OpCode::EndSwitch, pnode->sxSwitch.pnodeDefault->sxCase.labelCase);
  9096. }
  9097. else
  9098. {
  9099. if (!pnode->emitLabels)
  9100. {
  9101. pnode->sxStmt.breakLabel = byteCodeGenerator->Writer()->DefineLabel();
  9102. }
  9103. byteCodeGenerator->Writer()->Br(Js::OpCode::EndSwitch, pnode->sxStmt.breakLabel);
  9104. }
  9105. // Now emit the case arms to which we jump on matching a case value.
  9106. for (pnodeCase = pnode->sxSwitch.pnodeCases; pnodeCase; pnodeCase = pnodeCase->sxCase.pnodeNext)
  9107. {
  9108. byteCodeGenerator->Writer()->MarkLabel(pnodeCase->sxCase.labelCase);
  9109. Emit(pnodeCase->sxCase.pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  9110. funcInfo->ReleaseLoc(pnodeCase->sxCase.pnodeBody);
  9111. }
  9112. EndEmitBlock(pnode->sxSwitch.pnodeBlock, byteCodeGenerator, funcInfo);
  9113. funcInfo->ReleaseTmpRegister(regVal);
  9114. funcInfo->ReleaseLoc(pnode->sxSwitch.pnodeVal);
  9115. if (!fHasDefault || pnode->emitLabels)
  9116. {
  9117. byteCodeGenerator->Writer()->MarkLabel(pnode->sxStmt.breakLabel);
  9118. }
  9119. break;
  9120. }
  9121. case knopTryCatch:
  9122. {
  9123. Js::ByteCodeLabel catchLabel = (Js::ByteCodeLabel) - 1;
  9124. ParseNode *pnodeTry = pnode->sxTryCatch.pnodeTry;
  9125. Assert(pnodeTry);
  9126. ParseNode *pnodeCatch = pnode->sxTryCatch.pnodeCatch;
  9127. Assert(pnodeCatch);
  9128. catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  9129. // Note: try uses OpCode::Leave which causes a return to parent interpreter thunk,
  9130. // same for catch block. Thus record cross interpreter frame entry/exit records for them.
  9131. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  9132. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  9133. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryCatch, catchLabel);
  9134. if (funcInfo->byteCodeFunction->IsGenerator())
  9135. {
  9136. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  9137. }
  9138. Emit(pnodeTry->sxTry.pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  9139. funcInfo->ReleaseLoc(pnodeTry->sxTry.pnodeBody);
  9140. if (funcInfo->byteCodeFunction->IsGenerator())
  9141. {
  9142. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  9143. }
  9144. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  9145. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  9146. byteCodeGenerator->Writer()->Br(pnode->sxStmt.breakLabel);
  9147. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  9148. Assert(pnodeCatch->sxCatch.pnodeParam);
  9149. ParseNode *pnodeObj = pnodeCatch->sxCatch.pnodeParam;
  9150. Js::RegSlot location;
  9151. bool acquiredTempLocation = false;
  9152. Js::DebuggerScope *debuggerScope = nullptr;
  9153. Js::DebuggerScopePropertyFlags debuggerPropertyFlags = Js::DebuggerScopePropertyFlags_CatchObject;
  9154. bool isPattern = pnodeObj->nop == knopParamPattern;
  9155. if (isPattern)
  9156. {
  9157. location = pnodeObj->sxParamPattern.location;
  9158. }
  9159. else
  9160. {
  9161. location = pnodeObj->sxPid.sym->GetLocation();
  9162. }
  9163. if (location == Js::Constants::NoRegister)
  9164. {
  9165. location = funcInfo->AcquireLoc(pnodeObj);
  9166. acquiredTempLocation = true;
  9167. }
  9168. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, location);
  9169. Scope *scope = pnodeCatch->sxCatch.scope;
  9170. if (isPattern || scope->GetMustInstantiate())
  9171. {
  9172. byteCodeGenerator->PushScope(scope);
  9173. }
  9174. if (scope->GetMustInstantiate())
  9175. {
  9176. Assert(scope->GetLocation() == Js::Constants::NoRegister);
  9177. if (scope->GetIsObject())
  9178. {
  9179. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnode, Js::DiagCatchScopeInObject, funcInfo->InnerScopeToRegSlot(scope));
  9180. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::NewPseudoScope, scope->GetInnerScopeIndex());
  9181. }
  9182. else
  9183. {
  9184. int index = Js::DebuggerScope::InvalidScopeIndex;
  9185. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnode, Js::DiagCatchScopeInSlot, funcInfo->InnerScopeToRegSlot(scope), &index);
  9186. byteCodeGenerator->Writer()->Num3(Js::OpCode::NewInnerScopeSlots, scope->GetInnerScopeIndex(), scope->GetScopeSlotCount() + Js::ScopeSlots::FirstSlotIndex, index);
  9187. }
  9188. }
  9189. else
  9190. {
  9191. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnode, Js::DiagCatchScopeDirect, location);
  9192. }
  9193. auto ParamTrackAndInitialization = [&](Symbol *sym, bool initializeParam, Js::RegSlot location)
  9194. {
  9195. if (sym->IsInSlot(funcInfo))
  9196. {
  9197. Assert(scope->GetMustInstantiate());
  9198. if (scope->GetIsObject())
  9199. {
  9200. Js::OpCode op = (sym->GetDecl()->nop == knopLetDecl) ? Js::OpCode::InitUndeclLetFld :
  9201. byteCodeGenerator->GetInitFldOp(scope, scope->GetLocation(), funcInfo, false);
  9202. Js::PropertyId propertyId = sym->EnsurePosition(byteCodeGenerator);
  9203. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
  9204. byteCodeGenerator->Writer()->ElementPIndexed(op, location, scope->GetInnerScopeIndex(), cacheId);
  9205. byteCodeGenerator->TrackActivationObjectPropertyForDebugger(debuggerScope, sym, debuggerPropertyFlags);
  9206. }
  9207. else
  9208. {
  9209. byteCodeGenerator->TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(byteCodeGenerator), debuggerPropertyFlags);
  9210. if (initializeParam)
  9211. {
  9212. byteCodeGenerator->EmitLocalPropInit(location, sym, funcInfo);
  9213. }
  9214. else
  9215. {
  9216. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  9217. byteCodeGenerator->Writer()->Reg1(Js::OpCode::InitUndecl, tmpReg);
  9218. byteCodeGenerator->EmitLocalPropInit(tmpReg, sym, funcInfo);
  9219. funcInfo->ReleaseTmpRegister(tmpReg);
  9220. }
  9221. }
  9222. }
  9223. else
  9224. {
  9225. byteCodeGenerator->TrackRegisterPropertyForDebugger(debuggerScope, sym, funcInfo, debuggerPropertyFlags);
  9226. if (initializeParam)
  9227. {
  9228. byteCodeGenerator->EmitLocalPropInit(location, sym, funcInfo);
  9229. }
  9230. else
  9231. {
  9232. byteCodeGenerator->Writer()->Reg1(Js::OpCode::InitUndecl, location);
  9233. }
  9234. }
  9235. };
  9236. if (isPattern)
  9237. {
  9238. Parser::MapBindIdentifier(pnodeObj->sxParamPattern.pnode1, [&](ParseNodePtr item)
  9239. {
  9240. ParamTrackAndInitialization(item->sxVar.sym, false /*initializeParam*/, item->sxVar.sym->GetLocation());
  9241. });
  9242. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  9243. // Now emitting bytecode for destructuring pattern
  9244. byteCodeGenerator->StartStatement(pnodeCatch);
  9245. ParseNodePtr pnode1 = pnodeObj->sxParamPattern.pnode1;
  9246. Assert(pnode1->IsPattern());
  9247. EmitAssignment(nullptr, pnode1, location, byteCodeGenerator, funcInfo);
  9248. byteCodeGenerator->EndStatement(pnodeCatch);
  9249. }
  9250. else
  9251. {
  9252. ParamTrackAndInitialization(pnodeObj->sxPid.sym, true /*initializeParam*/, location);
  9253. if (scope->GetMustInstantiate())
  9254. {
  9255. pnodeObj->sxPid.sym->SetIsGlobalCatch(true);
  9256. }
  9257. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  9258. // Allow a debugger to stop on the 'catch (e)'
  9259. byteCodeGenerator->StartStatement(pnodeCatch);
  9260. byteCodeGenerator->Writer()->Empty(Js::OpCode::Nop);
  9261. byteCodeGenerator->EndStatement(pnodeCatch);
  9262. }
  9263. ByteCodeGenerator::TryScopeRecord tryRecForCatch(Js::OpCode::ResumeCatch, catchLabel);
  9264. if (funcInfo->byteCodeFunction->IsGenerator())
  9265. {
  9266. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForCatch);
  9267. }
  9268. Emit(pnodeCatch->sxCatch.pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  9269. if (funcInfo->byteCodeFunction->IsGenerator())
  9270. {
  9271. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  9272. }
  9273. if (scope->GetMustInstantiate() || isPattern)
  9274. {
  9275. byteCodeGenerator->PopScope();
  9276. }
  9277. byteCodeGenerator->RecordEndScopeObject(pnode);
  9278. funcInfo->ReleaseLoc(pnodeCatch->sxCatch.pnodeBody);
  9279. if (acquiredTempLocation)
  9280. {
  9281. funcInfo->ReleaseLoc(pnodeObj);
  9282. }
  9283. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  9284. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  9285. byteCodeGenerator->Writer()->MarkLabel(pnode->sxStmt.breakLabel);
  9286. break;
  9287. }
  9288. case knopTryFinally:
  9289. {
  9290. Js::ByteCodeLabel finallyLabel = (Js::ByteCodeLabel) - 1;
  9291. ParseNode *pnodeTry = pnode->sxTryFinally.pnodeTry;
  9292. Assert(pnodeTry);
  9293. ParseNode *pnodeFinally = pnode->sxTryFinally.pnodeFinally;
  9294. Assert(pnodeFinally);
  9295. // If we yield from the finally block after an exception, we have to store the exception object for the future next call.
  9296. // When we yield from the Try-Finally the offset to the end of the Try block is needed for the branch instruction.
  9297. Js::RegSlot regException = Js::Constants::NoRegister;
  9298. Js::RegSlot regOffset = Js::Constants::NoRegister;
  9299. finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  9300. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  9301. // [CONSIDER][aneeshd] Ideally the TryFinallyWithYield opcode needs to be used only if there is a yield expression.
  9302. // For now, if the function is generator we are using the TryFinallyWithYield.
  9303. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryFinallyWithYield, finallyLabel);
  9304. if (funcInfo->byteCodeFunction->IsGenerator())
  9305. {
  9306. regException = funcInfo->AcquireTmpRegister();
  9307. regOffset = funcInfo->AcquireTmpRegister();
  9308. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  9309. tryRecForTry.reg1 = regException;
  9310. tryRecForTry.reg2 = regOffset;
  9311. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  9312. }
  9313. else
  9314. {
  9315. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  9316. }
  9317. Emit(pnodeTry->sxTry.pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  9318. funcInfo->ReleaseLoc(pnodeTry->sxTry.pnodeBody);
  9319. if (funcInfo->byteCodeFunction->IsGenerator())
  9320. {
  9321. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  9322. }
  9323. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  9324. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  9325. // Note: although we don't use OpCode::Leave for finally block,
  9326. // OpCode::LeaveNull causes a return to parent interpreter thunk.
  9327. // This has to be on offset prior to offset of 1st statement of finally.
  9328. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  9329. byteCodeGenerator->Writer()->Br(pnode->sxStmt.breakLabel);
  9330. byteCodeGenerator->Writer()->MarkLabel(finallyLabel);
  9331. ByteCodeGenerator::TryScopeRecord tryRecForFinally(Js::OpCode::ResumeFinally, finallyLabel, regException, regOffset);
  9332. if (funcInfo->byteCodeFunction->IsGenerator())
  9333. {
  9334. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForFinally);
  9335. }
  9336. Emit(pnodeFinally->sxFinally.pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  9337. funcInfo->ReleaseLoc(pnodeFinally->sxFinally.pnodeBody);
  9338. if (funcInfo->byteCodeFunction->IsGenerator())
  9339. {
  9340. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  9341. funcInfo->ReleaseTmpRegister(regOffset);
  9342. funcInfo->ReleaseTmpRegister(regException);
  9343. }
  9344. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  9345. byteCodeGenerator->Writer()->Empty(Js::OpCode::LeaveNull);
  9346. byteCodeGenerator->Writer()->MarkLabel(pnode->sxStmt.breakLabel);
  9347. break;
  9348. }
  9349. case knopThrow:
  9350. byteCodeGenerator->StartStatement(pnode);
  9351. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  9352. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Throw, pnode->sxUni.pnode1->location);
  9353. funcInfo->ReleaseLoc(pnode->sxUni.pnode1);
  9354. byteCodeGenerator->EndStatement(pnode);
  9355. break;
  9356. case knopYieldLeaf:
  9357. byteCodeGenerator->StartStatement(pnode);
  9358. funcInfo->AcquireLoc(pnode);
  9359. EmitYield(funcInfo->undefinedConstantRegister, pnode->location, byteCodeGenerator, funcInfo);
  9360. byteCodeGenerator->EndStatement(pnode);
  9361. break;
  9362. case knopAwait:
  9363. case knopYield:
  9364. byteCodeGenerator->StartStatement(pnode);
  9365. funcInfo->AcquireLoc(pnode);
  9366. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  9367. EmitYield(pnode->sxUni.pnode1->location, pnode->location, byteCodeGenerator, funcInfo);
  9368. funcInfo->ReleaseLoc(pnode->sxUni.pnode1);
  9369. byteCodeGenerator->EndStatement(pnode);
  9370. break;
  9371. case knopYieldStar:
  9372. byteCodeGenerator->StartStatement(pnode);
  9373. EmitYieldStar(pnode, byteCodeGenerator, funcInfo);
  9374. byteCodeGenerator->EndStatement(pnode);
  9375. break;
  9376. case knopAsyncSpawn:
  9377. EmitBinary(Js::OpCode::AsyncSpawn, pnode, byteCodeGenerator, funcInfo);
  9378. break;
  9379. default:
  9380. AssertMsg(0, "emit unhandled pnode op");
  9381. break;
  9382. }
  9383. if (fReturnValue && IsExpressionStatement(pnode, byteCodeGenerator->GetScriptContext()))
  9384. {
  9385. // If this statement may produce the global function's return value, copy its result to the return register.
  9386. // fReturnValue implies global function, which implies that "return" is a parse error.
  9387. Assert(funcInfo->IsGlobalFunction());
  9388. Assert(pnode->nop != knopReturn);
  9389. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, pnode->location);
  9390. }
  9391. }