ByteCodeEmitter.cpp 461 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727
  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. #include "ConfigFlagsList.h"
  9. void EmitReference(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  10. void EmitAssignment(ParseNode *asgnNode, ParseNode *lhs, Js::RegSlot rhsLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  11. void EmitLoad(ParseNode *rhs, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  12. void EmitCall(ParseNodeCall* pnodeCall, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue, BOOL fEvaluateComponents, Js::RegSlot overrideThisLocation = Js::Constants::NoRegister, Js::RegSlot newTargetLocation = Js::Constants::NoRegister);
  13. void EmitYield(Js::RegSlot inputLocation, Js::RegSlot resultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot yieldStarIterator = Js::Constants::NoRegister);
  14. void EmitUseBeforeDeclaration(Symbol *sym, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  15. void EmitUseBeforeDeclarationRuntimeError(ByteCodeGenerator *byteCodeGenerator, Js::RegSlot location);
  16. void VisitClearTmpRegs(ParseNode * pnode, ByteCodeGenerator * byteCodeGenerator, FuncInfo * funcInfo);
  17. bool CallTargetIsArray(ParseNode *pnode)
  18. {
  19. return pnode->nop == knopName && pnode->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::Array;
  20. }
  21. #define STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode) \
  22. if ((isTopLevel)) \
  23. { \
  24. byteCodeGenerator->StartStatement(pnode); \
  25. }
  26. #define ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode) \
  27. if ((isTopLevel)) \
  28. { \
  29. byteCodeGenerator->EndStatement(pnode); \
  30. }
  31. BOOL MayHaveSideEffectOnNode(ParseNode *pnode, ParseNode *pnodeSE)
  32. {
  33. // Try to determine whether pnodeSE may kill the named var represented by pnode.
  34. if (pnode->nop == knopComputedName)
  35. {
  36. pnode = pnode->AsParseNodeUni()->pnode1;
  37. }
  38. if (pnode->nop != knopName)
  39. {
  40. // Only investigating named vars here.
  41. return false;
  42. }
  43. uint fnop = ParseNode::Grfnop(pnodeSE->nop);
  44. if (fnop & fnopLeaf)
  45. {
  46. // pnodeSE is a leaf and can't kill anything.
  47. return false;
  48. }
  49. if (fnop & fnopAsg)
  50. {
  51. // pnodeSE is an assignment (=, ++, +=, etc.)
  52. // Trying to examine the LHS of pnodeSE caused small perf regressions,
  53. // maybe because of code layout or some other subtle effect.
  54. return true;
  55. }
  56. if (fnop & fnopUni)
  57. {
  58. // pnodeSE is a unary op, so recurse to the source (if present - e.g., [] may have no opnd).
  59. if (pnodeSE->nop == knopTempRef)
  60. {
  61. return false;
  62. }
  63. else
  64. {
  65. return pnodeSE->AsParseNodeUni()->pnode1 && MayHaveSideEffectOnNode(pnode, pnodeSE->AsParseNodeUni()->pnode1);
  66. }
  67. }
  68. else if (fnop & fnopBin)
  69. {
  70. // pnodeSE is a binary (or ternary) op, so recurse to the sources (if present).
  71. return MayHaveSideEffectOnNode(pnode, pnodeSE->AsParseNodeBin()->pnode1) ||
  72. (pnodeSE->AsParseNodeBin()->pnode2 && MayHaveSideEffectOnNode(pnode, pnodeSE->AsParseNodeBin()->pnode2));
  73. }
  74. else if (pnodeSE->nop == knopQmark)
  75. {
  76. ParseNodeTri * pnodeTriSE = pnodeSE->AsParseNodeTri();
  77. return MayHaveSideEffectOnNode(pnode, pnodeTriSE->pnode1) ||
  78. MayHaveSideEffectOnNode(pnode, pnodeTriSE->pnode2) ||
  79. MayHaveSideEffectOnNode(pnode, pnodeTriSE->pnode3);
  80. }
  81. else if (pnodeSE->nop == knopCall || pnodeSE->nop == knopNew)
  82. {
  83. return MayHaveSideEffectOnNode(pnode, pnodeSE->AsParseNodeCall()->pnodeTarget) ||
  84. (pnodeSE->AsParseNodeCall()->pnodeArgs && MayHaveSideEffectOnNode(pnode, pnodeSE->AsParseNodeCall()->pnodeArgs));
  85. }
  86. else if (pnodeSE->nop == knopList)
  87. {
  88. return true;
  89. }
  90. return false;
  91. }
  92. bool IsCallOfConstants(ParseNode *pnode);
  93. bool BlockHasOwnScope(ParseNodeBlock * pnodeBlock, ByteCodeGenerator *byteCodeGenerator);
  94. bool CreateNativeArrays(ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  95. bool IsArguments(ParseNode *pnode)
  96. {
  97. for (;;)
  98. {
  99. switch (pnode->nop)
  100. {
  101. case knopName:
  102. return pnode->AsParseNodeName()->sym && pnode->AsParseNodeName()->sym->IsArguments();
  103. case knopCall:
  104. case knopNew:
  105. if (IsArguments(pnode->AsParseNodeCall()->pnodeTarget))
  106. {
  107. return true;
  108. }
  109. if (pnode->AsParseNodeCall()->pnodeArgs)
  110. {
  111. ParseNode *pnodeArg = pnode->AsParseNodeCall()->pnodeArgs;
  112. while (pnodeArg->nop == knopList)
  113. {
  114. if (IsArguments(pnodeArg->AsParseNodeBin()->pnode1))
  115. return true;
  116. pnodeArg = pnodeArg->AsParseNodeBin()->pnode2;
  117. }
  118. pnode = pnodeArg;
  119. break;
  120. }
  121. return false;
  122. case knopArray:
  123. if (pnode->AsParseNodeArrLit()->arrayOfNumbers || pnode->AsParseNodeArrLit()->count == 0)
  124. {
  125. return false;
  126. }
  127. pnode = pnode->AsParseNodeUni()->pnode1;
  128. break;
  129. case knopQmark:
  130. if (IsArguments(pnode->AsParseNodeTri()->pnode1) || IsArguments(pnode->AsParseNodeTri()->pnode2))
  131. {
  132. return true;
  133. }
  134. pnode = pnode->AsParseNodeTri()->pnode3;
  135. break;
  136. //
  137. // Cases where we don't check for "arguments" yet.
  138. // Assume that they might have it. Disable the optimization is such scenarios
  139. //
  140. case knopList:
  141. case knopObject:
  142. case knopVarDecl:
  143. case knopConstDecl:
  144. case knopLetDecl:
  145. case knopFncDecl:
  146. case knopClassDecl:
  147. case knopFor:
  148. case knopIf:
  149. case knopDoWhile:
  150. case knopWhile:
  151. case knopForIn:
  152. case knopForOf:
  153. case knopReturn:
  154. case knopBlock:
  155. case knopBreak:
  156. case knopContinue:
  157. case knopTypeof:
  158. case knopThrow:
  159. case knopWith:
  160. case knopFinally:
  161. case knopTry:
  162. case knopTryCatch:
  163. case knopTryFinally:
  164. case knopArrayPattern:
  165. case knopObjectPattern:
  166. case knopParamPattern:
  167. return true;
  168. default:
  169. {
  170. uint flags = ParseNode::Grfnop(pnode->nop);
  171. if (flags&fnopUni)
  172. {
  173. ParseNodeUni * pnodeUni = pnode->AsParseNodeUni();
  174. Assert(pnodeUni->pnode1);
  175. pnode = pnodeUni->pnode1;
  176. break;
  177. }
  178. else if (flags&fnopBin)
  179. {
  180. ParseNodeBin * pnodeBin = pnode->AsParseNodeBin();
  181. Assert(pnodeBin->pnode1 && pnodeBin->pnode2);
  182. if (IsArguments(pnodeBin->pnode1))
  183. {
  184. return true;
  185. }
  186. pnode = pnodeBin->pnode2;
  187. break;
  188. }
  189. return false;
  190. }
  191. }
  192. }
  193. }
  194. bool ApplyEnclosesArgs(ParseNode* fncDecl, ByteCodeGenerator* byteCodeGenerator);
  195. void Emit(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue, bool isConstructorCall = false, ParseNode *bindPnode = nullptr, bool isTopLevel = false);
  196. void EmitBinaryOpnds(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  197. bool IsExpressionStatement(ParseNode* stmt, const Js::ScriptContext *const scriptContext);
  198. void EmitInvoke(Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  199. void EmitInvoke(Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot arg1Location);
  200. static const Js::OpCode nopToOp[knopLim] =
  201. {
  202. #define OP(x) Br##x##_A
  203. #define PTNODE(nop,sn,pc,nk,grfnop,json) Js::OpCode::pc,
  204. #include "ptlist.h"
  205. };
  206. static const Js::OpCode nopToCMOp[knopLim] =
  207. {
  208. #define OP(x) Cm##x##_A
  209. #define PTNODE(nop,sn,pc,nk,grfnop,json) Js::OpCode::pc,
  210. #include "ptlist.h"
  211. };
  212. Js::OpCode ByteCodeGenerator::ToChkUndeclOp(Js::OpCode op) const
  213. {
  214. switch (op)
  215. {
  216. case Js::OpCode::StLocalSlot:
  217. return Js::OpCode::StLocalSlotChkUndecl;
  218. case Js::OpCode::StParamSlot:
  219. return Js::OpCode::StParamSlotChkUndecl;
  220. case Js::OpCode::StInnerSlot:
  221. return Js::OpCode::StInnerSlotChkUndecl;
  222. case Js::OpCode::StEnvSlot:
  223. return Js::OpCode::StEnvSlotChkUndecl;
  224. case Js::OpCode::StObjSlot:
  225. return Js::OpCode::StObjSlotChkUndecl;
  226. case Js::OpCode::StLocalObjSlot:
  227. return Js::OpCode::StLocalObjSlotChkUndecl;
  228. case Js::OpCode::StParamObjSlot:
  229. return Js::OpCode::StParamObjSlotChkUndecl;
  230. case Js::OpCode::StInnerObjSlot:
  231. return Js::OpCode::StInnerObjSlotChkUndecl;
  232. case Js::OpCode::StEnvObjSlot:
  233. return Js::OpCode::StEnvObjSlotChkUndecl;
  234. default:
  235. AssertMsg(false, "Unknown opcode for chk undecl mapping");
  236. return Js::OpCode::InvalidOpCode;
  237. }
  238. }
  239. // Tracks a register slot let/const property for the passed in debugger block/catch scope.
  240. // debuggerScope - The scope to add the variable to.
  241. // symbol - The symbol that represents the register property.
  242. // funcInfo - The function info used to store the property into the tracked debugger register slot list.
  243. // flags - The flags to assign to the property.
  244. // isFunctionDeclaration - Whether or not the register is a function declaration, which requires that its byte code offset be updated immediately.
  245. void ByteCodeGenerator::TrackRegisterPropertyForDebugger(
  246. Js::DebuggerScope *debuggerScope,
  247. Symbol *symbol,
  248. FuncInfo *funcInfo,
  249. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  250. bool isFunctionDeclaration /*= false*/)
  251. {
  252. Assert(debuggerScope);
  253. Assert(symbol);
  254. Assert(funcInfo);
  255. Js::RegSlot location = symbol->GetLocation();
  256. Js::DebuggerScope *correctDebuggerScope = debuggerScope;
  257. if (debuggerScope->scopeType != Js::DiagExtraScopesType::DiagBlockScopeDirect && debuggerScope->scopeType != Js::DiagExtraScopesType::DiagCatchScopeDirect)
  258. {
  259. // We have to get the appropriate scope and add property over there.
  260. // Make sure the scope is created whether we're in debug mode or not, because we
  261. // need the empty scopes present during reparsing for debug mode.
  262. correctDebuggerScope = debuggerScope->GetSiblingScope(location, Writer()->GetFunctionWrite());
  263. }
  264. if (this->ShouldTrackDebuggerMetadata() && !symbol->GetIsTrackedForDebugger())
  265. {
  266. // Only track the property if we're in debug mode since it's only needed by the debugger.
  267. Js::PropertyId propertyId = symbol->EnsurePosition(this);
  268. this->Writer()->AddPropertyToDebuggerScope(
  269. correctDebuggerScope,
  270. location,
  271. propertyId,
  272. /*shouldConsumeRegister*/ true,
  273. flags,
  274. isFunctionDeclaration);
  275. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  276. byteCodeFunction->InsertSymbolToRegSlotList(location, propertyId, funcInfo->varRegsCount);
  277. symbol->SetIsTrackedForDebugger(true);
  278. }
  279. }
  280. void ByteCodeGenerator::TrackActivationObjectPropertyForDebugger(
  281. Js::DebuggerScope *debuggerScope,
  282. Symbol *symbol,
  283. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  284. bool isFunctionDeclaration /*= false*/)
  285. {
  286. Assert(debuggerScope);
  287. Assert(symbol);
  288. // Only need to track activation object properties in debug mode.
  289. if (ShouldTrackDebuggerMetadata() && !symbol->GetIsTrackedForDebugger())
  290. {
  291. Js::RegSlot location = symbol->GetLocation();
  292. Js::PropertyId propertyId = symbol->EnsurePosition(this);
  293. this->Writer()->AddPropertyToDebuggerScope(
  294. debuggerScope,
  295. location,
  296. propertyId,
  297. /*shouldConsumeRegister*/ false,
  298. flags,
  299. isFunctionDeclaration);
  300. symbol->SetIsTrackedForDebugger(true);
  301. }
  302. }
  303. void ByteCodeGenerator::TrackSlotArrayPropertyForDebugger(
  304. Js::DebuggerScope *debuggerScope,
  305. Symbol* symbol,
  306. Js::PropertyId propertyId,
  307. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  308. bool isFunctionDeclaration /*= false*/)
  309. {
  310. // Note: Slot array properties are tracked even in non-debug mode in order to support slot array serialization
  311. // of let/const variables between non-debug and debug mode (for example, when a slot array var escapes and is retrieved
  312. // after a debugger attach or for WWA apps). They are also needed for heap enumeration.
  313. Assert(debuggerScope);
  314. Assert(symbol);
  315. if (!symbol->GetIsTrackedForDebugger())
  316. {
  317. Js::RegSlot location = symbol->GetScopeSlot();
  318. Assert(location != Js::Constants::NoRegister);
  319. Assert(propertyId != Js::Constants::NoProperty);
  320. this->Writer()->AddPropertyToDebuggerScope(
  321. debuggerScope,
  322. location,
  323. propertyId,
  324. /*shouldConsumeRegister*/ false,
  325. flags,
  326. isFunctionDeclaration);
  327. symbol->SetIsTrackedForDebugger(true);
  328. }
  329. }
  330. // Tracks a function declaration inside a block scope for the debugger metadata's current scope (let binding).
  331. void ByteCodeGenerator::TrackFunctionDeclarationPropertyForDebugger(Symbol *functionDeclarationSymbol, FuncInfo *funcInfoParent)
  332. {
  333. Assert(functionDeclarationSymbol);
  334. Assert(funcInfoParent);
  335. AssertMsg(functionDeclarationSymbol->GetIsBlockVar(), "We should only track inner function let bindings for the debugger.");
  336. // Note: we don't have to check symbol->GetIsTrackedForDebugger, as we are not doing actual work here,
  337. // which is done in other Track* functions that we call.
  338. if (functionDeclarationSymbol->IsInSlot(this, funcInfoParent))
  339. {
  340. if (functionDeclarationSymbol->GetScope()->GetIsObject())
  341. {
  342. this->TrackActivationObjectPropertyForDebugger(
  343. this->Writer()->GetCurrentDebuggerScope(),
  344. functionDeclarationSymbol,
  345. Js::DebuggerScopePropertyFlags_None,
  346. true /*isFunctionDeclaration*/);
  347. }
  348. else
  349. {
  350. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  351. // Note that slot array inner function bindings are tracked even in non-debug mode in order
  352. // to keep the lifetime of the closure binding that could escape around for heap enumeration.
  353. functionDeclarationSymbol->EnsureScopeSlot(this, funcInfoParent);
  354. functionDeclarationSymbol->EnsurePosition(this);
  355. this->TrackSlotArrayPropertyForDebugger(
  356. this->Writer()->GetCurrentDebuggerScope(),
  357. functionDeclarationSymbol,
  358. functionDeclarationSymbol->GetPosition(),
  359. Js::DebuggerScopePropertyFlags_None,
  360. true /*isFunctionDeclaration*/);
  361. }
  362. }
  363. else
  364. {
  365. this->TrackRegisterPropertyForDebugger(
  366. this->Writer()->GetCurrentDebuggerScope(),
  367. functionDeclarationSymbol,
  368. funcInfoParent,
  369. Js::DebuggerScopePropertyFlags_None,
  370. true /*isFunctionDeclaration*/);
  371. }
  372. }
  373. // Updates the byte code offset of the property with the passed in location and ID.
  374. // Used to track let/const variables that are in the dead zone debugger side.
  375. // location - The activation object, scope slot index, or register location for the property.
  376. // propertyId - The ID of the property to update.
  377. // shouldConsumeRegister - Whether or not the a register should be consumed (used for reg slot locations).
  378. void ByteCodeGenerator::UpdateDebuggerPropertyInitializationOffset(Js::RegSlot location, Js::PropertyId propertyId, bool shouldConsumeRegister)
  379. {
  380. Assert(this->Writer());
  381. Js::DebuggerScope* currentDebuggerScope = this->Writer()->GetCurrentDebuggerScope();
  382. Assert(currentDebuggerScope);
  383. if (currentDebuggerScope != nullptr)
  384. {
  385. this->Writer()->UpdateDebuggerPropertyInitializationOffset(
  386. currentDebuggerScope,
  387. location,
  388. propertyId,
  389. shouldConsumeRegister);
  390. }
  391. }
  392. void ByteCodeGenerator::LoadHeapArguments(FuncInfo *funcInfo)
  393. {
  394. if (funcInfo->GetHasCachedScope())
  395. {
  396. this->LoadCachedHeapArguments(funcInfo);
  397. }
  398. else
  399. {
  400. this->LoadUncachedHeapArguments(funcInfo);
  401. }
  402. }
  403. void GetFormalArgsArray(ByteCodeGenerator *byteCodeGenerator, FuncInfo * funcInfo, Js::PropertyIdArray *propIds)
  404. {
  405. Assert(funcInfo);
  406. Assert(propIds);
  407. Assert(byteCodeGenerator);
  408. bool hadDuplicates = false;
  409. Js::ArgSlot i = 0;
  410. auto processArg = [&](ParseNode *pnode)
  411. {
  412. if (pnode->IsVarLetOrConst())
  413. {
  414. Assert(i < propIds->count);
  415. Symbol *sym = pnode->AsParseNodeVar()->sym;
  416. Assert(sym);
  417. Js::PropertyId symPos = sym->EnsurePosition(byteCodeGenerator);
  418. //
  419. // Check if the function has any same name parameters
  420. // For the same name param, only the last one will be passed the correct propertyid
  421. // For remaining dup param names, pass Constants::NoProperty
  422. //
  423. for (Js::ArgSlot j = 0; j < i; j++)
  424. {
  425. if (propIds->elements[j] == symPos)
  426. {
  427. // Found a dup parameter name
  428. propIds->elements[j] = Js::Constants::NoProperty;
  429. hadDuplicates = true;
  430. break;
  431. }
  432. }
  433. propIds->elements[i] = symPos;
  434. }
  435. else
  436. {
  437. propIds->elements[i] = Js::Constants::NoProperty;
  438. }
  439. ++i;
  440. };
  441. MapFormals(funcInfo->root, processArg);
  442. propIds->hadDuplicates = hadDuplicates;
  443. }
  444. void ByteCodeGenerator::LoadUncachedHeapArguments(FuncInfo *funcInfo)
  445. {
  446. Assert(funcInfo->GetHasHeapArguments());
  447. Scope *scope = funcInfo->GetBodyScope();
  448. Assert(scope);
  449. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  450. Assert(argSym && argSym->IsArguments());
  451. Js::RegSlot argumentsLoc = argSym->GetLocation();
  452. Js::OpCode opcode = !funcInfo->root->HasNonSimpleParameterList() ? Js::OpCode::LdHeapArguments : Js::OpCode::LdLetHeapArguments;
  453. bool hasRest = funcInfo->root->pnodeRest != nullptr;
  454. uint count = funcInfo->inArgsCount + (hasRest ? 1 : 0) - 1;
  455. if (count == 0)
  456. {
  457. // If no formals to function (only "this"), then no need to create the scope object.
  458. // Leave both the arguments location and the propertyIds location as null.
  459. Assert(funcInfo->root->pnodeParams == nullptr && !hasRest);
  460. }
  461. else if (!NeedScopeObjectForArguments(funcInfo, funcInfo->root))
  462. {
  463. // We may not need a scope object for arguments, e.g. strict mode with no eval.
  464. }
  465. else if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  466. {
  467. // Pass the frame object and ID array to the runtime, and put the resulting Arguments object
  468. // at the expected location.
  469. Js::PropertyIdArray *propIds = funcInfo->GetParsedFunctionBody()->AllocatePropertyIdArrayForFormals(UInt32Math::Mul(count, sizeof(Js::PropertyId)), count, 0);
  470. GetFormalArgsArray(this, funcInfo, propIds);
  471. }
  472. this->m_writer.Reg1(opcode, argumentsLoc);
  473. EmitLocalPropInit(argSym->GetLocation(), argSym, funcInfo);
  474. }
  475. void ByteCodeGenerator::LoadCachedHeapArguments(FuncInfo *funcInfo)
  476. {
  477. Assert(funcInfo->GetHasHeapArguments());
  478. Scope *scope = funcInfo->GetBodyScope();
  479. Assert(scope);
  480. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  481. Assert(argSym && argSym->IsArguments());
  482. Js::RegSlot argumentsLoc = argSym->GetLocation();
  483. Js::OpCode op = !funcInfo->root->HasNonSimpleParameterList() ? Js::OpCode::LdHeapArgsCached : Js::OpCode::LdLetHeapArgsCached;
  484. this->m_writer.Reg1(op, argumentsLoc);
  485. EmitLocalPropInit(argumentsLoc, argSym, funcInfo);
  486. }
  487. Js::JavascriptArray* ByteCodeGenerator::BuildArrayFromStringList(ParseNode* stringNodeList, uint arrayLength, Js::ScriptContext* scriptContext)
  488. {
  489. Assert(stringNodeList);
  490. uint index = 0;
  491. Js::Var str;
  492. IdentPtr pid;
  493. Js::JavascriptArray* pArr = scriptContext->GetLibrary()->CreateArray(arrayLength);
  494. while (stringNodeList->nop == knopList)
  495. {
  496. Assert(stringNodeList->AsParseNodeBin()->pnode1->nop == knopStr);
  497. pid = stringNodeList->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid;
  498. str = Js::JavascriptString::NewCopyBuffer(pid->Psz(), pid->Cch(), scriptContext);
  499. pArr->SetItemWithAttributes(index, str, PropertyEnumerable);
  500. stringNodeList = stringNodeList->AsParseNodeBin()->pnode2;
  501. index++;
  502. }
  503. Assert(stringNodeList->nop == knopStr);
  504. pid = stringNodeList->AsParseNodeStr()->pid;
  505. str = Js::JavascriptString::NewCopyBuffer(pid->Psz(), pid->Cch(), scriptContext);
  506. pArr->SetItemWithAttributes(index, str, PropertyEnumerable);
  507. return pArr;
  508. }
  509. // For now, this just assigns field ids for the current script.
  510. // Later, we will combine this information with the global field id map.
  511. // This temporary code will not work if a global member is accessed both with and without a LHS.
  512. void ByteCodeGenerator::AssignPropertyIds(Js::ParseableFunctionInfo* functionInfo)
  513. {
  514. globalScope->ForEachSymbol([this, functionInfo](Symbol * sym)
  515. {
  516. this->AssignPropertyId(sym, functionInfo);
  517. });
  518. }
  519. void ByteCodeGenerator::InitBlockScopedContent(ParseNodeBlock *pnodeBlock, Js::DebuggerScope* debuggerScope, FuncInfo *funcInfo)
  520. {
  521. Assert(pnodeBlock->nop == knopBlock);
  522. auto genBlockInit = [this, debuggerScope, funcInfo](ParseNode *pnode)
  523. {
  524. // Only check if the scope is valid when let/const vars are in the scope. If there are no let/const vars,
  525. // the debugger scope will not be created.
  526. AssertMsg(debuggerScope, "Missing a case of scope tracking in BeginEmitBlock.");
  527. FuncInfo *funcInfo = this->TopFuncInfo();
  528. Symbol *sym = pnode->AsParseNodeVar()->sym;
  529. Scope *scope = sym->GetScope();
  530. if (sym->GetIsGlobal())
  531. {
  532. Js::PropertyId propertyId = sym->EnsurePosition(this);
  533. if (this->flags & fscrEval)
  534. {
  535. AssertMsg(this->IsConsoleScopeEval(), "Let/Consts cannot be in global scope outside of console eval");
  536. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ? Js::OpCode::InitUndeclConsoleConstFld : Js::OpCode::InitUndeclConsoleLetFld;
  537. this->m_writer.ElementScopedU(op, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  538. }
  539. else
  540. {
  541. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  542. Js::OpCode::InitUndeclRootConstFld : Js::OpCode::InitUndeclRootLetFld;
  543. this->m_writer.ElementRootU(op, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  544. }
  545. }
  546. else if (sym->IsInSlot(this, funcInfo) || (scope->GetIsObject() && sym->NeedsSlotAlloc(this, funcInfo)))
  547. {
  548. if (scope->GetIsObject())
  549. {
  550. Js::RegSlot scopeLocation = scope->GetLocation();
  551. Js::PropertyId propertyId = sym->EnsurePosition(this);
  552. if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  553. {
  554. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  555. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  556. Js::OpCode::InitUndeclLocalConstFld : Js::OpCode::InitUndeclLocalLetFld;
  557. this->m_writer.ElementP(op, ByteCodeGenerator::ReturnRegister, cacheId);
  558. }
  559. else
  560. {
  561. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
  562. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  563. Js::OpCode::InitUndeclConstFld : Js::OpCode::InitUndeclLetFld;
  564. this->m_writer.ElementPIndexed(op, ByteCodeGenerator::ReturnRegister, scope->GetInnerScopeIndex(), cacheId);
  565. }
  566. TrackActivationObjectPropertyForDebugger(debuggerScope, sym, pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  567. }
  568. else
  569. {
  570. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  571. this->m_writer.Reg1(Js::OpCode::InitUndecl, tmpReg);
  572. this->EmitLocalPropInit(tmpReg, sym, funcInfo);
  573. funcInfo->ReleaseTmpRegister(tmpReg);
  574. // Slot array properties are tracked in non-debug mode as well because they need to stay
  575. // around for heap enumeration and escaping during attach/detach.
  576. TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(this), pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  577. }
  578. }
  579. else if (!sym->GetIsModuleExportStorage())
  580. {
  581. if (sym->GetDecl()->AsParseNodeVar()->isSwitchStmtDecl)
  582. {
  583. // let/const declared in a switch is the only case of a variable that must be checked for
  584. // use-before-declaration dynamically within its own function.
  585. this->m_writer.Reg1(Js::OpCode::InitUndecl, sym->GetLocation());
  586. }
  587. // Syms that begin in register may be delay-captured. In debugger mode, such syms
  588. // will live only in slots, so tell the debugger to find them there.
  589. if (sym->NeedsSlotAlloc(this, funcInfo))
  590. {
  591. TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(this), pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  592. }
  593. else
  594. {
  595. TrackRegisterPropertyForDebugger(debuggerScope, sym, funcInfo, pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  596. }
  597. }
  598. };
  599. IterateBlockScopedVariables(pnodeBlock, genBlockInit);
  600. }
  601. // Records the start of a debugger scope if the passed in node has any let/const variables (or is not a block node).
  602. // If it has no let/const variables, nullptr will be returned as no scope will be created.
  603. Js::DebuggerScope* ByteCodeGenerator::RecordStartScopeObject(ParseNode * pnode, Js::DiagExtraScopesType scopeType, Js::RegSlot scopeLocation /*= Js::Constants::NoRegister*/, int* index /*= nullptr*/)
  604. {
  605. Assert(pnode);
  606. if (pnode->nop == knopBlock && !pnode->AsParseNodeBlock()->HasBlockScopedContent())
  607. {
  608. // In order to reduce allocations now that we track debugger scopes in non-debug mode,
  609. // don't add a block to the chain if it has no let/const variables at all.
  610. return nullptr;
  611. }
  612. return this->Writer()->RecordStartScopeObject(scopeType, scopeLocation, index);
  613. }
  614. // Records the end of the current scope, but only if the current block has block scoped content.
  615. // Otherwise, a scope would not have been added (see ByteCodeGenerator::RecordStartScopeObject()).
  616. void ByteCodeGenerator::RecordEndScopeObject(ParseNode *pnodeBlock)
  617. {
  618. Assert(pnodeBlock);
  619. if (pnodeBlock->nop == knopBlock && !pnodeBlock->AsParseNodeBlock()->HasBlockScopedContent())
  620. {
  621. return;
  622. }
  623. this->Writer()->RecordEndScopeObject();
  624. }
  625. void BeginEmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  626. {
  627. Js::DebuggerScope* debuggerScope = nullptr;
  628. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  629. {
  630. Scope *scope = pnodeBlock->scope;
  631. byteCodeGenerator->PushScope(scope);
  632. Js::RegSlot scopeLocation = scope->GetLocation();
  633. if (scope->GetMustInstantiate())
  634. {
  635. Assert(scopeLocation == Js::Constants::NoRegister);
  636. scopeLocation = funcInfo->FirstInnerScopeReg() + scope->GetInnerScopeIndex();
  637. if (scope->GetIsObject())
  638. {
  639. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInObject, scopeLocation);
  640. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::NewBlockScope, scope->GetInnerScopeIndex());
  641. }
  642. else
  643. {
  644. int scopeIndex = Js::DebuggerScope::InvalidScopeIndex;
  645. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInSlot, scopeLocation, &scopeIndex);
  646. // TODO: Handle heap enumeration
  647. int scopeSlotCount = scope->GetScopeSlotCount();
  648. byteCodeGenerator->Writer()->Num3(Js::OpCode::NewInnerScopeSlots, scope->GetInnerScopeIndex(), scopeSlotCount + Js::ScopeSlots::FirstSlotIndex, scopeIndex);
  649. }
  650. }
  651. else
  652. {
  653. // In the direct register access case, there is no block scope emitted but we can still track
  654. // the start and end offset of the block. The location registers for let/const variables will still be
  655. // captured along with this range in InitBlockScopedContent().
  656. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeDirect);
  657. }
  658. bool const isGlobalEvalBlockScope = scope->IsGlobalEvalBlockScope();
  659. Js::RegSlot frameDisplayLoc = Js::Constants::NoRegister;
  660. Js::RegSlot tmpInnerEnvReg = Js::Constants::NoRegister;
  661. ParseNodePtr pnodeScope;
  662. for (pnodeScope = pnodeBlock->pnodeScopes; pnodeScope;)
  663. {
  664. switch (pnodeScope->nop)
  665. {
  666. case knopFncDecl:
  667. if (pnodeScope->AsParseNodeFnc()->IsDeclaration())
  668. {
  669. // The frameDisplayLoc register's lifetime has to be controlled by this function. We can't let
  670. // it be released by DefineOneFunction, because further iterations of this loop can allocate
  671. // temps, and we can't let frameDisplayLoc be re-purposed until this loop completes.
  672. // So we'll supply a temp that we allocate and release here.
  673. if (frameDisplayLoc == Js::Constants::NoRegister)
  674. {
  675. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  676. {
  677. frameDisplayLoc = funcInfo->frameDisplayRegister;
  678. }
  679. else
  680. {
  681. frameDisplayLoc = funcInfo->GetEnvRegister();
  682. }
  683. tmpInnerEnvReg = funcInfo->AcquireTmpRegister();
  684. frameDisplayLoc = byteCodeGenerator->PrependLocalScopes(frameDisplayLoc, tmpInnerEnvReg, funcInfo);
  685. }
  686. byteCodeGenerator->DefineOneFunction(pnodeScope->AsParseNodeFnc(), funcInfo, true, frameDisplayLoc);
  687. }
  688. // If this is the global eval block scope, the function is actually assigned to the global
  689. // so we don't need to keep the registers.
  690. if (isGlobalEvalBlockScope)
  691. {
  692. funcInfo->ReleaseLoc(pnodeScope);
  693. pnodeScope->location = Js::Constants::NoRegister;
  694. }
  695. pnodeScope = pnodeScope->AsParseNodeFnc()->pnodeNext;
  696. break;
  697. case knopBlock:
  698. pnodeScope = pnodeScope->AsParseNodeBlock()->pnodeNext;
  699. break;
  700. case knopCatch:
  701. pnodeScope = pnodeScope->AsParseNodeCatch()->pnodeNext;
  702. break;
  703. case knopWith:
  704. pnodeScope = pnodeScope->AsParseNodeWith()->pnodeNext;
  705. break;
  706. }
  707. }
  708. if (tmpInnerEnvReg != Js::Constants::NoRegister)
  709. {
  710. funcInfo->ReleaseTmpRegister(tmpInnerEnvReg);
  711. }
  712. }
  713. else
  714. {
  715. Scope *scope = pnodeBlock->scope;
  716. if (scope)
  717. {
  718. if (scope->GetMustInstantiate())
  719. {
  720. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInObject);
  721. }
  722. else
  723. {
  724. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeDirect);
  725. }
  726. }
  727. else
  728. {
  729. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInSlot);
  730. }
  731. }
  732. byteCodeGenerator->InitBlockScopedContent(pnodeBlock, debuggerScope, funcInfo);
  733. }
  734. void EndEmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  735. {
  736. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  737. {
  738. Scope *scope = pnodeBlock->scope;
  739. Assert(scope);
  740. Assert(scope == byteCodeGenerator->GetCurrentScope());
  741. byteCodeGenerator->PopScope();
  742. }
  743. byteCodeGenerator->RecordEndScopeObject(pnodeBlock);
  744. }
  745. void CloneEmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  746. {
  747. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  748. {
  749. // Only let variables have observable behavior when there are per iteration
  750. // bindings. const variables do not since they are immutable. Therefore,
  751. // (and the spec agrees), only create new scope clones if the loop variable
  752. // is a let declaration.
  753. bool isConst = false;
  754. pnodeBlock->scope->ForEachSymbolUntil([&isConst](Symbol * const sym) {
  755. // Exploit the fact that a for loop sxBlock can only have let and const
  756. // declarations, and can only have one or the other, regardless of how
  757. // many syms there might be. Thus only check the first sym.
  758. isConst = sym->GetDecl()->nop == knopConstDecl;
  759. return true;
  760. });
  761. if (!isConst)
  762. {
  763. Scope *scope = pnodeBlock->scope;
  764. Assert(scope == byteCodeGenerator->GetCurrentScope());
  765. if (scope->GetMustInstantiate())
  766. {
  767. Js::OpCode op = scope->GetIsObject() ? Js::OpCode::CloneBlockScope : Js::OpCode::CloneInnerScopeSlots;
  768. byteCodeGenerator->Writer()->Unsigned1(op, scope->GetInnerScopeIndex());
  769. }
  770. }
  771. }
  772. }
  773. void EmitBlock(ParseNodeBlock *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue)
  774. {
  775. Assert(pnodeBlock->nop == knopBlock);
  776. ParseNode *pnode = pnodeBlock->pnodeStmt;
  777. if (pnode == nullptr)
  778. {
  779. return;
  780. }
  781. BeginEmitBlock(pnodeBlock, byteCodeGenerator, funcInfo);
  782. ParseNode *pnodeLastValStmt = pnodeBlock->pnodeLastValStmt;
  783. while (pnode->nop == knopList)
  784. {
  785. ParseNode* stmt = pnode->AsParseNodeBin()->pnode1;
  786. if (stmt == pnodeLastValStmt)
  787. {
  788. // This is the last guaranteed return value, so any potential return values have to be
  789. // copied to the return register from this point forward.
  790. pnodeLastValStmt = nullptr;
  791. }
  792. byteCodeGenerator->EmitTopLevelStatement(stmt, funcInfo, fReturnValue && (pnodeLastValStmt == nullptr));
  793. pnode = pnode->AsParseNodeBin()->pnode2;
  794. }
  795. if (pnode == pnodeLastValStmt)
  796. {
  797. pnodeLastValStmt = nullptr;
  798. }
  799. byteCodeGenerator->EmitTopLevelStatement(pnode, funcInfo, fReturnValue && (pnodeLastValStmt == nullptr));
  800. EndEmitBlock(pnodeBlock, byteCodeGenerator, funcInfo);
  801. }
  802. void ClearTmpRegs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* emitFunc)
  803. {
  804. if (emitFunc->IsTmpReg(pnode->location))
  805. {
  806. pnode->location = Js::Constants::NoRegister;
  807. }
  808. }
  809. void ByteCodeGenerator::EmitTopLevelStatement(ParseNode *stmt, FuncInfo *funcInfo, BOOL fReturnValue)
  810. {
  811. if (stmt->nop == knopFncDecl && stmt->AsParseNodeFnc()->IsDeclaration())
  812. {
  813. // Function declarations (not function-declaration RHS's) are already fully processed.
  814. // Skip them here so the temp registers don't get messed up.
  815. return;
  816. }
  817. if (stmt->nop == knopName || stmt->nop == knopDot)
  818. {
  819. // Generating span for top level names are mostly useful in debugging mode, because user can debug it even though no side-effect expected.
  820. // But the name can have runtime error, e.g., foo.bar; // where foo is not defined.
  821. // At this time we need to throw proper line number and offset. so recording on all modes will be useful.
  822. StartStatement(stmt);
  823. Writer()->Empty(Js::OpCode::Nop);
  824. EndStatement(stmt);
  825. }
  826. Emit(stmt, this, funcInfo, fReturnValue, false/*isConstructorCall*/, nullptr/*bindPnode*/, true/*isTopLevel*/);
  827. if (funcInfo->IsTmpReg(stmt->location))
  828. {
  829. if (!stmt->isUsed && !fReturnValue)
  830. {
  831. m_writer.Reg1(Js::OpCode::Unused, stmt->location);
  832. }
  833. funcInfo->ReleaseLoc(stmt);
  834. }
  835. }
  836. // ByteCodeGenerator::DefineFunctions
  837. //
  838. // Emit byte code for scope-wide function definitions before any calls in the scope, regardless of lexical
  839. // order. Note that stores to the closure array are not emitted until we see the knopFncDecl in the tree
  840. // to make sure that sources of the stores have been defined.
  841. void ByteCodeGenerator::DefineFunctions(FuncInfo *funcInfoParent)
  842. {
  843. // DefineCachedFunctions doesn't depend on whether the user vars are declared or not, so
  844. // we'll just overload this variable to mean that the functions getting called again and we don't need to do anything
  845. if (funcInfoParent->GetHasCachedScope())
  846. {
  847. this->DefineCachedFunctions(funcInfoParent);
  848. }
  849. else
  850. {
  851. this->DefineUncachedFunctions(funcInfoParent);
  852. }
  853. }
  854. // Iterate over all child functions in a function's parameter and body scopes.
  855. template<typename Fn>
  856. void MapContainerScopeFunctions(ParseNode* pnodeScope, Fn fn)
  857. {
  858. auto mapFncDeclsInScopeList = [&](ParseNode *pnodeHead)
  859. {
  860. for (ParseNode *pnode = pnodeHead; pnode != nullptr;)
  861. {
  862. switch (pnode->nop)
  863. {
  864. case knopFncDecl:
  865. fn(pnode);
  866. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  867. break;
  868. case knopBlock:
  869. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  870. break;
  871. case knopCatch:
  872. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  873. break;
  874. case knopWith:
  875. pnode = pnode->AsParseNodeWith()->pnodeNext;
  876. break;
  877. default:
  878. AssertMsg(false, "Unexpected opcode in tree of scopes");
  879. return;
  880. }
  881. }
  882. };
  883. pnodeScope->AsParseNodeFnc()->MapContainerScopes(mapFncDeclsInScopeList);
  884. }
  885. void ByteCodeGenerator::DefineCachedFunctions(FuncInfo *funcInfoParent)
  886. {
  887. ParseNode *pnodeParent = funcInfoParent->root;
  888. uint slotCount = 0;
  889. auto countFncSlots = [&](ParseNode *pnodeFnc)
  890. {
  891. if (pnodeFnc->AsParseNodeFnc()->GetFuncSymbol() != nullptr && pnodeFnc->AsParseNodeFnc()->IsDeclaration())
  892. {
  893. slotCount++;
  894. }
  895. };
  896. MapContainerScopeFunctions(pnodeParent, countFncSlots);
  897. if (slotCount == 0)
  898. {
  899. return;
  900. }
  901. size_t extraBytesActual = AllocSizeMath::Mul(slotCount, sizeof(Js::FuncInfoEntry));
  902. // Reg2Aux takes int for byteCount so we need to convert to int. OOM if we can't because it would truncate data.
  903. if (extraBytesActual > INT_MAX)
  904. {
  905. Js::Throw::OutOfMemory();
  906. }
  907. int extraBytes = (int)extraBytesActual;
  908. Js::FuncInfoArray *info = AnewPlus(alloc, extraBytes, Js::FuncInfoArray, slotCount);
  909. // slotCount is guaranteed to be non-zero here.
  910. Js::AuxArray<uint32> * slotIdInCachedScopeToNestedIndexArray = funcInfoParent->GetParsedFunctionBody()->AllocateSlotIdInCachedScopeToNestedIndexArray(slotCount);
  911. slotCount = 0;
  912. auto fillEntries = [&](ParseNode *pnodeFnc)
  913. {
  914. Symbol *sym = pnodeFnc->AsParseNodeFnc()->GetFuncSymbol();
  915. if (sym != nullptr && (pnodeFnc->AsParseNodeFnc()->IsDeclaration()))
  916. {
  917. AssertMsg(!pnodeFnc->AsParseNodeFnc()->IsGenerator(), "Generator functions are not supported by InitCachedFuncs but since they always escape they should disable function caching");
  918. Js::FuncInfoEntry *entry = &info->elements[slotCount];
  919. entry->nestedIndex = pnodeFnc->AsParseNodeFnc()->nestedIndex;
  920. entry->scopeSlot = sym->GetScopeSlot();
  921. slotIdInCachedScopeToNestedIndexArray->elements[slotCount] = pnodeFnc->AsParseNodeFnc()->nestedIndex;
  922. slotCount++;
  923. }
  924. };
  925. MapContainerScopeFunctions(pnodeParent, fillEntries);
  926. m_writer.AuxNoReg(Js::OpCode::InitCachedFuncs,
  927. info,
  928. sizeof(Js::FuncInfoArray) + extraBytes,
  929. sizeof(Js::FuncInfoArray) + extraBytes);
  930. slotCount = 0;
  931. auto defineOrGetCachedFunc = [&](ParseNode *pnodeFnc)
  932. {
  933. Symbol *sym = pnodeFnc->AsParseNodeFnc()->GetFuncSymbol();
  934. if (pnodeFnc->AsParseNodeFnc()->IsDeclaration())
  935. {
  936. // Do we need to define the function here (i.e., is it not one of our cached locals)?
  937. // Only happens if the sym is null (e.g., function x.y(){}).
  938. if (sym == nullptr)
  939. {
  940. this->DefineOneFunction(pnodeFnc->AsParseNodeFnc(), funcInfoParent);
  941. }
  942. else if (!sym->IsInSlot(this, funcInfoParent) && sym->GetLocation() != Js::Constants::NoRegister)
  943. {
  944. // If it was defined by InitCachedFuncs, do we need to put it in a register rather than a slot?
  945. m_writer.Reg1Unsigned1(Js::OpCode::GetCachedFunc, sym->GetLocation(), slotCount);
  946. }
  947. // The "x = function() {...}" case is being generated on the fly, during emission,
  948. // so the caller expects to be able to release this register.
  949. funcInfoParent->ReleaseLoc(pnodeFnc);
  950. pnodeFnc->location = Js::Constants::NoRegister;
  951. slotCount++;
  952. }
  953. };
  954. MapContainerScopeFunctions(pnodeParent, defineOrGetCachedFunc);
  955. AdeletePlus(alloc, extraBytes, info);
  956. }
  957. void ByteCodeGenerator::DefineUncachedFunctions(FuncInfo *funcInfoParent)
  958. {
  959. ParseNode *pnodeParent = funcInfoParent->root;
  960. auto defineCheck = [&](ParseNode *pnodeFnc)
  961. {
  962. Assert(pnodeFnc->nop == knopFncDecl);
  963. //
  964. // Don't define the function upfront in following cases
  965. // 1. x = function() {...};
  966. // Don't define the function for all modes.
  967. // Such a function can only be accessed via the LHS, so we define it at the assignment point
  968. // rather than the scope entry to save a register (and possibly save the whole definition).
  969. //
  970. // 2. x = function f() {...};
  971. // f is not visible in the enclosing scope.
  972. // Such function expressions should be emitted only at the assignment point, as can be used only
  973. // after the assignment. Might save register.
  974. //
  975. if (pnodeFnc->AsParseNodeFnc()->IsDeclaration())
  976. {
  977. this->DefineOneFunction(pnodeFnc->AsParseNodeFnc(), funcInfoParent);
  978. // The "x = function() {...}" case is being generated on the fly, during emission,
  979. // so the caller expects to be able to release this register.
  980. funcInfoParent->ReleaseLoc(pnodeFnc);
  981. pnodeFnc->location = Js::Constants::NoRegister;
  982. }
  983. };
  984. MapContainerScopeFunctions(pnodeParent, defineCheck);
  985. }
  986. void EmitAssignmentToFuncName(ParseNodeFnc *pnodeFnc, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfoParent)
  987. {
  988. // Assign the location holding the func object reference to the given name.
  989. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  990. Symbol *sym = pnodeFnc->pnodeName->sym;
  991. if (sym != nullptr && !sym->GetIsFuncExpr())
  992. {
  993. if (sym->GetIsModuleExportStorage())
  994. {
  995. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  996. }
  997. else if (sym->GetIsGlobal())
  998. {
  999. Js::PropertyId propertyId = sym->GetPosition();
  1000. byteCodeGenerator->EmitGlobalFncDeclInit(pnodeFnc->location, propertyId, funcInfoParent);
  1001. if (byteCodeGenerator->GetFlags() & fscrEval && !funcInfoParent->GetIsStrictMode())
  1002. {
  1003. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  1004. }
  1005. }
  1006. else
  1007. {
  1008. if (sym->NeedsSlotAlloc(byteCodeGenerator, funcInfoParent))
  1009. {
  1010. if (!sym->GetHasNonCommittedReference() ||
  1011. (funcInfoParent->GetParsedFunctionBody()->DoStackNestedFunc()))
  1012. {
  1013. // No point in trying to optimize if there are no references before we have to commit to slot.
  1014. // And not safe to delay putting a stack function in the slot, since we may miss boxing.
  1015. sym->SetIsCommittedToSlot();
  1016. }
  1017. }
  1018. if (sym->GetScope()->GetFunc() != byteCodeGenerator->TopFuncInfo())
  1019. {
  1020. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  1021. }
  1022. else
  1023. {
  1024. byteCodeGenerator->EmitLocalPropInit(pnodeFnc->location, sym, funcInfoParent);
  1025. }
  1026. Symbol * fncScopeSym = sym->GetFuncScopeVarSym();
  1027. if (fncScopeSym)
  1028. {
  1029. if (fncScopeSym->GetIsGlobal() && byteCodeGenerator->GetFlags() & fscrEval)
  1030. {
  1031. Js::PropertyId propertyId = fncScopeSym->GetPosition();
  1032. byteCodeGenerator->EmitGlobalFncDeclInit(pnodeFnc->location, propertyId, funcInfoParent);
  1033. }
  1034. else
  1035. {
  1036. byteCodeGenerator->EmitPropStore(pnodeFnc->location, fncScopeSym, nullptr, funcInfoParent, false, false, /* isFncDeclVar */true);
  1037. }
  1038. }
  1039. }
  1040. }
  1041. }
  1042. Js::RegSlot ByteCodeGenerator::DefineOneFunction(ParseNodeFnc *pnodeFnc, FuncInfo *funcInfoParent, bool generateAssignment, Js::RegSlot regEnv, Js::RegSlot frameDisplayTemp)
  1043. {
  1044. Assert(pnodeFnc->nop == knopFncDecl);
  1045. funcInfoParent->AcquireLoc(pnodeFnc);
  1046. if (regEnv == Js::Constants::NoRegister)
  1047. {
  1048. // If the child needs a closure, find a heap-allocated frame to pass to it.
  1049. if (frameDisplayTemp != Js::Constants::NoRegister)
  1050. {
  1051. // We allocated a temp to hold a local frame display value. Use that.
  1052. // It's likely that the FD is on the stack, and we used the temp to load it back.
  1053. regEnv = frameDisplayTemp;
  1054. }
  1055. else if (funcInfoParent->frameDisplayRegister != Js::Constants::NoRegister)
  1056. {
  1057. // This function has built a frame display, so pass it down.
  1058. regEnv = funcInfoParent->frameDisplayRegister;
  1059. }
  1060. else
  1061. {
  1062. // This function has no captured locals but inherits a closure environment, so pass it down.
  1063. regEnv = funcInfoParent->GetEnvRegister();
  1064. }
  1065. regEnv = this->PrependLocalScopes(regEnv, Js::Constants::NoRegister, funcInfoParent);
  1066. }
  1067. // AssertMsg(funcInfo->nonLocalSymbols == 0 || regEnv != funcInfoParent->nullConstantRegister,
  1068. // "We need a closure for the nested function");
  1069. Assert(pnodeFnc->nestedIndex != (uint)-1);
  1070. // If we are in a parameter scope and it is not merged with body scope then we have to create the child function as an inner function
  1071. if (regEnv == funcInfoParent->frameDisplayRegister || regEnv == funcInfoParent->GetEnvRegister())
  1072. {
  1073. m_writer.NewFunction(pnodeFnc->location, pnodeFnc->nestedIndex, pnodeFnc->IsCoroutine(), pnodeFnc->GetHomeObjLocation());
  1074. }
  1075. else
  1076. {
  1077. m_writer.NewInnerFunction(pnodeFnc->location, pnodeFnc->nestedIndex, regEnv, pnodeFnc->IsCoroutine(), pnodeFnc->GetHomeObjLocation());
  1078. }
  1079. if (funcInfoParent->IsGlobalFunction() && (this->flags & fscrEval))
  1080. {
  1081. // A function declared at global scope in eval is untrackable,
  1082. // so make sure the caller's cached scope is invalidated.
  1083. this->funcEscapes = true;
  1084. }
  1085. else
  1086. {
  1087. if (pnodeFnc->IsDeclaration())
  1088. {
  1089. Symbol * funcSymbol = pnodeFnc->GetFuncSymbol();
  1090. if (funcSymbol)
  1091. {
  1092. // In the case where a let/const declaration is the same symbol name
  1093. // as the function declaration (shadowing case), the let/const var and
  1094. // the function declaration symbol are the same and share the same flags
  1095. // (particularly, sym->GetIsBlockVar() for this code path).
  1096. //
  1097. // For example:
  1098. // let a = 0; // <-- sym->GetIsBlockVar() = true
  1099. // function b(){} // <-- sym2->GetIsBlockVar() = false
  1100. //
  1101. // let x = 0; // <-- sym3->GetIsBlockVar() = true
  1102. // function x(){} // <-- sym3->GetIsBlockVar() = true
  1103. //
  1104. // In order to tell if the function is actually part
  1105. // of a block scope, we compare against the function scope here.
  1106. // Note that having a function with the same name as a let/const declaration
  1107. // is a redeclaration error, but we're pushing the fix for this out since it's
  1108. // a bit involved.
  1109. Assert(funcInfoParent->GetBodyScope() != nullptr && funcSymbol->GetScope() != nullptr);
  1110. bool isFunctionDeclarationInBlock = funcSymbol->GetIsBlockVar();
  1111. // Track all vars/lets/consts register slot function declarations.
  1112. if (ShouldTrackDebuggerMetadata()
  1113. // If this is a let binding function declaration at global level, we want to
  1114. // be sure to track the register location as well.
  1115. && !(funcInfoParent->IsGlobalFunction() && !isFunctionDeclarationInBlock))
  1116. {
  1117. if (!funcSymbol->IsInSlot(this, funcInfoParent))
  1118. {
  1119. funcInfoParent->byteCodeFunction->GetFunctionBody()->InsertSymbolToRegSlotList(funcSymbol->GetName(), pnodeFnc->location, funcInfoParent->varRegsCount);
  1120. }
  1121. }
  1122. if (isFunctionDeclarationInBlock)
  1123. {
  1124. // We only track inner let bindings for the debugger side.
  1125. this->TrackFunctionDeclarationPropertyForDebugger(funcSymbol, funcInfoParent);
  1126. }
  1127. }
  1128. }
  1129. }
  1130. if (pnodeFnc->IsDefaultModuleExport())
  1131. {
  1132. this->EmitAssignmentToDefaultModuleExport(pnodeFnc, funcInfoParent);
  1133. }
  1134. if (pnodeFnc->pnodeName == nullptr || !generateAssignment)
  1135. {
  1136. return regEnv;
  1137. }
  1138. EmitAssignmentToFuncName(pnodeFnc, this, funcInfoParent);
  1139. return regEnv;
  1140. }
  1141. void ByteCodeGenerator::DefineUserVars(FuncInfo *funcInfo)
  1142. {
  1143. // Initialize scope-wide variables on entry to the scope. TODO: optimize by detecting uses that are always reached
  1144. // by an existing initialization.
  1145. BOOL fGlobal = funcInfo->IsGlobalFunction();
  1146. ParseNode *pnode;
  1147. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1148. // Global declarations need a temp register to hold the init value, but the node shouldn't get a register.
  1149. // Just assign one on the fly and re-use it for all initializations.
  1150. Js::RegSlot tmpReg = fGlobal ? funcInfo->AcquireTmpRegister() : Js::Constants::NoRegister;
  1151. for (pnode = funcInfo->root->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1152. {
  1153. Symbol* sym = pnode->AsParseNodeVar()->sym;
  1154. if (sym != nullptr && !(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  1155. {
  1156. if (sym->IsSpecialSymbol())
  1157. {
  1158. // Special symbols have already had their initial values stored into their registers.
  1159. // In default-argument case we've stored those values into their slot locations, as well.
  1160. // We must do that because a default parameter may access a special symbol through a scope slot.
  1161. // In the non-default-argument case, though, we didn't yet store the values into the
  1162. // slots so let's do that now.
  1163. if (!funcInfo->root->HasNonSimpleParameterList())
  1164. {
  1165. EmitPropStoreForSpecialSymbol(sym->GetLocation(), sym, sym->GetPid(), funcInfo, true);
  1166. if (ShouldTrackDebuggerMetadata() && !sym->IsInSlot(this, funcInfo))
  1167. {
  1168. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), sym->GetLocation(), funcInfo->varRegsCount);
  1169. }
  1170. }
  1171. continue;
  1172. }
  1173. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  1174. {
  1175. // The init node was bound to the catch object, because it's inside a catch and has the
  1176. // same name as the catch object. But we want to define a user var at function scope,
  1177. // so find the right symbol. (We'll still assign the RHS value to the catch object symbol.)
  1178. // This also applies to a var declaration in the same scope as a let declaration.
  1179. #if DBG
  1180. if (sym->IsArguments())
  1181. {
  1182. // There is a block scoped var named arguments
  1183. Assert(!funcInfo->GetHasArguments());
  1184. continue;
  1185. }
  1186. else if (!sym->GetIsCatch())
  1187. {
  1188. // Assert that catch cannot be at function scope and let and var at function scope is redeclaration error.
  1189. Assert(funcInfo->bodyScope != sym->GetScope());
  1190. }
  1191. #endif
  1192. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  1193. Assert(sym && !sym->GetIsCatch() && !sym->GetIsBlockVar());
  1194. }
  1195. if (sym->GetSymbolType() == STVariable && !sym->GetIsModuleExportStorage())
  1196. {
  1197. if (fGlobal)
  1198. {
  1199. Js::PropertyId propertyId = sym->EnsurePosition(this);
  1200. // We do need to initialize some globals to avoid JS errors on loading undefined variables.
  1201. // But we first need to make sure we're not trashing built-ins.
  1202. if (this->flags & fscrEval)
  1203. {
  1204. if (funcInfo->byteCodeFunction->GetIsStrictMode())
  1205. {
  1206. // Check/Init the property of the frame object
  1207. this->m_writer.ElementRootU(Js::OpCode::LdLocalElemUndef,
  1208. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1209. }
  1210. else
  1211. {
  1212. // The check and the init involve the first element in the scope chain.
  1213. this->m_writer.ElementScopedU(
  1214. Js::OpCode::LdElemUndefScoped, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1215. }
  1216. }
  1217. else
  1218. {
  1219. this->m_writer.ElementU(Js::OpCode::LdElemUndef, ByteCodeGenerator::RootObjectRegister,
  1220. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1221. }
  1222. }
  1223. else if (!sym->IsArguments())
  1224. {
  1225. if (sym->NeedsSlotAlloc(this, funcInfo))
  1226. {
  1227. if (!sym->GetHasNonCommittedReference() ||
  1228. (sym->GetHasFuncAssignment() && funcInfo->GetParsedFunctionBody()->DoStackNestedFunc()))
  1229. {
  1230. // No point in trying to optimize if there are no references before we have to commit to slot.
  1231. // And not safe to delay putting a stack function in the slot, since we may miss boxing.
  1232. sym->SetIsCommittedToSlot();
  1233. }
  1234. }
  1235. // Undef-initialize the home location if it is a register (not closure-captured, or else capture
  1236. // is delayed) or a property of an object.
  1237. if ((!sym->GetHasInit() && !sym->IsInSlot(this, funcInfo)) ||
  1238. (funcInfo->bodyScope->GetIsObject() && !funcInfo->GetHasCachedScope()))
  1239. {
  1240. Js::RegSlot reg = sym->GetLocation();
  1241. if (reg == Js::Constants::NoRegister)
  1242. {
  1243. Assert(sym->IsInSlot(this, funcInfo));
  1244. reg = funcInfo->AcquireTmpRegister();
  1245. }
  1246. this->m_writer.Reg1(Js::OpCode::LdUndef, reg);
  1247. this->EmitLocalPropInit(reg, sym, funcInfo);
  1248. if (ShouldTrackDebuggerMetadata() && !sym->GetHasInit() && !sym->IsInSlot(this, funcInfo))
  1249. {
  1250. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), reg, funcInfo->varRegsCount);
  1251. }
  1252. funcInfo->ReleaseTmpRegister(reg);
  1253. }
  1254. }
  1255. else if (ShouldTrackDebuggerMetadata())
  1256. {
  1257. if (!sym->GetHasInit() && !sym->IsInSlot(this, funcInfo))
  1258. {
  1259. Js::RegSlot reg = sym->GetLocation();
  1260. if (reg != Js::Constants::NoRegister)
  1261. {
  1262. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), reg, funcInfo->varRegsCount);
  1263. }
  1264. }
  1265. }
  1266. sym->SetHasInit(TRUE);
  1267. }
  1268. }
  1269. }
  1270. if (tmpReg != Js::Constants::NoRegister)
  1271. {
  1272. funcInfo->ReleaseTmpRegister(tmpReg);
  1273. }
  1274. for (int i = 0; i < funcInfo->nonUserNonTempRegistersToInitialize.Count(); ++i)
  1275. {
  1276. m_writer.Reg1(Js::OpCode::LdUndef, funcInfo->nonUserNonTempRegistersToInitialize.Item(i));
  1277. }
  1278. }
  1279. void ByteCodeGenerator::InitBlockScopedNonTemps(ParseNode *pnode, FuncInfo *funcInfo)
  1280. {
  1281. // Initialize all non-temp register variables on entry to the enclosing func - in particular,
  1282. // those with lifetimes that begin after the start of user code and may not be initialized normally.
  1283. // This protects us from, for instance, trying to restore garbage on bailout.
  1284. // It was originally done in debugger mode only, but we do it always to avoid issues with boxing
  1285. // garbage on exit from jitted loop bodies.
  1286. while (pnode)
  1287. {
  1288. switch (pnode->nop)
  1289. {
  1290. case knopFncDecl:
  1291. {
  1292. // If this is a block-scoped function, initialize it.
  1293. ParseNodeFnc * pnodeFnc = pnode->AsParseNodeFnc();
  1294. ParseNodeVar *pnodeName = pnodeFnc->pnodeName;
  1295. if (!pnodeFnc->IsMethod() && pnodeName != nullptr)
  1296. {
  1297. Symbol *sym = pnodeName->sym;
  1298. Assert(sym);
  1299. if (sym->GetLocation() != Js::Constants::NoRegister &&
  1300. sym->GetScope()->IsBlockScope(funcInfo) &&
  1301. sym->GetScope()->GetFunc() == funcInfo)
  1302. {
  1303. this->m_writer.Reg1(Js::OpCode::LdUndef, sym->GetLocation());
  1304. }
  1305. }
  1306. // No need to recurse to the nested scopes, as they belong to a nested function.
  1307. pnode = pnodeFnc->pnodeNext;
  1308. break;
  1309. }
  1310. case knopBlock:
  1311. {
  1312. ParseNodeBlock * pnodeBlock = pnode->AsParseNodeBlock();
  1313. Scope *scope = pnodeBlock->scope;
  1314. if (scope)
  1315. {
  1316. if (scope->IsBlockScope(funcInfo))
  1317. {
  1318. Js::RegSlot scopeLoc = scope->GetLocation();
  1319. if (scopeLoc != Js::Constants::NoRegister && !funcInfo->IsTmpReg(scopeLoc))
  1320. {
  1321. this->m_writer.Reg1(Js::OpCode::LdUndef, scopeLoc);
  1322. }
  1323. }
  1324. auto fnInit = [this, funcInfo](ParseNode *pnode)
  1325. {
  1326. Symbol *sym = pnode->AsParseNodeVar()->sym;
  1327. if (!sym->IsInSlot(this, funcInfo) && !sym->GetIsGlobal() && !sym->GetIsModuleImport())
  1328. {
  1329. this->m_writer.Reg1(Js::OpCode::InitUndecl, pnode->AsParseNodeVar()->sym->GetLocation());
  1330. }
  1331. };
  1332. IterateBlockScopedVariables(pnodeBlock, fnInit);
  1333. }
  1334. InitBlockScopedNonTemps(pnodeBlock->pnodeScopes, funcInfo);
  1335. pnode = pnodeBlock->pnodeNext;
  1336. break;
  1337. }
  1338. case knopCatch:
  1339. InitBlockScopedNonTemps(pnode->AsParseNodeCatch()->pnodeScopes, funcInfo);
  1340. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  1341. break;
  1342. case knopWith:
  1343. {
  1344. Js::RegSlot withLoc = pnode->location;
  1345. AssertMsg(withLoc != Js::Constants::NoRegister && !funcInfo->IsTmpReg(withLoc),
  1346. "We should put with objects at known stack locations in debug mode");
  1347. this->m_writer.Reg1(Js::OpCode::LdUndef, withLoc);
  1348. InitBlockScopedNonTemps(pnode->AsParseNodeWith()->pnodeScopes, funcInfo);
  1349. pnode = pnode->AsParseNodeWith()->pnodeNext;
  1350. break;
  1351. }
  1352. default:
  1353. Assert(false);
  1354. return;
  1355. }
  1356. }
  1357. }
  1358. void ByteCodeGenerator::EmitScopeObjectInit(FuncInfo *funcInfo)
  1359. {
  1360. Assert(!funcInfo->byteCodeFunction->GetFunctionBody()->DoStackNestedFunc());
  1361. if (!funcInfo->GetHasCachedScope() /* || forcing scope/inner func caching */)
  1362. {
  1363. return;
  1364. }
  1365. Scope* currentScope = funcInfo->GetCurrentChildScope();
  1366. uint slotCount = currentScope->GetScopeSlotCount();
  1367. uint cachedFuncCount = 0;
  1368. Js::PropertyId firstFuncSlot = Js::Constants::NoProperty;
  1369. Js::PropertyId firstVarSlot = Js::Constants::NoProperty;
  1370. uint extraAlloc = UInt32Math::Add(slotCount, Js::ActivationObjectEx::ExtraSlotCount());
  1371. extraAlloc = UInt32Math::Mul(extraAlloc, sizeof(Js::PropertyId));
  1372. // Create and fill the array of local property ID's.
  1373. // They all have slots assigned to them already (if they need them): see StartEmitFunction.
  1374. Js::PropertyIdArray *propIds = funcInfo->GetParsedFunctionBody()->AllocatePropertyIdArrayForFormals(extraAlloc, slotCount, Js::ActivationObjectEx::ExtraSlotCount());
  1375. ParseNodeFnc *pnodeFnc = funcInfo->root;
  1376. ParseNode *pnode;
  1377. Symbol *sym;
  1378. if (funcInfo->GetFuncExprNameReference() && pnodeFnc->GetFuncSymbol()->GetScope() == funcInfo->GetBodyScope())
  1379. {
  1380. Symbol::SaveToPropIdArray(pnodeFnc->GetFuncSymbol(), propIds, this);
  1381. }
  1382. if (funcInfo->GetHasArguments())
  1383. {
  1384. // Because the arguments object can access all instances of same-named formals ("function(x,x){...}"),
  1385. // be sure we initialize any duplicate appearances of a formal parameter to "NoProperty".
  1386. Js::PropertyId slot = 0;
  1387. auto initArg = [&](ParseNode *pnode)
  1388. {
  1389. if (pnode->IsVarLetOrConst())
  1390. {
  1391. Symbol *sym = pnode->AsParseNodeVar()->sym;
  1392. Assert(sym);
  1393. if (sym->GetScopeSlot() == slot)
  1394. {
  1395. // This is the last appearance of the formal, so record the ID.
  1396. Symbol::SaveToPropIdArray(sym, propIds, this);
  1397. }
  1398. else
  1399. {
  1400. // This is an earlier duplicate appearance of the formal, so use NoProperty as a placeholder
  1401. // since this slot can't be accessed by name.
  1402. Assert(sym->GetScopeSlot() != Js::Constants::NoProperty && sym->GetScopeSlot() > slot);
  1403. propIds->elements[slot] = Js::Constants::NoProperty;
  1404. }
  1405. }
  1406. else
  1407. {
  1408. // This is for patterns
  1409. propIds->elements[slot] = Js::Constants::NoProperty;
  1410. }
  1411. slot++;
  1412. };
  1413. MapFormalsWithoutRest(pnodeFnc, initArg);
  1414. // If the rest is in the slot - we need to keep that slot.
  1415. if (pnodeFnc->pnodeRest != nullptr && pnodeFnc->pnodeRest->sym->IsInSlot(this, funcInfo))
  1416. {
  1417. Symbol::SaveToPropIdArray(pnodeFnc->pnodeRest->sym, propIds, this);
  1418. }
  1419. }
  1420. else
  1421. {
  1422. MapFormals(pnodeFnc, [&](ParseNode *pnode)
  1423. {
  1424. if (pnode->IsVarLetOrConst())
  1425. {
  1426. Symbol::SaveToPropIdArray(pnode->AsParseNodeVar()->sym, propIds, this);
  1427. }
  1428. });
  1429. }
  1430. auto saveFunctionVarsToPropIdArray = [&](ParseNode *pnodeFunction)
  1431. {
  1432. if (pnodeFunction->AsParseNodeFnc()->IsDeclaration())
  1433. {
  1434. ParseNode *pnodeName = pnodeFunction->AsParseNodeFnc()->pnodeName;
  1435. if (pnodeName != nullptr)
  1436. {
  1437. while (pnodeName->nop == knopList)
  1438. {
  1439. if (pnodeName->AsParseNodeBin()->pnode1->nop == knopVarDecl)
  1440. {
  1441. sym = pnodeName->AsParseNodeBin()->pnode1->AsParseNodeVar()->sym;
  1442. if (sym)
  1443. {
  1444. Symbol::SaveToPropIdArray(sym, propIds, this, &firstFuncSlot);
  1445. }
  1446. }
  1447. pnodeName = pnodeName->AsParseNodeBin()->pnode2;
  1448. }
  1449. if (pnodeName->nop == knopVarDecl)
  1450. {
  1451. sym = pnodeName->AsParseNodeVar()->sym;
  1452. if (sym)
  1453. {
  1454. Symbol::SaveToPropIdArray(sym, propIds, this, &firstFuncSlot);
  1455. cachedFuncCount++;
  1456. }
  1457. }
  1458. }
  1459. }
  1460. };
  1461. MapContainerScopeFunctions(pnodeFnc, saveFunctionVarsToPropIdArray);
  1462. if (currentScope->GetScopeType() != ScopeType_Parameter)
  1463. {
  1464. for (pnode = pnodeFnc->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1465. {
  1466. sym = pnode->AsParseNodeVar()->sym;
  1467. if (!(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  1468. {
  1469. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  1470. {
  1471. sym = currentScope->FindLocalSymbol(sym->GetName());
  1472. }
  1473. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1474. }
  1475. }
  1476. ParseNodeBlock *pnodeBlock = pnodeFnc->pnodeScopes;
  1477. for (pnode = pnodeBlock->pnodeLexVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1478. {
  1479. sym = pnode->AsParseNodeVar()->sym;
  1480. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1481. }
  1482. pnodeBlock = pnodeFnc->pnodeBodyScope;
  1483. for (pnode = pnodeBlock->pnodeLexVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1484. {
  1485. sym = pnode->AsParseNodeVar()->sym;
  1486. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1487. }
  1488. }
  1489. else
  1490. {
  1491. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  1492. }
  1493. // Write the first func slot and first var slot into the auxiliary data
  1494. Js::PropertyId *slots = propIds->elements + slotCount;
  1495. slots[0] = cachedFuncCount;
  1496. slots[1] = firstFuncSlot;
  1497. slots[2] = firstVarSlot;
  1498. slots[3] = funcInfo->GetParsedFunctionBody()->NewObjectLiteral();
  1499. propIds->hasNonSimpleParams = funcInfo->root->HasNonSimpleParameterList();
  1500. funcInfo->GetParsedFunctionBody()->SetHasCachedScopePropIds(true);
  1501. }
  1502. void ByteCodeGenerator::SetClosureRegisters(FuncInfo* funcInfo, Js::FunctionBody* byteCodeFunction)
  1503. {
  1504. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  1505. {
  1506. byteCodeFunction->MapAndSetLocalFrameDisplayRegister(funcInfo->frameDisplayRegister);
  1507. }
  1508. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  1509. {
  1510. byteCodeFunction->MapAndSetLocalClosureRegister(funcInfo->frameObjRegister);
  1511. byteCodeFunction->SetHasScopeObject(true);
  1512. }
  1513. else if (funcInfo->frameSlotsRegister != Js::Constants::NoRegister)
  1514. {
  1515. byteCodeFunction->MapAndSetLocalClosureRegister(funcInfo->frameSlotsRegister);
  1516. }
  1517. if (funcInfo->paramSlotsRegister != Js::Constants::NoRegister)
  1518. {
  1519. byteCodeFunction->MapAndSetParamClosureRegister(funcInfo->paramSlotsRegister);
  1520. }
  1521. }
  1522. void ByteCodeGenerator::FinalizeRegisters(FuncInfo * funcInfo, Js::FunctionBody * byteCodeFunction)
  1523. {
  1524. if (byteCodeFunction->IsCoroutine())
  1525. {
  1526. // EmitYield uses 'false' to create the IteratorResult object
  1527. funcInfo->AssignFalseConstRegister();
  1528. }
  1529. if (funcInfo->NeedEnvRegister())
  1530. {
  1531. bool constReg = !funcInfo->GetIsTopLevelEventHandler() && funcInfo->IsGlobalFunction() && !(this->flags & fscrEval);
  1532. funcInfo->AssignEnvRegister(constReg);
  1533. }
  1534. // Set the function body's constant count before emitting anything so that the byte code writer
  1535. // can distinguish constants from variables.
  1536. byteCodeFunction->CheckAndSetConstantCount(funcInfo->constRegsCount);
  1537. this->SetClosureRegisters(funcInfo, byteCodeFunction);
  1538. if (this->IsInDebugMode() || byteCodeFunction->IsCoroutine())
  1539. {
  1540. // Give permanent registers to the inner scopes in debug mode.
  1541. // TODO: We create seperate debuggerscopes for each block which has own scope. These are stored in the var registers
  1542. // allocated below. Ideally we should change this logic to not allocate separate registers for these and save the debug
  1543. // info in corresponding symbols and use it from there. This will also affect the temp register allocation logic in
  1544. // EmitOneFunction.
  1545. uint innerScopeCount = funcInfo->InnerScopeCount();
  1546. byteCodeFunction->SetInnerScopeCount(innerScopeCount);
  1547. if (innerScopeCount)
  1548. {
  1549. funcInfo->SetFirstInnerScopeReg(funcInfo->NextVarRegister());
  1550. for (uint i = 1; i < innerScopeCount; i++)
  1551. {
  1552. funcInfo->NextVarRegister();
  1553. }
  1554. }
  1555. }
  1556. // NOTE: The FB expects the yield reg to be the final non-temp.
  1557. if (byteCodeFunction->IsCoroutine())
  1558. {
  1559. funcInfo->AssignYieldRegister();
  1560. }
  1561. Js::RegSlot firstTmpReg = funcInfo->varRegsCount;
  1562. funcInfo->SetFirstTmpReg(firstTmpReg);
  1563. byteCodeFunction->SetFirstTmpReg(funcInfo->RegCount());
  1564. }
  1565. void ByteCodeGenerator::InitScopeSlotArray(FuncInfo * funcInfo)
  1566. {
  1567. // Record slots info for ScopeSlots/ScopeObject.
  1568. uint scopeSlotCount = funcInfo->bodyScope->GetScopeSlotCount();
  1569. bool isSplitScope = !funcInfo->IsBodyAndParamScopeMerged();
  1570. Assert(funcInfo->paramScope == nullptr || funcInfo->paramScope->GetScopeSlotCount() == 0 || isSplitScope);
  1571. uint scopeSlotCountForParamScope = funcInfo->paramScope != nullptr ? funcInfo->paramScope->GetScopeSlotCount() : 0;
  1572. if (scopeSlotCount == 0 && scopeSlotCountForParamScope == 0)
  1573. {
  1574. return;
  1575. }
  1576. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1577. if (scopeSlotCount > 0 || scopeSlotCountForParamScope > 0)
  1578. {
  1579. byteCodeFunction->SetScopeSlotArraySizes(scopeSlotCount, scopeSlotCountForParamScope);
  1580. }
  1581. // TODO: Need to add property ids for the case when scopeSlotCountForParamSCope is non-zero
  1582. if (scopeSlotCount)
  1583. {
  1584. Js::PropertyId *propertyIdsForScopeSlotArray = RecyclerNewArrayLeafZ(scriptContext->GetRecycler(), Js::PropertyId, scopeSlotCount);
  1585. byteCodeFunction->SetPropertyIdsForScopeSlotArray(propertyIdsForScopeSlotArray, scopeSlotCount, scopeSlotCountForParamScope);
  1586. AssertMsg(!byteCodeFunction->IsReparsed() || byteCodeFunction->WasEverAsmJsMode() || byteCodeFunction->scopeSlotArraySize == scopeSlotCount,
  1587. "The slot array size is different between debug and non-debug mode");
  1588. #if DEBUG
  1589. for (UINT i = 0; i < scopeSlotCount; i++)
  1590. {
  1591. propertyIdsForScopeSlotArray[i] = Js::Constants::NoProperty;
  1592. }
  1593. #endif
  1594. auto setPropertyIdForScopeSlotArray =
  1595. [scopeSlotCount, propertyIdsForScopeSlotArray]
  1596. (Js::PropertyId slot, Js::PropertyId propId)
  1597. {
  1598. if (slot < 0 || (uint)slot >= scopeSlotCount)
  1599. {
  1600. Js::Throw::FatalInternalError();
  1601. }
  1602. propertyIdsForScopeSlotArray[slot] = propId;
  1603. };
  1604. auto setPropIdsForScopeSlotArray = [this, funcInfo, setPropertyIdForScopeSlotArray](Symbol *const sym)
  1605. {
  1606. if (sym->NeedsSlotAlloc(this, funcInfo))
  1607. {
  1608. // All properties should get correct propertyId here.
  1609. Assert(sym->HasScopeSlot()); // We can't allocate scope slot now. Any symbol needing scope slot must have allocated it before this point.
  1610. setPropertyIdForScopeSlotArray(sym->GetScopeSlot(), sym->EnsurePosition(funcInfo));
  1611. }
  1612. };
  1613. funcInfo->GetBodyScope()->ForEachSymbol(setPropIdsForScopeSlotArray);
  1614. #if DEBUG
  1615. for (UINT i = 0; i < scopeSlotCount; i++)
  1616. {
  1617. Assert(propertyIdsForScopeSlotArray[i] != Js::Constants::NoProperty
  1618. || funcInfo->frameObjRegister != Js::Constants::NoRegister); // ScopeObject may have unassigned entries, e.g. for same-named parameters
  1619. }
  1620. #endif
  1621. }
  1622. }
  1623. // temporarily load all constants and special registers in a single block
  1624. void ByteCodeGenerator::LoadAllConstants(FuncInfo *funcInfo)
  1625. {
  1626. Symbol *sym;
  1627. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1628. byteCodeFunction->CreateConstantTable();
  1629. if (funcInfo->nullConstantRegister != Js::Constants::NoRegister)
  1630. {
  1631. byteCodeFunction->RecordNullObject(byteCodeFunction->MapRegSlot(funcInfo->nullConstantRegister));
  1632. }
  1633. if (funcInfo->undefinedConstantRegister != Js::Constants::NoRegister)
  1634. {
  1635. byteCodeFunction->RecordUndefinedObject(byteCodeFunction->MapRegSlot(funcInfo->undefinedConstantRegister));
  1636. }
  1637. if (funcInfo->trueConstantRegister != Js::Constants::NoRegister)
  1638. {
  1639. byteCodeFunction->RecordTrueObject(byteCodeFunction->MapRegSlot(funcInfo->trueConstantRegister));
  1640. }
  1641. if (funcInfo->falseConstantRegister != Js::Constants::NoRegister)
  1642. {
  1643. byteCodeFunction->RecordFalseObject(byteCodeFunction->MapRegSlot(funcInfo->falseConstantRegister));
  1644. }
  1645. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  1646. {
  1647. m_writer.RecordObjectRegister(funcInfo->frameObjRegister);
  1648. if (!funcInfo->GetApplyEnclosesArgs())
  1649. {
  1650. this->EmitScopeObjectInit(funcInfo);
  1651. }
  1652. #if DBG
  1653. uint count = 0;
  1654. funcInfo->GetBodyScope()->ForEachSymbol([&](Symbol *const sym)
  1655. {
  1656. if (sym->NeedsSlotAlloc(this, funcInfo))
  1657. {
  1658. // All properties should get correct propertyId here.
  1659. count++;
  1660. }
  1661. });
  1662. if (funcInfo->GetParamScope() != nullptr)
  1663. {
  1664. funcInfo->GetParamScope()->ForEachSymbol([&](Symbol *const sym)
  1665. {
  1666. if (sym->NeedsSlotAlloc(this, funcInfo))
  1667. {
  1668. // All properties should get correct propertyId here.
  1669. count++;
  1670. }
  1671. });
  1672. }
  1673. // A reparse should result in the same size of the activation object.
  1674. // Exclude functions which were created from the ByteCodeCache.
  1675. AssertMsg(!byteCodeFunction->IsReparsed() || byteCodeFunction->HasGeneratedFromByteCodeCache() ||
  1676. byteCodeFunction->scopeObjectSize == count || byteCodeFunction->WasEverAsmJsMode(),
  1677. "The activation object size is different between debug and non-debug mode");
  1678. byteCodeFunction->scopeObjectSize = count;
  1679. #endif
  1680. }
  1681. else if (funcInfo->frameSlotsRegister != Js::Constants::NoRegister)
  1682. {
  1683. int scopeSlotCount = funcInfo->bodyScope->GetScopeSlotCount();
  1684. int paramSlotCount = funcInfo->paramScope->GetScopeSlotCount();
  1685. if (scopeSlotCount == 0 && paramSlotCount == 0)
  1686. {
  1687. AssertMsg(funcInfo->frameDisplayRegister != Js::Constants::NoRegister, "Why do we need scope slots?");
  1688. m_writer.Reg1(Js::OpCode::LdC_A_Null, funcInfo->frameSlotsRegister);
  1689. }
  1690. }
  1691. if (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject())
  1692. {
  1693. byteCodeFunction->MapAndSetFuncExprScopeRegister(funcInfo->funcExprScope->GetLocation());
  1694. byteCodeFunction->SetEnvDepth((uint16)-1);
  1695. }
  1696. bool thisLoadedFromParams = false;
  1697. if (funcInfo->NeedEnvRegister())
  1698. {
  1699. byteCodeFunction->MapAndSetEnvRegister(funcInfo->GetEnvRegister());
  1700. if (funcInfo->GetIsTopLevelEventHandler())
  1701. {
  1702. if (funcInfo->GetThisSymbol())
  1703. {
  1704. byteCodeFunction->MapAndSetThisRegisterForEventHandler(funcInfo->GetThisSymbol()->GetLocation());
  1705. }
  1706. // The environment is the namespace hierarchy starting with "this".
  1707. Assert(!funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1708. thisLoadedFromParams = true;
  1709. this->InvalidateCachedOuterScopes(funcInfo);
  1710. }
  1711. else if (funcInfo->IsGlobalFunction() && !(this->flags & fscrEval))
  1712. {
  1713. Assert(funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1714. if (funcInfo->GetIsStrictMode())
  1715. {
  1716. byteCodeFunction->RecordStrictNullDisplayConstant(byteCodeFunction->MapRegSlot(funcInfo->GetEnvRegister()));
  1717. }
  1718. else
  1719. {
  1720. byteCodeFunction->RecordNullDisplayConstant(byteCodeFunction->MapRegSlot(funcInfo->GetEnvRegister()));
  1721. }
  1722. }
  1723. else
  1724. {
  1725. // environment may be required to load "this"
  1726. Assert(!funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1727. this->InvalidateCachedOuterScopes(funcInfo);
  1728. }
  1729. }
  1730. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  1731. {
  1732. m_writer.RecordFrameDisplayRegister(funcInfo->frameDisplayRegister);
  1733. }
  1734. this->RecordAllIntConstants(funcInfo);
  1735. this->RecordAllStrConstants(funcInfo);
  1736. this->RecordAllStringTemplateCallsiteConstants(funcInfo);
  1737. funcInfo->doubleConstantToRegister.Map([byteCodeFunction](double d, Js::RegSlot location)
  1738. {
  1739. byteCodeFunction->RecordFloatConstant(byteCodeFunction->MapRegSlot(location), d);
  1740. });
  1741. // WARNING !!!
  1742. // DO NOT emit any bytecode before loading the heap arguments. This is because those opcodes may bail
  1743. // out (unlikely, since opcodes emitted in this function should not correspond to user code, but possible)
  1744. // and the Jit assumes that there cannot be any bailouts before LdHeapArguments (or its equivalent)
  1745. if (funcInfo->GetHasArguments())
  1746. {
  1747. sym = funcInfo->GetArgumentsSymbol();
  1748. Assert(sym);
  1749. Assert(funcInfo->GetHasHeapArguments());
  1750. if (funcInfo->GetCallsEval() || (!funcInfo->GetApplyEnclosesArgs()))
  1751. {
  1752. this->LoadHeapArguments(funcInfo);
  1753. }
  1754. }
  1755. else if (!funcInfo->IsGlobalFunction() && !IsInNonDebugMode())
  1756. {
  1757. uint count = funcInfo->inArgsCount + (funcInfo->root->pnodeRest != nullptr ? 1 : 0) - 1;
  1758. if (count != 0)
  1759. {
  1760. Js::PropertyIdArray *propIds = RecyclerNewPlus(scriptContext->GetRecycler(), UInt32Math::Mul(count, sizeof(Js::PropertyId)), Js::PropertyIdArray, count, 0);
  1761. GetFormalArgsArray(this, funcInfo, propIds);
  1762. byteCodeFunction->SetPropertyIdsOfFormals(propIds);
  1763. }
  1764. }
  1765. // Class constructors do not have a [[call]] slot but we don't implement a generic way to express this.
  1766. // What we do is emit a check for the new flag here. If we don't have CallFlags_New set, the opcode will throw.
  1767. // We need to do this before emitting 'this' since the base class constructor will try to construct a new object.
  1768. if (funcInfo->IsClassConstructor())
  1769. {
  1770. m_writer.Empty(Js::OpCode::ChkNewCallFlag);
  1771. }
  1772. // new.target may be used to construct the 'this' register so make sure to load it first
  1773. if (funcInfo->GetNewTargetSymbol())
  1774. {
  1775. this->LoadNewTargetObject(funcInfo);
  1776. }
  1777. if (funcInfo->GetThisSymbol())
  1778. {
  1779. this->LoadThisObject(funcInfo, thisLoadedFromParams);
  1780. }
  1781. else if (ShouldLoadConstThis(funcInfo))
  1782. {
  1783. this->EmitThis(funcInfo, funcInfo->thisConstantRegister, funcInfo->nullConstantRegister);
  1784. }
  1785. if (funcInfo->GetSuperSymbol())
  1786. {
  1787. this->LoadSuperObject(funcInfo);
  1788. }
  1789. if (funcInfo->GetSuperConstructorSymbol())
  1790. {
  1791. this->LoadSuperConstructorObject(funcInfo);
  1792. }
  1793. //
  1794. // If the function is a function expression with a name,
  1795. // load the function object at runtime to its activation object.
  1796. //
  1797. sym = funcInfo->root->GetFuncSymbol();
  1798. bool funcExprWithName = !funcInfo->IsGlobalFunction() && sym && sym->GetIsFuncExpr();
  1799. if (funcExprWithName)
  1800. {
  1801. if (funcInfo->GetFuncExprNameReference() ||
  1802. (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject()))
  1803. {
  1804. //
  1805. // x = function f(...) { ... }
  1806. // A named function expression's name (Symbol:f) belongs to the enclosing scope.
  1807. // Thus there are no uses of 'f' within the scope of the function (as references to 'f'
  1808. // are looked up in the closure). So, we can't use f's register as it is from the enclosing
  1809. // scope's register namespace. So use a tmp register.
  1810. // In ES5 mode though 'f' is *not* a part of the enclosing scope. So we always assign 'f' a register
  1811. // from it's register namespace, which LdFuncExpr can use.
  1812. //
  1813. Js::RegSlot ldFuncExprDst = sym->GetLocation();
  1814. this->m_writer.Reg1(Js::OpCode::LdFuncExpr, ldFuncExprDst);
  1815. if (sym->IsInSlot(this, funcInfo))
  1816. {
  1817. Js::RegSlot scopeLocation;
  1818. AnalysisAssert(funcInfo->funcExprScope);
  1819. if (funcInfo->funcExprScope->GetIsObject())
  1820. {
  1821. scopeLocation = funcInfo->funcExprScope->GetLocation();
  1822. this->m_writer.Property(Js::OpCode::StFuncExpr, sym->GetLocation(), scopeLocation,
  1823. funcInfo->FindOrAddReferencedPropertyId(sym->GetPosition()));
  1824. }
  1825. else if (funcInfo->paramScope->GetIsObject() || (funcInfo->paramScope->GetCanMerge() && funcInfo->bodyScope->GetIsObject()))
  1826. {
  1827. this->m_writer.ElementU(Js::OpCode::StLocalFuncExpr, sym->GetLocation(),
  1828. funcInfo->FindOrAddReferencedPropertyId(sym->GetPosition()));
  1829. }
  1830. else
  1831. {
  1832. Assert(sym->HasScopeSlot());
  1833. this->m_writer.SlotI1(Js::OpCode::StLocalSlot, sym->GetLocation(),
  1834. sym->GetScopeSlot() + Js::ScopeSlots::FirstSlotIndex);
  1835. }
  1836. }
  1837. else if (ShouldTrackDebuggerMetadata())
  1838. {
  1839. funcInfo->byteCodeFunction->GetFunctionBody()->InsertSymbolToRegSlotList(sym->GetName(), sym->GetLocation(), funcInfo->varRegsCount);
  1840. }
  1841. }
  1842. }
  1843. }
  1844. void ByteCodeGenerator::InvalidateCachedOuterScopes(FuncInfo *funcInfo)
  1845. {
  1846. Assert(funcInfo->GetEnvRegister() != Js::Constants::NoRegister);
  1847. // Walk the scope stack, from funcInfo outward, looking for scopes that have been cached.
  1848. Scope *scope = funcInfo->GetBodyScope()->GetEnclosingScope();
  1849. uint32 envIndex = 0;
  1850. while (scope && scope->GetFunc() == funcInfo)
  1851. {
  1852. // Skip over FuncExpr Scope and parameter scope for current funcInfo to get to the first enclosing scope of the outer function.
  1853. scope = scope->GetEnclosingScope();
  1854. }
  1855. for (; scope; scope = scope->GetEnclosingScope())
  1856. {
  1857. FuncInfo *func = scope->GetFunc();
  1858. if (scope == func->GetBodyScope())
  1859. {
  1860. if (func->Escapes() && func->GetHasCachedScope())
  1861. {
  1862. AssertOrFailFast(scope->GetIsObject());
  1863. this->m_writer.Unsigned1(Js::OpCode::InvalCachedScope, envIndex);
  1864. }
  1865. }
  1866. if (scope->GetMustInstantiate())
  1867. {
  1868. envIndex++;
  1869. }
  1870. }
  1871. }
  1872. void ByteCodeGenerator::LoadThisObject(FuncInfo *funcInfo, bool thisLoadedFromParams)
  1873. {
  1874. Symbol* thisSym = funcInfo->GetThisSymbol();
  1875. Assert(thisSym);
  1876. Assert(!funcInfo->IsLambda());
  1877. if (this->scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled() && funcInfo->IsClassConstructor())
  1878. {
  1879. // Derived class constructors initialize 'this' to be Undecl
  1880. // - we'll check this value during a super call and during 'this' access
  1881. //
  1882. // Base class constructors initialize 'this' to a new object using new.target
  1883. if (funcInfo->IsBaseClassConstructor())
  1884. {
  1885. Symbol* newTargetSym = funcInfo->GetNewTargetSymbol();
  1886. Assert(newTargetSym);
  1887. this->Writer()->Reg2(Js::OpCode::NewScObjectNoCtorFull, thisSym->GetLocation(), newTargetSym->GetLocation());
  1888. }
  1889. else
  1890. {
  1891. this->m_writer.Reg1(Js::OpCode::InitUndecl, thisSym->GetLocation());
  1892. }
  1893. }
  1894. else if (!funcInfo->IsGlobalFunction())
  1895. {
  1896. //
  1897. // thisLoadedFromParams would be true for the event Handler case,
  1898. // "this" would have been loaded from parameters to put in the environment
  1899. //
  1900. if (!thisLoadedFromParams)
  1901. {
  1902. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  1903. m_writer.ArgIn0(tmpReg);
  1904. EmitThis(funcInfo, thisSym->GetLocation(), tmpReg);
  1905. funcInfo->ReleaseTmpRegister(tmpReg);
  1906. }
  1907. else
  1908. {
  1909. EmitThis(funcInfo, thisSym->GetLocation(), thisSym->GetLocation());
  1910. }
  1911. }
  1912. else
  1913. {
  1914. Assert(funcInfo->IsGlobalFunction());
  1915. Js::RegSlot root = funcInfo->nullConstantRegister;
  1916. EmitThis(funcInfo, thisSym->GetLocation(), root);
  1917. }
  1918. }
  1919. void ByteCodeGenerator::LoadNewTargetObject(FuncInfo *funcInfo)
  1920. {
  1921. Symbol* newTargetSym = funcInfo->GetNewTargetSymbol();
  1922. Assert(newTargetSym);
  1923. if (funcInfo->IsClassConstructor())
  1924. {
  1925. Assert(!funcInfo->IsLambda());
  1926. m_writer.ArgIn0(newTargetSym->GetLocation());
  1927. }
  1928. else if (funcInfo->IsGlobalFunction())
  1929. {
  1930. m_writer.Reg1(Js::OpCode::LdUndef, newTargetSym->GetLocation());
  1931. }
  1932. else
  1933. {
  1934. m_writer.Reg1(Js::OpCode::LdNewTarget, newTargetSym->GetLocation());
  1935. }
  1936. }
  1937. void ByteCodeGenerator::LoadSuperConstructorObject(FuncInfo *funcInfo)
  1938. {
  1939. Symbol* superConstructorSym = funcInfo->GetSuperConstructorSymbol();
  1940. Assert(superConstructorSym);
  1941. Assert(!funcInfo->IsLambda());
  1942. if (funcInfo->IsDerivedClassConstructor())
  1943. {
  1944. m_writer.Reg1(Js::OpCode::LdFuncObj, superConstructorSym->GetLocation());
  1945. }
  1946. else
  1947. {
  1948. m_writer.Reg1(Js::OpCode::LdUndef, superConstructorSym->GetLocation());
  1949. }
  1950. }
  1951. void ByteCodeGenerator::LoadSuperObject(FuncInfo *funcInfo)
  1952. {
  1953. Symbol* superSym = funcInfo->GetSuperSymbol();
  1954. Assert(superSym);
  1955. Assert(!funcInfo->IsLambda());
  1956. m_writer.Reg1(Js::OpCode::LdHomeObj, superSym->GetLocation());
  1957. }
  1958. void ByteCodeGenerator::EmitSuperCall(FuncInfo* funcInfo, ParseNodeSuperCall * pnodeSuperCall, BOOL fReturnValue)
  1959. {
  1960. FuncInfo* nonLambdaFunc = funcInfo;
  1961. bool isResultUsed = pnodeSuperCall->isUsed;
  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. pnodeSuperCall->isUsed = true;
  1973. // pnode->location refers to two things: the result of the inner function call (`temp` in the pseudocode below),
  1974. // and the result of the super() expression itself
  1975. funcInfo->AcquireLoc(pnodeSuperCall);
  1976. // We need to emit 'this' directly so we can skip throwing a reference error if 'this' is currently undecl (we want to get undecl if 'this' is undecl)
  1977. funcInfo->AcquireLoc(pnodeSuperCall->pnodeThis);
  1978. EmitPropLoadThis(pnodeSuperCall->pnodeThis->location, pnodeSuperCall->pnodeThis, funcInfo, false);
  1979. EmitLoad(pnodeSuperCall->pnodeNewTarget, this, funcInfo);
  1980. Assert(pnodeSuperCall->isSuperCall);
  1981. EmitLoad(pnodeSuperCall->pnodeTarget, this, funcInfo);
  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. Js::RegSlot thisForSuperCall = funcInfo->AcquireTmpRegister();
  2001. Js::RegSlot valueForThis = funcInfo->AcquireTmpRegister();
  2002. Js::RegSlot tmpUndeclReg = funcInfo->AcquireTmpRegister();
  2003. Js::ByteCodeLabel useNewTargetForThisLabel = this->Writer()->DefineLabel();
  2004. Js::ByteCodeLabel makeCallLabel = this->Writer()->DefineLabel();
  2005. Js::ByteCodeLabel useSuperCallResultLabel = this->Writer()->DefineLabel();
  2006. Js::ByteCodeLabel doneLabel = this->Writer()->DefineLabel();
  2007. Js::RegSlot tmpReg = this->EmitLdObjProto(Js::OpCode::LdFuncObjProto, pnodeSuperCall->pnodeTarget->location, funcInfo);
  2008. this->Writer()->BrReg1(Js::OpCode::BrOnClassConstructor, useNewTargetForThisLabel, tmpReg);
  2009. this->Writer()->Reg2(Js::OpCode::NewScObjectNoCtorFull, thisForSuperCall, pnodeSuperCall->pnodeNewTarget->location);
  2010. this->Writer()->Br(Js::OpCode::Br, makeCallLabel);
  2011. this->Writer()->MarkLabel(useNewTargetForThisLabel);
  2012. this->Writer()->Reg2(Js::OpCode::Ld_A, thisForSuperCall, pnodeSuperCall->pnodeNewTarget->location);
  2013. this->Writer()->MarkLabel(makeCallLabel);
  2014. EmitCall(pnodeSuperCall, this, funcInfo, fReturnValue, /*fEvaluateComponents*/ true, thisForSuperCall, pnodeSuperCall->pnodeNewTarget->location);
  2015. // We have to use another temp for the this value before assigning to this register.
  2016. // This is because IRBuilder does not expect us to use the value of a temp after potentially assigning to that same temp.
  2017. // Ex:
  2018. // _this = new.target;
  2019. // temp = super.call(_this);
  2020. // if (temp is object) {
  2021. // _this = temp; // creates a new sym for _this as it was previously used
  2022. // }
  2023. // this = _this; // tries to loads a value from the old sym (which is dead)
  2024. this->Writer()->BrReg1(Js::OpCode::BrOnObject_A, useSuperCallResultLabel, pnodeSuperCall->location);
  2025. this->Writer()->Reg2(Js::OpCode::Ld_A, valueForThis, thisForSuperCall);
  2026. this->Writer()->Br(Js::OpCode::Br, doneLabel);
  2027. this->Writer()->MarkLabel(useSuperCallResultLabel);
  2028. this->Writer()->Reg2(Js::OpCode::Ld_A, valueForThis, pnodeSuperCall->location);
  2029. this->Writer()->MarkLabel(doneLabel);
  2030. // The call is done and we know what we will bind to 'this' so let's check to see if 'this' is already decl.
  2031. Js::ByteCodeLabel skipLabel = this->Writer()->DefineLabel();
  2032. this->Writer()->Reg1(Js::OpCode::InitUndecl, tmpUndeclReg);
  2033. this->Writer()->BrReg2(Js::OpCode::BrSrEq_A, skipLabel, pnodeSuperCall->pnodeThis->location, tmpUndeclReg);
  2034. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_ClassThisAlreadyAssigned));
  2035. this->Writer()->MarkLabel(skipLabel);
  2036. // If calling code cares about the return value, then move the selected `this` value into the result register.
  2037. if (isResultUsed)
  2038. {
  2039. this->Writer()->Reg2(Js::OpCode::Ld_A, pnodeSuperCall->location, valueForThis);
  2040. }
  2041. Symbol* thisSym = pnodeSuperCall->pnodeThis->sym;
  2042. this->Writer()->Reg2(Js::OpCode::StrictLdThis, pnodeSuperCall->pnodeThis->location, valueForThis);
  2043. EmitPropStoreForSpecialSymbol(pnodeSuperCall->pnodeThis->location, thisSym, pnodeSuperCall->pnodeThis->pid, funcInfo, false);
  2044. funcInfo->ReleaseTmpRegister(tmpUndeclReg);
  2045. funcInfo->ReleaseTmpRegister(valueForThis);
  2046. funcInfo->ReleaseTmpRegister(thisForSuperCall);
  2047. funcInfo->ReleaseLoc(pnodeSuperCall->pnodeTarget);
  2048. funcInfo->ReleaseLoc(pnodeSuperCall->pnodeNewTarget);
  2049. funcInfo->ReleaseLoc(pnodeSuperCall->pnodeThis);
  2050. }
  2051. void ByteCodeGenerator::EmitClassConstructorEndCode(FuncInfo *funcInfo)
  2052. {
  2053. Symbol* thisSym = funcInfo->GetThisSymbol();
  2054. if (thisSym && thisSym->GetLocation() != Js::Constants::NoRegister)
  2055. {
  2056. EmitPropLoad(ByteCodeGenerator::ReturnRegister, thisSym, thisSym->GetPid(), funcInfo, true);
  2057. this->m_writer.Reg1(Js::OpCode::ChkUndecl, ByteCodeGenerator::ReturnRegister);
  2058. }
  2059. }
  2060. void ByteCodeGenerator::EmitThis(FuncInfo *funcInfo, Js::RegSlot lhsLocation, Js::RegSlot fromRegister)
  2061. {
  2062. if (funcInfo->byteCodeFunction->GetIsStrictMode() && !funcInfo->IsGlobalFunction() && !funcInfo->IsLambda())
  2063. {
  2064. m_writer.Reg2(Js::OpCode::StrictLdThis, lhsLocation, fromRegister);
  2065. }
  2066. else
  2067. {
  2068. m_writer.Reg2Int1(Js::OpCode::LdThis, lhsLocation, fromRegister, this->GetModuleID());
  2069. }
  2070. }
  2071. void ByteCodeGenerator::EmitLoadFormalIntoRegister(ParseNode *pnodeFormal, Js::RegSlot pos, FuncInfo *funcInfo)
  2072. {
  2073. if (pnodeFormal->IsVarLetOrConst())
  2074. {
  2075. // Get the param from its argument position into its assigned register.
  2076. // The position should match the location, otherwise, it has been shadowed by parameter with the same name
  2077. Symbol *formal = pnodeFormal->AsParseNodeVar()->sym;
  2078. if (formal->GetLocation() + 1 == pos)
  2079. {
  2080. // Transfer to the frame object, etc., if necessary.
  2081. this->EmitLocalPropInit(formal->GetLocation(), formal, funcInfo);
  2082. }
  2083. }
  2084. }
  2085. void ByteCodeGenerator::HomeArguments(FuncInfo *funcInfo)
  2086. {
  2087. if (ShouldTrackDebuggerMetadata())
  2088. {
  2089. // Add formals to the debugger propertyidcontainer for reg slots
  2090. auto addFormalsToPropertyIdContainer = [this, funcInfo](ParseNode *pnodeFormal)
  2091. {
  2092. if (pnodeFormal->IsVarLetOrConst())
  2093. {
  2094. Symbol* formal = pnodeFormal->AsParseNodeVar()->sym;
  2095. if (!formal->IsInSlot(this, funcInfo))
  2096. {
  2097. Assert(!formal->GetHasInit());
  2098. funcInfo->GetParsedFunctionBody()->InsertSymbolToRegSlotList(formal->GetName(), formal->GetLocation(), funcInfo->varRegsCount);
  2099. }
  2100. }
  2101. };
  2102. MapFormals(funcInfo->root, addFormalsToPropertyIdContainer);
  2103. }
  2104. // Transfer formal parameters to their home locations on the local frame.
  2105. if (funcInfo->GetHasArguments())
  2106. {
  2107. if (funcInfo->root->pnodeRest != nullptr)
  2108. {
  2109. // Since we don't have to iterate over arguments here, we'll trust the location to be correct.
  2110. EmitLoadFormalIntoRegister(funcInfo->root->pnodeRest, funcInfo->root->pnodeRest->sym->GetLocation() + 1, funcInfo);
  2111. }
  2112. // The arguments object creation helper does this work for us.
  2113. return;
  2114. }
  2115. Js::ArgSlot pos = 1;
  2116. auto loadFormal = [&](ParseNode *pnodeFormal)
  2117. {
  2118. EmitLoadFormalIntoRegister(pnodeFormal, pos, funcInfo);
  2119. pos++;
  2120. };
  2121. MapFormals(funcInfo->root, loadFormal);
  2122. }
  2123. void ByteCodeGenerator::DefineLabels(FuncInfo *funcInfo)
  2124. {
  2125. funcInfo->singleExit = m_writer.DefineLabel();
  2126. SList<ParseNodeStmt *>::Iterator iter(&funcInfo->targetStatements);
  2127. while (iter.Next())
  2128. {
  2129. ParseNodeStmt * node = iter.Data();
  2130. node->breakLabel = m_writer.DefineLabel();
  2131. node->continueLabel = m_writer.DefineLabel();
  2132. node->emitLabels = true;
  2133. }
  2134. }
  2135. void ByteCodeGenerator::EmitGlobalBody(FuncInfo *funcInfo)
  2136. {
  2137. // Emit global code (global scope or eval), fixing up the return register with the implicit
  2138. // return value.
  2139. ParseNode *pnode = funcInfo->root->pnodeBody;
  2140. ParseNode *pnodeLastVal = funcInfo->root->AsParseNodeProg()->pnodeLastValStmt;
  2141. if (pnodeLastVal == nullptr || pnodeLastVal->IsPatternDeclaration())
  2142. {
  2143. // We're not guaranteed to compute any values, so fix up the return register at the top
  2144. // in case.
  2145. this->m_writer.Reg1(Js::OpCode::LdUndef, ReturnRegister);
  2146. }
  2147. while (pnode->nop == knopList)
  2148. {
  2149. ParseNode *stmt = pnode->AsParseNodeBin()->pnode1;
  2150. if (stmt == pnodeLastVal)
  2151. {
  2152. pnodeLastVal = nullptr;
  2153. }
  2154. if (pnodeLastVal == nullptr && (this->flags & fscrReturnExpression))
  2155. {
  2156. EmitTopLevelStatement(stmt, funcInfo, true);
  2157. }
  2158. else
  2159. {
  2160. // Haven't hit the post-dominating return value yet,
  2161. // so don't bother with the return register.
  2162. EmitTopLevelStatement(stmt, funcInfo, false);
  2163. }
  2164. pnode = pnode->AsParseNodeBin()->pnode2;
  2165. }
  2166. EmitTopLevelStatement(pnode, funcInfo, false);
  2167. }
  2168. void ByteCodeGenerator::EmitFunctionBody(FuncInfo *funcInfo)
  2169. {
  2170. // Emit a function body. Only explicit returns and the implicit "undef" at the bottom
  2171. // get copied to the return register.
  2172. ParseNode *pnodeBody = funcInfo->root->pnodeBody;
  2173. ParseNode *pnode = pnodeBody;
  2174. while (pnode->nop == knopList)
  2175. {
  2176. ParseNode *stmt = pnode->AsParseNodeBin()->pnode1;
  2177. if (stmt->CapturesSyms())
  2178. {
  2179. CapturedSymMap *map = funcInfo->EnsureCapturedSymMap();
  2180. SList<Symbol*> *list = map->Item(stmt);
  2181. FOREACH_SLIST_ENTRY(Symbol*, sym, list)
  2182. {
  2183. if (!sym->GetIsCommittedToSlot())
  2184. {
  2185. Assert(sym->GetLocation() != Js::Constants::NoProperty);
  2186. sym->SetIsCommittedToSlot();
  2187. ParseNode *decl = sym->GetDecl();
  2188. Assert(decl);
  2189. if (PHASE_TRACE(Js::DelayCapturePhase, funcInfo->byteCodeFunction))
  2190. {
  2191. Output::Print(_u("--- DelayCapture: Committed symbol '%s' to slot.\n"),
  2192. sym->GetName().GetBuffer());
  2193. Output::Flush();
  2194. }
  2195. // REVIEW[ianhall]: HACK to work around this causing an error due to sym not yet being initialized
  2196. // what is this doing? Why are we assigning sym to itself?
  2197. bool old = sym->GetNeedDeclaration();
  2198. sym->SetNeedDeclaration(false);
  2199. this->EmitPropStore(sym->GetLocation(), sym, sym->GetPid(), funcInfo, decl->nop == knopLetDecl, decl->nop == knopConstDecl);
  2200. sym->SetNeedDeclaration(old);
  2201. }
  2202. }
  2203. NEXT_SLIST_ENTRY;
  2204. }
  2205. EmitTopLevelStatement(stmt, funcInfo, false);
  2206. pnode = pnode->AsParseNodeBin()->pnode2;
  2207. }
  2208. Assert(!pnode->CapturesSyms());
  2209. EmitTopLevelStatement(pnode, funcInfo, false);
  2210. }
  2211. void ByteCodeGenerator::EmitProgram(ParseNodeProg *pnodeProg)
  2212. {
  2213. // Indicate that the binding phase is over.
  2214. this->isBinding = false;
  2215. this->trackEnvDepth = true;
  2216. AssignPropertyIds(pnodeProg->funcInfo->byteCodeFunction);
  2217. int32 initSize = this->maxAstSize / AstBytecodeRatioEstimate;
  2218. // Use the temp allocator in bytecode write temp buffer.
  2219. m_writer.InitData(this->alloc, initSize);
  2220. #ifdef LOG_BYTECODE_AST_RATIO
  2221. // log the max Ast size
  2222. Output::Print(_u("Max Ast size: %d"), initSize);
  2223. #endif
  2224. Assert(pnodeProg && pnodeProg->nop == knopProg);
  2225. if (this->parentScopeInfo)
  2226. {
  2227. // Scope stack is already set up the way we want it, so don't visit the global scope.
  2228. // Start emitting with the nested scope (i.e., the deferred function).
  2229. this->EmitScopeList(pnodeProg->pnodeScopes);
  2230. }
  2231. else
  2232. {
  2233. this->EmitScopeList(pnodeProg);
  2234. }
  2235. }
  2236. void EmitDestructuredObject(ParseNode *lhs, Js::RegSlot rhsLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  2237. void EmitDestructuredValueOrInitializer(ParseNodePtr lhsElementNode, Js::RegSlot rhsLocation, ParseNodePtr initializer, bool isNonPatternAssignmentTarget, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  2238. void ByteCodeGenerator::PopulateFormalsScope(uint beginOffset, FuncInfo *funcInfo, ParseNodeFnc *pnodeFnc)
  2239. {
  2240. Js::DebuggerScope *debuggerScope = nullptr;
  2241. auto processArg = [&](ParseNode *pnodeArg) {
  2242. if (pnodeArg->IsVarLetOrConst())
  2243. {
  2244. if (debuggerScope == nullptr)
  2245. {
  2246. debuggerScope = RecordStartScopeObject(pnodeFnc, funcInfo->paramScope && funcInfo->paramScope->GetIsObject() ? Js::DiagParamScopeInObject : Js::DiagParamScope);
  2247. debuggerScope->SetBegin(beginOffset);
  2248. }
  2249. InsertPropertyToDebuggerScope(funcInfo, debuggerScope, pnodeArg->AsParseNodeVar()->sym);
  2250. }
  2251. };
  2252. MapFormals(pnodeFnc, processArg);
  2253. MapFormalsFromPattern(pnodeFnc, processArg);
  2254. if (debuggerScope != nullptr)
  2255. {
  2256. if (!funcInfo->GetParsedFunctionBody()->IsParamAndBodyScopeMerged())
  2257. {
  2258. InsertPropertyToDebuggerScope(funcInfo, debuggerScope, funcInfo->GetArgumentsSymbol());
  2259. }
  2260. RecordEndScopeObject(pnodeFnc);
  2261. }
  2262. }
  2263. void ByteCodeGenerator::InsertPropertyToDebuggerScope(FuncInfo* funcInfo, Js::DebuggerScope* debuggerScope, Symbol* sym)
  2264. {
  2265. if (sym)
  2266. {
  2267. Js::FunctionBody* funcBody = funcInfo->GetParsedFunctionBody();
  2268. Js::DebuggerScopePropertyFlags flag = Js::DebuggerScopePropertyFlags_None;
  2269. Js::RegSlot location = sym->GetLocation();
  2270. if (ShouldTrackDebuggerMetadata() && !funcInfo->IsBodyAndParamScopeMerged() && funcInfo->bodyScope->FindLocalSymbol(sym->GetName()) != nullptr)
  2271. {
  2272. flag |= Js::DebuggerScopePropertyFlags_HasDuplicateInBody;
  2273. location = funcBody->MapRegSlot(location);
  2274. }
  2275. debuggerScope->AddProperty(location, sym->EnsurePosition(funcInfo), flag);
  2276. }
  2277. }
  2278. void ByteCodeGenerator::EmitDefaultArgs(FuncInfo *funcInfo, ParseNodeFnc *pnodeFnc)
  2279. {
  2280. uint beginOffset = m_writer.GetCurrentOffset();
  2281. auto emitDefaultArg = [&](ParseNode *pnodeArg)
  2282. {
  2283. if (pnodeArg->nop == knopParamPattern)
  2284. {
  2285. this->StartStatement(pnodeArg);
  2286. Assert(pnodeArg->AsParseNodeParamPattern()->location != Js::Constants::NoRegister);
  2287. ParseNodePtr pnode1 = pnodeArg->AsParseNodeParamPattern()->pnode1;
  2288. if (pnode1->IsPattern())
  2289. {
  2290. EmitAssignment(nullptr, pnode1, pnodeArg->AsParseNodeParamPattern()->location, this, funcInfo);
  2291. }
  2292. else
  2293. {
  2294. Assert(pnode1->nop == knopAsg);
  2295. Assert(pnode1->AsParseNodeBin()->pnode1->IsPattern());
  2296. EmitDestructuredValueOrInitializer(pnode1->AsParseNodeBin()->pnode1,
  2297. pnodeArg->AsParseNodeParamPattern()->location,
  2298. pnode1->AsParseNodeBin()->pnode2,
  2299. false /*isNonPatternAssignmentTarget*/,
  2300. this,
  2301. funcInfo);
  2302. }
  2303. this->EndStatement(pnodeArg);
  2304. return;
  2305. }
  2306. else if (pnodeArg->IsVarLetOrConst())
  2307. {
  2308. Js::RegSlot location = pnodeArg->AsParseNodeVar()->sym->GetLocation();
  2309. if (pnodeArg->AsParseNodeVar()->pnodeInit == nullptr)
  2310. {
  2311. // Since the formal hasn't been initialized in LdLetHeapArguments, we'll initialize it here.
  2312. pnodeArg->AsParseNodeVar()->sym->SetNeedDeclaration(false);
  2313. EmitPropStore(location, pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo, true);
  2314. return;
  2315. }
  2316. // Load the default argument if we got undefined, skip RHS evaluation otherwise.
  2317. Js::ByteCodeLabel noDefaultLabel = this->m_writer.DefineLabel();
  2318. Js::ByteCodeLabel endLabel = this->m_writer.DefineLabel();
  2319. this->StartStatement(pnodeArg);
  2320. // Let us use strict not equal to differentiate between null and undefined
  2321. m_writer.BrReg2(Js::OpCode::BrSrNeq_A, noDefaultLabel, location, funcInfo->undefinedConstantRegister);
  2322. Emit(pnodeArg->AsParseNodeVar()->pnodeInit, this, funcInfo, false);
  2323. pnodeArg->AsParseNodeVar()->sym->SetNeedDeclaration(false); // After emit to prevent foo(a = a)
  2324. if (funcInfo->GetHasArguments() && pnodeArg->AsParseNodeVar()->sym->IsInSlot(this, funcInfo))
  2325. {
  2326. EmitPropStore(pnodeArg->AsParseNodeVar()->pnodeInit->location, pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo, true);
  2327. m_writer.Br(endLabel);
  2328. }
  2329. else
  2330. {
  2331. EmitAssignment(nullptr, pnodeArg, pnodeArg->AsParseNodeVar()->pnodeInit->location, this, funcInfo);
  2332. }
  2333. funcInfo->ReleaseLoc(pnodeArg->AsParseNodeVar()->pnodeInit);
  2334. m_writer.MarkLabel(noDefaultLabel);
  2335. if (funcInfo->GetHasArguments() && pnodeArg->AsParseNodeVar()->sym->IsInSlot(this, funcInfo))
  2336. {
  2337. EmitPropStore(location, pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo, true);
  2338. m_writer.MarkLabel(endLabel);
  2339. }
  2340. this->EndStatement(pnodeArg);
  2341. }
  2342. };
  2343. // If the function is async, we wrap the default arguments in a try catch and reject a Promise in case of error.
  2344. if (pnodeFnc->IsAsync())
  2345. {
  2346. uint cacheId;
  2347. Js::ByteCodeLabel catchLabel = m_writer.DefineLabel();
  2348. Js::ByteCodeLabel doneLabel = m_writer.DefineLabel();
  2349. Js::RegSlot catchArgLocation = funcInfo->AcquireTmpRegister();
  2350. Js::RegSlot promiseLocation = funcInfo->AcquireTmpRegister();
  2351. Js::RegSlot rejectLocation = funcInfo->AcquireTmpRegister();
  2352. // try
  2353. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  2354. m_writer.Br(Js::OpCode::TryCatch, catchLabel);
  2355. // Rest cannot have a default argument, so we ignore it.
  2356. MapFormalsWithoutRest(pnodeFnc, emitDefaultArg);
  2357. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  2358. m_writer.Empty(Js::OpCode::Leave);
  2359. m_writer.Br(doneLabel);
  2360. // catch
  2361. m_writer.MarkLabel(catchLabel);
  2362. m_writer.Reg1(Js::OpCode::Catch, catchArgLocation);
  2363. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  2364. m_writer.Empty(Js::OpCode::Nop);
  2365. // return Promise.reject(error);
  2366. cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(Js::PropertyIds::Promise, false, false);
  2367. m_writer.PatchableRootProperty(Js::OpCode::LdRootFld, promiseLocation, cacheId, false, false);
  2368. EmitInvoke(rejectLocation, promiseLocation, Js::PropertyIds::reject, this, funcInfo, catchArgLocation);
  2369. m_writer.Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, rejectLocation);
  2370. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  2371. m_writer.Empty(Js::OpCode::Leave);
  2372. m_writer.Br(funcInfo->singleExit);
  2373. m_writer.Empty(Js::OpCode::Leave);
  2374. m_writer.MarkLabel(doneLabel);
  2375. this->SetHasTry(true);
  2376. funcInfo->ReleaseTmpRegister(rejectLocation);
  2377. funcInfo->ReleaseTmpRegister(promiseLocation);
  2378. funcInfo->ReleaseTmpRegister(catchArgLocation);
  2379. }
  2380. else
  2381. {
  2382. // Rest cannot have a default argument, so we ignore it.
  2383. MapFormalsWithoutRest(pnodeFnc, emitDefaultArg);
  2384. }
  2385. if (m_writer.GetCurrentOffset() > beginOffset)
  2386. {
  2387. PopulateFormalsScope(beginOffset, funcInfo, pnodeFnc);
  2388. }
  2389. }
  2390. void ByteCodeGenerator::EmitOneFunction(ParseNodeFnc *pnodeFnc)
  2391. {
  2392. Assert(pnodeFnc && (pnodeFnc->nop == knopProg || pnodeFnc->nop == knopFncDecl));
  2393. FuncInfo *funcInfo = pnodeFnc->funcInfo;
  2394. Assert(funcInfo != nullptr);
  2395. if (funcInfo->IsFakeGlobalFunction(this->flags))
  2396. {
  2397. return;
  2398. }
  2399. Js::ParseableFunctionInfo* deferParseFunction = funcInfo->byteCodeFunction;
  2400. deferParseFunction->SetGrfscr(deferParseFunction->GetGrfscr() | (this->flags & ~fscrDeferredFncExpression));
  2401. deferParseFunction->SetSourceInfo(this->GetCurrentSourceIndex(),
  2402. funcInfo->root,
  2403. !!(this->flags & fscrEvalCode),
  2404. ((this->flags & fscrDynamicCode) && !(this->flags & fscrEvalCode)));
  2405. deferParseFunction->SetInParamsCount(funcInfo->inArgsCount);
  2406. if (pnodeFnc->HasDefaultArguments())
  2407. {
  2408. deferParseFunction->SetReportedInParamsCount(pnodeFnc->firstDefaultArg + 1);
  2409. }
  2410. else
  2411. {
  2412. deferParseFunction->SetReportedInParamsCount(funcInfo->inArgsCount);
  2413. }
  2414. // Note: Don't check the actual attributes on the functionInfo here, since CanDefer has been cleared while
  2415. // we're generating byte code.
  2416. if (deferParseFunction->IsDeferred() || funcInfo->canDefer)
  2417. {
  2418. Js::ScopeInfo::SaveEnclosingScopeInfo(this, funcInfo);
  2419. }
  2420. if (funcInfo->root->pnodeBody == nullptr)
  2421. {
  2422. if (!PHASE_OFF1(Js::SkipNestedDeferredPhase) && (this->GetFlags() & fscrCreateParserState) == fscrCreateParserState && deferParseFunction->GetCompileCount() == 0)
  2423. {
  2424. deferParseFunction->BuildDeferredStubs(funcInfo->root);
  2425. }
  2426. Assert(!deferParseFunction->IsFunctionBody() || deferParseFunction->GetFunctionBody()->GetByteCode() != nullptr);
  2427. return;
  2428. }
  2429. Js::FunctionBody* byteCodeFunction = funcInfo->GetParsedFunctionBody();
  2430. try
  2431. {
  2432. if (!funcInfo->IsGlobalFunction())
  2433. {
  2434. // Note: Do not set the stack nested func flag if the function has been redeferred and recompiled.
  2435. // In that case the flag already has the value we want.
  2436. if (CanStackNestedFunc(funcInfo, true) && byteCodeFunction->GetCompileCount() == 0)
  2437. {
  2438. #if DBG
  2439. byteCodeFunction->SetCanDoStackNestedFunc();
  2440. #endif
  2441. if (funcInfo->root->astSize <= ParseNodeFnc::MaxStackClosureAST)
  2442. {
  2443. byteCodeFunction->SetStackNestedFunc(true);
  2444. }
  2445. }
  2446. }
  2447. if (byteCodeFunction->DoStackNestedFunc())
  2448. {
  2449. uint nestedCount = byteCodeFunction->GetNestedCount();
  2450. for (uint i = 0; i < nestedCount; i++)
  2451. {
  2452. Js::FunctionProxy * nested = byteCodeFunction->GetNestedFunctionProxy(i);
  2453. if (nested->IsFunctionBody())
  2454. {
  2455. nested->GetFunctionBody()->SetStackNestedFuncParent(byteCodeFunction->GetFunctionInfo());
  2456. }
  2457. }
  2458. }
  2459. if (byteCodeFunction->GetByteCode() != nullptr)
  2460. {
  2461. // Previously compiled function nested within a re-deferred and re-compiled function.
  2462. return;
  2463. }
  2464. // Bug : 301517
  2465. // In the debug mode the hasOnlyThis optimization needs to be disabled, since user can break in this function
  2466. // and do operation on 'this' and its property, which may not be defined yet.
  2467. if (funcInfo->root->HasOnlyThisStmts() && !IsInDebugMode())
  2468. {
  2469. byteCodeFunction->SetHasOnlyThisStmts(true);
  2470. }
  2471. if (byteCodeFunction->IsInlineApplyDisabled() || this->scriptContext->GetConfig()->IsNoNative())
  2472. {
  2473. if ((pnodeFnc->nop == knopFncDecl) && (funcInfo->GetHasHeapArguments()) && (!funcInfo->GetCallsEval()) && ApplyEnclosesArgs(pnodeFnc, this))
  2474. {
  2475. bool applyEnclosesArgs = true;
  2476. for (ParseNode* pnodeVar = funcInfo->root->pnodeVars; pnodeVar; pnodeVar = pnodeVar->AsParseNodeVar()->pnodeNext)
  2477. {
  2478. Symbol* sym = pnodeVar->AsParseNodeVar()->sym;
  2479. if (sym->GetSymbolType() == STVariable && !sym->IsArguments())
  2480. {
  2481. applyEnclosesArgs = false;
  2482. break;
  2483. }
  2484. }
  2485. auto constAndLetCheck = [](ParseNodeBlock *pnodeBlock, bool *applyEnclosesArgs)
  2486. {
  2487. if (*applyEnclosesArgs)
  2488. {
  2489. for (auto lexvar = pnodeBlock->pnodeLexVars; lexvar; lexvar = lexvar->AsParseNodeVar()->pnodeNext)
  2490. {
  2491. Symbol* sym = lexvar->AsParseNodeVar()->sym;
  2492. if (sym->GetSymbolType() == STVariable && !sym->IsArguments())
  2493. {
  2494. *applyEnclosesArgs = false;
  2495. break;
  2496. }
  2497. }
  2498. }
  2499. };
  2500. constAndLetCheck(funcInfo->root->pnodeScopes, &applyEnclosesArgs);
  2501. constAndLetCheck(funcInfo->root->pnodeBodyScope, &applyEnclosesArgs);
  2502. funcInfo->SetApplyEnclosesArgs(applyEnclosesArgs);
  2503. }
  2504. }
  2505. InitScopeSlotArray(funcInfo);
  2506. FinalizeRegisters(funcInfo, byteCodeFunction);
  2507. DebugOnly(Js::RegSlot firstTmpReg = funcInfo->varRegsCount);
  2508. // Reserve temp registers for the inner scopes. We prefer temps because the JIT will then renumber them
  2509. // and see different lifetimes. (Note that debug mode requires permanent registers. See FinalizeRegisters.)
  2510. // Need to revisit the condition when enabling JitES6Generators.
  2511. uint innerScopeCount = funcInfo->InnerScopeCount();
  2512. if (!this->IsInDebugMode() && !byteCodeFunction->IsCoroutine())
  2513. {
  2514. byteCodeFunction->SetInnerScopeCount(innerScopeCount);
  2515. if (innerScopeCount)
  2516. {
  2517. funcInfo->SetFirstInnerScopeReg(funcInfo->AcquireTmpRegister());
  2518. for (uint i = 1; i < innerScopeCount; i++)
  2519. {
  2520. funcInfo->AcquireTmpRegister();
  2521. }
  2522. }
  2523. }
  2524. funcInfo->inlineCacheMap = Anew(alloc, FuncInfo::InlineCacheMap,
  2525. alloc,
  2526. funcInfo->RegCount() // Pass the actual register count. // TODO: Check if we can reduce this count
  2527. );
  2528. funcInfo->rootObjectLoadInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2529. alloc,
  2530. 10);
  2531. funcInfo->rootObjectLoadMethodInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2532. alloc,
  2533. 10);
  2534. funcInfo->rootObjectStoreInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2535. alloc,
  2536. 10);
  2537. funcInfo->referencedPropertyIdToMapIndex = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2538. alloc,
  2539. 10);
  2540. byteCodeFunction->AllocateLiteralRegexArray();
  2541. m_callSiteId = 0;
  2542. m_writer.Begin(byteCodeFunction, alloc, this->DoJitLoopBodies(funcInfo), funcInfo->hasLoop, this->IsInDebugMode());
  2543. this->PushFuncInfo(_u("EmitOneFunction"), funcInfo);
  2544. this->inPrologue = true;
  2545. Scope* paramScope = funcInfo->GetParamScope();
  2546. Scope* bodyScope = funcInfo->GetBodyScope();
  2547. // For now, emit all constant loads at top of function (should instead put in closest dominator of uses).
  2548. LoadAllConstants(funcInfo);
  2549. HomeArguments(funcInfo);
  2550. if (!funcInfo->IsBodyAndParamScopeMerged())
  2551. {
  2552. byteCodeFunction->SetParamAndBodyScopeNotMerged();
  2553. // Pop the body scope before emitting the default args
  2554. PopScope();
  2555. Assert(this->GetCurrentScope() == paramScope);
  2556. }
  2557. if (funcInfo->root->pnodeRest != nullptr)
  2558. {
  2559. byteCodeFunction->SetHasRestParameter();
  2560. }
  2561. if (funcInfo->IsGlobalFunction())
  2562. {
  2563. EnsureNoRedeclarations(pnodeFnc->pnodeScopes, funcInfo);
  2564. }
  2565. ::BeginEmitBlock(pnodeFnc->pnodeScopes, this, funcInfo);
  2566. DefineLabels(funcInfo);
  2567. // We need to emit the storage for special symbols before we emit the default arguments in case the default
  2568. // argument expressions reference those special names.
  2569. if (pnodeFnc->HasNonSimpleParameterList())
  2570. {
  2571. // If the param and body scope are merged, the special symbol vars are located in the body scope so we
  2572. // need to walk over the var list.
  2573. if (funcInfo->IsBodyAndParamScopeMerged())
  2574. {
  2575. for (ParseNodePtr pnodeVar = pnodeFnc->pnodeVars; pnodeVar; pnodeVar = pnodeVar->AsParseNodeVar()->pnodeNext)
  2576. {
  2577. #if DBG
  2578. bool reachedEndOfSpecialSymbols = false;
  2579. #endif
  2580. Symbol* sym = pnodeVar->AsParseNodeVar()->sym;
  2581. if (sym != nullptr && sym->IsSpecialSymbol())
  2582. {
  2583. EmitPropStoreForSpecialSymbol(sym->GetLocation(), sym, sym->GetPid(), funcInfo, true);
  2584. if (ShouldTrackDebuggerMetadata() && !sym->IsInSlot(this, funcInfo))
  2585. {
  2586. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), sym->GetLocation(), funcInfo->varRegsCount);
  2587. }
  2588. }
  2589. else
  2590. {
  2591. #if DBG
  2592. reachedEndOfSpecialSymbols = true;
  2593. #else
  2594. // All of the special symbols exist at the beginning of the var list (parser guarantees this and debug build asserts this)
  2595. // so we can quit walking at the first non-special one we see.
  2596. break;
  2597. #endif
  2598. }
  2599. #if DBG
  2600. if (reachedEndOfSpecialSymbols)
  2601. {
  2602. Assert(sym == nullptr || !sym->IsSpecialSymbol());
  2603. }
  2604. #endif
  2605. }
  2606. }
  2607. else
  2608. {
  2609. paramScope->ForEachSymbol([&](Symbol* sym) {
  2610. if (sym && sym->IsSpecialSymbol())
  2611. {
  2612. EmitPropStoreForSpecialSymbol(sym->GetLocation(), sym, sym->GetPid(), funcInfo, true);
  2613. }
  2614. });
  2615. }
  2616. }
  2617. if (pnodeFnc->HasNonSimpleParameterList() || !funcInfo->IsBodyAndParamScopeMerged())
  2618. {
  2619. Assert(pnodeFnc->HasNonSimpleParameterList() || CONFIG_FLAG(ForceSplitScope));
  2620. this->InitBlockScopedNonTemps(funcInfo->root->pnodeScopes, funcInfo);
  2621. EmitDefaultArgs(funcInfo, pnodeFnc);
  2622. if (!funcInfo->IsBodyAndParamScopeMerged())
  2623. {
  2624. Assert(this->GetCurrentScope() == paramScope);
  2625. // Push the body scope
  2626. PushScope(bodyScope);
  2627. funcInfo->SetCurrentChildScope(bodyScope);
  2628. // Mark the beginning of the body scope so that new scope slots can be created.
  2629. this->Writer()->Empty(Js::OpCode::BeginBodyScope);
  2630. }
  2631. }
  2632. // If the function has non simple parameter list, the params needs to be evaluated when the generator object is created
  2633. // (that is when the function is called). This yield opcode is to mark the begining of the function body.
  2634. // TODO: Inserting a yield should have almost no impact on perf as it is a direct return from the function. But this needs
  2635. // to be verified. Ideally if the function has simple parameter list then we can avoid inserting the opcode and the additional call.
  2636. if (pnodeFnc->IsGenerator())
  2637. {
  2638. Js::RegSlot tempReg = funcInfo->AcquireTmpRegister();
  2639. EmitYield(funcInfo->AssignUndefinedConstRegister(), tempReg, this, funcInfo);
  2640. m_writer.Reg1(Js::OpCode::Unused, tempReg);
  2641. funcInfo->ReleaseTmpRegister(tempReg);
  2642. }
  2643. DefineUserVars(funcInfo);
  2644. // Emit all scope-wide function definitions before emitting function bodies
  2645. // so that calls may reference functions they precede lexically.
  2646. // Note, global eval scope is a fake local scope and is handled as if it were
  2647. // a lexical block instead of a true global scope, so do not define the functions
  2648. // here. They will be defined during BeginEmitBlock.
  2649. if (!(funcInfo->IsGlobalFunction() && this->IsEvalWithNoParentScopeInfo()))
  2650. {
  2651. // This only handles function declarations, which param scope cannot have any.
  2652. DefineFunctions(funcInfo);
  2653. }
  2654. if (pnodeFnc->HasNonSimpleParameterList() || !funcInfo->IsBodyAndParamScopeMerged())
  2655. {
  2656. Assert(pnodeFnc->HasNonSimpleParameterList() || CONFIG_FLAG(ForceSplitScope));
  2657. this->InitBlockScopedNonTemps(funcInfo->root->pnodeBodyScope, funcInfo);
  2658. }
  2659. else
  2660. {
  2661. this->InitBlockScopedNonTemps(funcInfo->root->pnodeScopes, funcInfo);
  2662. }
  2663. if (!pnodeFnc->HasNonSimpleParameterList() && funcInfo->GetHasArguments() && !NeedScopeObjectForArguments(funcInfo, pnodeFnc))
  2664. {
  2665. // If we didn't create a scope object and didn't have default args, we still need to transfer the formals to their slots.
  2666. MapFormalsWithoutRest(pnodeFnc, [&](ParseNode *pnodeArg) { EmitPropStore(pnodeArg->AsParseNodeVar()->sym->GetLocation(), pnodeArg->AsParseNodeVar()->sym, pnodeArg->AsParseNodeVar()->pid, funcInfo); });
  2667. }
  2668. // Rest needs to trigger use before declaration until all default args have been processed.
  2669. if (pnodeFnc->pnodeRest != nullptr)
  2670. {
  2671. pnodeFnc->pnodeRest->sym->SetNeedDeclaration(false);
  2672. }
  2673. Js::RegSlot formalsUpperBound = Js::Constants::NoRegister; // Needed for tracking the last RegSlot in the param scope
  2674. if (!funcInfo->IsBodyAndParamScopeMerged())
  2675. {
  2676. // Emit bytecode to copy the initial values from param names to their corresponding body bindings.
  2677. // We have to do this after the rest param is marked as false for need declaration.
  2678. Symbol* funcSym = funcInfo->root->GetFuncSymbol();
  2679. paramScope->ForEachSymbol([&](Symbol* param) {
  2680. Symbol* varSym = funcInfo->GetBodyScope()->FindLocalSymbol(param->GetName());
  2681. if ((funcSym == nullptr || funcSym != param) // Do not copy the symbol over to body as the function expression symbol
  2682. // is expected to stay inside the function expression scope
  2683. && (varSym && varSym->GetSymbolType() == STVariable && (varSym->IsInSlot(this, funcInfo) || varSym->GetLocation() != Js::Constants::NoRegister)))
  2684. {
  2685. if (!varSym->GetNeedDeclaration())
  2686. {
  2687. if (param->IsInSlot(this, funcInfo))
  2688. {
  2689. // Simulating EmitPropLoad here. We can't directly call the method as we have to use the param scope specifically.
  2690. // Walking the scope chain is not possible at this time.
  2691. Js::RegSlot tempReg = funcInfo->AcquireTmpRegister();
  2692. Js::PropertyId slot = param->EnsureScopeSlot(this, funcInfo);
  2693. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(paramScope, slot);
  2694. Js::OpCode op = paramScope->GetIsObject() ? Js::OpCode::LdParamObjSlot : Js::OpCode::LdParamSlot;
  2695. slot = slot + (paramScope->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  2696. this->m_writer.SlotI1(op, tempReg, slot, profileId);
  2697. this->EmitPropStore(tempReg, varSym, varSym->GetPid(), funcInfo);
  2698. funcInfo->ReleaseTmpRegister(tempReg);
  2699. }
  2700. else if (param->GetLocation() != Js::Constants::NoRegister)
  2701. {
  2702. this->EmitPropStore(param->GetLocation(), varSym, varSym->GetPid(), funcInfo);
  2703. }
  2704. else
  2705. {
  2706. Assert(param->IsArguments() && !funcInfo->GetHasArguments());
  2707. }
  2708. }
  2709. else
  2710. {
  2711. // There is a let redeclaration of arguments symbol. Any other var will cause a
  2712. // re-declaration error.
  2713. Assert(param->IsArguments());
  2714. }
  2715. }
  2716. if (ShouldTrackDebuggerMetadata() && param->GetLocation() != Js::Constants::NoRegister)
  2717. {
  2718. if (formalsUpperBound == Js::Constants::NoRegister || formalsUpperBound < param->GetLocation())
  2719. {
  2720. formalsUpperBound = param->GetLocation();
  2721. }
  2722. }
  2723. });
  2724. }
  2725. if (ShouldTrackDebuggerMetadata() && byteCodeFunction->GetPropertyIdOnRegSlotsContainer())
  2726. {
  2727. byteCodeFunction->GetPropertyIdOnRegSlotsContainer()->formalsUpperBound = formalsUpperBound;
  2728. }
  2729. if (pnodeFnc->pnodeBodyScope != nullptr)
  2730. {
  2731. ::BeginEmitBlock(pnodeFnc->pnodeBodyScope, this, funcInfo);
  2732. }
  2733. this->inPrologue = false;
  2734. if (funcInfo->IsGlobalFunction())
  2735. {
  2736. EmitGlobalBody(funcInfo);
  2737. }
  2738. else
  2739. {
  2740. EmitFunctionBody(funcInfo);
  2741. }
  2742. if (pnodeFnc->pnodeBodyScope != nullptr)
  2743. {
  2744. ::EndEmitBlock(pnodeFnc->pnodeBodyScope, this, funcInfo);
  2745. }
  2746. ::EndEmitBlock(pnodeFnc->pnodeScopes, this, funcInfo);
  2747. if (!this->IsInDebugMode())
  2748. {
  2749. // Release the temp registers that we reserved for inner scopes above.
  2750. if (innerScopeCount)
  2751. {
  2752. Js::RegSlot tmpReg = funcInfo->FirstInnerScopeReg() + innerScopeCount - 1;
  2753. for (uint i = 0; i < innerScopeCount; i++)
  2754. {
  2755. funcInfo->ReleaseTmpRegister(tmpReg);
  2756. tmpReg--;
  2757. }
  2758. }
  2759. }
  2760. Assert(funcInfo->firstTmpReg == firstTmpReg);
  2761. Assert(funcInfo->curTmpReg == firstTmpReg);
  2762. Assert(byteCodeFunction->GetFirstTmpReg() == firstTmpReg + byteCodeFunction->GetConstantCount());
  2763. byteCodeFunction->CheckAndSetVarCount(funcInfo->varRegsCount);
  2764. byteCodeFunction->CheckAndSetOutParamMaxDepth(funcInfo->outArgsMaxDepth);
  2765. byteCodeFunction->SetForInLoopDepth(funcInfo->GetMaxForInLoopLevel());
  2766. // Do a uint32 add just to verify that we haven't overflowed the reg slot type.
  2767. UInt32Math::Add(funcInfo->varRegsCount, funcInfo->constRegsCount);
  2768. #if DBG_DUMP
  2769. if (PHASE_STATS1(Js::ByteCodePhase))
  2770. {
  2771. Output::Print(_u(" BCode: %-10d, Aux: %-10d, AuxC: %-10d Total: %-10d, %s\n"),
  2772. m_writer.ByteCodeDataSize(),
  2773. m_writer.AuxiliaryDataSize(),
  2774. m_writer.AuxiliaryContextDataSize(),
  2775. m_writer.ByteCodeDataSize() + m_writer.AuxiliaryDataSize() + m_writer.AuxiliaryContextDataSize(),
  2776. funcInfo->name);
  2777. this->scriptContext->byteCodeDataSize += m_writer.ByteCodeDataSize();
  2778. this->scriptContext->byteCodeAuxiliaryDataSize += m_writer.AuxiliaryDataSize();
  2779. this->scriptContext->byteCodeAuxiliaryContextDataSize += m_writer.AuxiliaryContextDataSize();
  2780. }
  2781. #endif
  2782. this->MapCacheIdsToPropertyIds(funcInfo);
  2783. this->MapReferencedPropertyIds(funcInfo);
  2784. Assert(this->TopFuncInfo() == funcInfo);
  2785. PopFuncInfo(_u("EmitOneFunction"));
  2786. m_writer.SetCallSiteCount(m_callSiteId);
  2787. #ifdef LOG_BYTECODE_AST_RATIO
  2788. m_writer.End(funcInfo->root->astSize, this->maxAstSize);
  2789. #else
  2790. m_writer.End();
  2791. #endif
  2792. }
  2793. catch (...)
  2794. {
  2795. // Failed to generate byte-code for this function body (likely OOM or stack overflow). Notify the function body so that
  2796. // it can revert intermediate state changes that may have taken place during byte code generation before the failure.
  2797. byteCodeFunction->ResetByteCodeGenState();
  2798. m_writer.Reset();
  2799. throw;
  2800. }
  2801. #ifdef PERF_HINT
  2802. if (PHASE_TRACE1(Js::PerfHintPhase) && !byteCodeFunction->GetIsGlobalFunc())
  2803. {
  2804. if (byteCodeFunction->GetHasTry())
  2805. {
  2806. WritePerfHint(PerfHints::HasTryBlock_Verbose, byteCodeFunction);
  2807. }
  2808. if (funcInfo->GetCallsEval())
  2809. {
  2810. WritePerfHint(PerfHints::CallsEval_Verbose, byteCodeFunction);
  2811. }
  2812. else if (funcInfo->GetChildCallsEval())
  2813. {
  2814. WritePerfHint(PerfHints::ChildCallsEval, byteCodeFunction);
  2815. }
  2816. }
  2817. #endif
  2818. if (!byteCodeFunction->GetSourceContextInfo()->IsDynamic() && byteCodeFunction->GetIsTopLevel() && !(this->flags & fscrEvalCode))
  2819. {
  2820. // Add the top level of nested functions to the tracking dictionary. Wait until this point so that all nested functions have gone
  2821. // through the Emit API so source info, etc., is initialized, and these are not orphaned functions left behind by an unfinished pass.
  2822. byteCodeFunction->ForEachNestedFunc([&](Js::FunctionProxy * nestedFunc, uint32 i)
  2823. {
  2824. if (nestedFunc && nestedFunc->IsDeferredParseFunction() && nestedFunc->GetParseableFunctionInfo()->GetIsDeclaration())
  2825. {
  2826. byteCodeFunction->GetUtf8SourceInfo()->TrackDeferredFunction(nestedFunc->GetLocalFunctionId(), nestedFunc->GetParseableFunctionInfo());
  2827. }
  2828. return true;
  2829. });
  2830. }
  2831. byteCodeFunction->SetInitialDefaultEntryPoint();
  2832. byteCodeFunction->SetCompileCount(UInt32Math::Add(byteCodeFunction->GetCompileCount(), 1));
  2833. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2834. if (byteCodeFunction->IsInDebugMode() != scriptContext->IsScriptContextInDebugMode()) // debug mode mismatch
  2835. {
  2836. if (m_utf8SourceInfo->GetIsLibraryCode())
  2837. {
  2838. Assert(!byteCodeFunction->IsInDebugMode()); // Library script byteCode is never in debug mode
  2839. }
  2840. else
  2841. {
  2842. Js::Throw::FatalInternalError();
  2843. }
  2844. }
  2845. #endif
  2846. #if DBG_DUMP
  2847. if (PHASE_DUMP(Js::ByteCodePhase, funcInfo->byteCodeFunction) && Js::Configuration::Global.flags.Verbose)
  2848. {
  2849. pnodeFnc->Dump();
  2850. }
  2851. if (this->Trace() || PHASE_DUMP(Js::ByteCodePhase, funcInfo->byteCodeFunction))
  2852. {
  2853. Js::ByteCodeDumper::Dump(byteCodeFunction);
  2854. }
  2855. if (PHASE_DUMP(Js::DebuggerScopePhase, funcInfo->byteCodeFunction))
  2856. {
  2857. byteCodeFunction->DumpScopes();
  2858. }
  2859. #endif
  2860. #if ENABLE_NATIVE_CODEGEN
  2861. if ((!PHASE_OFF(Js::BackEndPhase, funcInfo->byteCodeFunction))
  2862. && !this->forceNoNative
  2863. && !this->scriptContext->GetConfig()->IsNoNative())
  2864. {
  2865. GenerateFunction(this->scriptContext->GetNativeCodeGenerator(), byteCodeFunction);
  2866. }
  2867. #endif
  2868. }
  2869. void ByteCodeGenerator::MapCacheIdsToPropertyIds(FuncInfo *funcInfo)
  2870. {
  2871. Js::FunctionBody *functionBody = funcInfo->GetParsedFunctionBody();
  2872. uint rootObjectLoadInlineCacheStart = funcInfo->GetInlineCacheCount();
  2873. uint rootObjectLoadMethodInlineCacheStart = rootObjectLoadInlineCacheStart + funcInfo->GetRootObjectLoadInlineCacheCount();
  2874. uint rootObjectStoreInlineCacheStart = rootObjectLoadMethodInlineCacheStart + funcInfo->GetRootObjectLoadMethodInlineCacheCount();
  2875. uint totalFieldAccessInlineCacheCount = rootObjectStoreInlineCacheStart + funcInfo->GetRootObjectStoreInlineCacheCount();
  2876. functionBody->CreateCacheIdToPropertyIdMap(rootObjectLoadInlineCacheStart, rootObjectLoadMethodInlineCacheStart,
  2877. rootObjectStoreInlineCacheStart, totalFieldAccessInlineCacheCount, funcInfo->GetIsInstInlineCacheCount());
  2878. if (totalFieldAccessInlineCacheCount == 0)
  2879. {
  2880. return;
  2881. }
  2882. funcInfo->inlineCacheMap->Map([functionBody](Js::RegSlot regSlot, FuncInfo::InlineCacheIdMap *inlineCacheIdMap)
  2883. {
  2884. inlineCacheIdMap->Map([functionBody](Js::PropertyId propertyId, FuncInfo::InlineCacheList* inlineCacheList)
  2885. {
  2886. if (inlineCacheList)
  2887. {
  2888. inlineCacheList->Iterate([functionBody, propertyId](InlineCacheUnit cacheUnit)
  2889. {
  2890. CompileAssert(offsetof(InlineCacheUnit, cacheId) == offsetof(InlineCacheUnit, loadCacheId));
  2891. if (cacheUnit.loadCacheId != -1)
  2892. {
  2893. functionBody->SetPropertyIdForCacheId(cacheUnit.loadCacheId, propertyId);
  2894. }
  2895. if (cacheUnit.loadMethodCacheId != -1)
  2896. {
  2897. functionBody->SetPropertyIdForCacheId(cacheUnit.loadMethodCacheId, propertyId);
  2898. }
  2899. if (cacheUnit.storeCacheId != -1)
  2900. {
  2901. functionBody->SetPropertyIdForCacheId(cacheUnit.storeCacheId, propertyId);
  2902. }
  2903. });
  2904. }
  2905. });
  2906. });
  2907. funcInfo->rootObjectLoadInlineCacheMap->Map([functionBody, rootObjectLoadInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  2908. {
  2909. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectLoadInlineCacheStart, propertyId);
  2910. });
  2911. funcInfo->rootObjectLoadMethodInlineCacheMap->Map([functionBody, rootObjectLoadMethodInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  2912. {
  2913. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectLoadMethodInlineCacheStart, propertyId);
  2914. });
  2915. funcInfo->rootObjectStoreInlineCacheMap->Map([functionBody, rootObjectStoreInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  2916. {
  2917. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectStoreInlineCacheStart, propertyId);
  2918. });
  2919. SListBase<uint>::Iterator valueOfIter(&funcInfo->valueOfStoreCacheIds);
  2920. while (valueOfIter.Next())
  2921. {
  2922. functionBody->SetPropertyIdForCacheId(valueOfIter.Data(), Js::PropertyIds::valueOf);
  2923. }
  2924. SListBase<uint>::Iterator toStringIter(&funcInfo->toStringStoreCacheIds);
  2925. while (toStringIter.Next())
  2926. {
  2927. functionBody->SetPropertyIdForCacheId(toStringIter.Data(), Js::PropertyIds::toString);
  2928. }
  2929. #if DBG
  2930. functionBody->VerifyCacheIdToPropertyIdMap();
  2931. #endif
  2932. }
  2933. void ByteCodeGenerator::MapReferencedPropertyIds(FuncInfo * funcInfo)
  2934. {
  2935. Js::FunctionBody *functionBody = funcInfo->GetParsedFunctionBody();
  2936. uint referencedPropertyIdCount = funcInfo->GetReferencedPropertyIdCount();
  2937. functionBody->CreateReferencedPropertyIdMap(referencedPropertyIdCount);
  2938. funcInfo->referencedPropertyIdToMapIndex->Map([functionBody](Js::PropertyId propertyId, uint mapIndex)
  2939. {
  2940. functionBody->SetReferencedPropertyIdWithMapIndex(mapIndex, propertyId);
  2941. });
  2942. #if DBG
  2943. functionBody->VerifyReferencedPropertyIdMap();
  2944. #endif
  2945. }
  2946. void ByteCodeGenerator::EmitScopeList(ParseNode *pnode, ParseNode *breakOnBodyScopeNode)
  2947. {
  2948. while (pnode)
  2949. {
  2950. if (breakOnBodyScopeNode != nullptr && breakOnBodyScopeNode == pnode)
  2951. {
  2952. break;
  2953. }
  2954. switch (pnode->nop)
  2955. {
  2956. case knopFncDecl:
  2957. #ifdef ASMJS_PLAT
  2958. if (pnode->AsParseNodeFnc()->GetAsmjsMode())
  2959. {
  2960. Js::ExclusiveContext context(this, GetScriptContext());
  2961. if (Js::AsmJSCompiler::Compile(&context, pnode->AsParseNodeFnc(), pnode->AsParseNodeFnc()->pnodeParams))
  2962. {
  2963. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  2964. break;
  2965. }
  2966. else if (CONFIG_FLAG(AsmJsStopOnError))
  2967. {
  2968. exit(JSERR_AsmJsCompileError);
  2969. }
  2970. else
  2971. {
  2972. // If deferral is not allowed, throw and reparse everything with asm.js disabled.
  2973. throw Js::AsmJsParseException();
  2974. }
  2975. }
  2976. #endif
  2977. // FALLTHROUGH
  2978. case knopProg:
  2979. if (pnode->AsParseNodeFnc()->funcInfo)
  2980. {
  2981. FuncInfo* funcInfo = pnode->AsParseNodeFnc()->funcInfo;
  2982. Scope* paramScope = funcInfo->GetParamScope();
  2983. if (!funcInfo->IsBodyAndParamScopeMerged())
  2984. {
  2985. funcInfo->SetCurrentChildScope(paramScope);
  2986. }
  2987. else
  2988. {
  2989. funcInfo->SetCurrentChildScope(funcInfo->GetBodyScope());
  2990. }
  2991. this->StartEmitFunction(pnode->AsParseNodeFnc());
  2992. PushFuncInfo(_u("StartEmitFunction"), funcInfo);
  2993. if (!funcInfo->IsBodyAndParamScopeMerged())
  2994. {
  2995. this->EmitScopeList(pnode->AsParseNodeFnc()->pnodeBodyScope->pnodeScopes);
  2996. }
  2997. else
  2998. {
  2999. this->EmitScopeList(pnode->AsParseNodeFnc()->pnodeScopes);
  3000. }
  3001. this->EmitOneFunction(pnode->AsParseNodeFnc());
  3002. this->EndEmitFunction(pnode->AsParseNodeFnc());
  3003. Assert(pnode->AsParseNodeFnc()->pnodeBody == nullptr || funcInfo->isReused || funcInfo->GetCurrentChildScope() == funcInfo->GetBodyScope());
  3004. funcInfo->SetCurrentChildScope(nullptr);
  3005. }
  3006. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  3007. break;
  3008. case knopBlock:
  3009. {
  3010. ParseNodeBlock * pnodeBlock = pnode->AsParseNodeBlock();
  3011. this->StartEmitBlock(pnodeBlock);
  3012. this->EmitScopeList(pnodeBlock->pnodeScopes);
  3013. this->EndEmitBlock(pnodeBlock);
  3014. pnode = pnodeBlock->pnodeNext;
  3015. break;
  3016. }
  3017. case knopCatch:
  3018. {
  3019. ParseNodeCatch * pnodeCatch = pnode->AsParseNodeCatch();
  3020. this->StartEmitCatch(pnodeCatch);
  3021. this->EmitScopeList(pnodeCatch->pnodeScopes);
  3022. this->EndEmitCatch(pnodeCatch);
  3023. pnode = pnodeCatch->pnodeNext;
  3024. break;
  3025. }
  3026. case knopWith:
  3027. this->StartEmitWith(pnode);
  3028. this->EmitScopeList(pnode->AsParseNodeWith()->pnodeScopes);
  3029. this->EndEmitWith(pnode);
  3030. pnode = pnode->AsParseNodeWith()->pnodeNext;
  3031. break;
  3032. default:
  3033. AssertMsg(false, "Unexpected opcode in tree of scopes");
  3034. break;
  3035. }
  3036. }
  3037. }
  3038. void ByteCodeGenerator::EnsureFncDeclScopeSlot(ParseNodeFnc *pnodeFnc, FuncInfo *funcInfo)
  3039. {
  3040. if (pnodeFnc->pnodeName)
  3041. {
  3042. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  3043. Symbol *sym = pnodeFnc->pnodeName->sym;
  3044. // If this function is shadowing the arguments symbol in body then skip it.
  3045. // We will allocate scope slot for the arguments symbol during EmitLocalPropInit.
  3046. if (sym && !sym->IsArguments())
  3047. {
  3048. sym->EnsureScopeSlot(this, funcInfo);
  3049. }
  3050. }
  3051. }
  3052. // Similar to EnsureFncScopeSlot visitor function, but verifies that a slot is needed before assigning it.
  3053. void ByteCodeGenerator::CheckFncDeclScopeSlot(ParseNodeFnc *pnodeFnc, FuncInfo *funcInfo)
  3054. {
  3055. if (pnodeFnc->pnodeName)
  3056. {
  3057. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  3058. Symbol *sym = pnodeFnc->pnodeName->sym;
  3059. if (sym && sym->NeedsSlotAlloc(this, funcInfo))
  3060. {
  3061. sym->EnsureScopeSlot(this, funcInfo);
  3062. }
  3063. }
  3064. }
  3065. void ByteCodeGenerator::StartEmitFunction(ParseNodeFnc *pnodeFnc)
  3066. {
  3067. Assert(pnodeFnc->nop == knopFncDecl || pnodeFnc->nop == knopProg);
  3068. FuncInfo *funcInfo = pnodeFnc->funcInfo;
  3069. Scope * const bodyScope = funcInfo->GetBodyScope();
  3070. Scope * const paramScope = funcInfo->GetParamScope();
  3071. if (funcInfo->byteCodeFunction->IsFunctionParsed() && funcInfo->root->pnodeBody != nullptr)
  3072. {
  3073. if (funcInfo->GetParsedFunctionBody()->GetByteCode() == nullptr && !(flags & (fscrEval | fscrImplicitThis)))
  3074. {
  3075. // Only set the environment depth if it's truly known (i.e., not in eval or event handler).
  3076. funcInfo->GetParsedFunctionBody()->SetEnvDepth(this->envDepth);
  3077. }
  3078. if (funcInfo->GetCallsEval())
  3079. {
  3080. funcInfo->byteCodeFunction->SetDontInline(true);
  3081. }
  3082. Scope * const funcExprScope = funcInfo->funcExprScope;
  3083. if (funcExprScope)
  3084. {
  3085. if (funcInfo->GetCallsEval())
  3086. {
  3087. Assert(funcExprScope->GetIsObject());
  3088. }
  3089. if (funcExprScope->GetIsObject())
  3090. {
  3091. funcExprScope->SetCapturesAll(true);
  3092. funcExprScope->SetMustInstantiate(true);
  3093. PushScope(funcExprScope);
  3094. }
  3095. else
  3096. {
  3097. Symbol *sym = funcInfo->root->GetFuncSymbol();
  3098. if (funcInfo->IsBodyAndParamScopeMerged())
  3099. {
  3100. funcInfo->bodyScope->AddSymbol(sym);
  3101. }
  3102. else
  3103. {
  3104. funcInfo->paramScope->AddSymbol(sym);
  3105. }
  3106. sym->EnsureScopeSlot(this, funcInfo);
  3107. if (sym->GetHasNonLocalReference())
  3108. {
  3109. sym->GetScope()->SetHasOwnLocalInClosure(true);
  3110. }
  3111. }
  3112. }
  3113. if (pnodeFnc->nop != knopProg)
  3114. {
  3115. if (!bodyScope->GetIsObject() && NeedObjectAsFunctionScope(funcInfo, pnodeFnc))
  3116. {
  3117. Assert(bodyScope->GetIsObject());
  3118. }
  3119. if (bodyScope->GetIsObject())
  3120. {
  3121. bodyScope->SetLocation(funcInfo->frameObjRegister);
  3122. }
  3123. else
  3124. {
  3125. bodyScope->SetLocation(funcInfo->frameSlotsRegister);
  3126. }
  3127. if (!funcInfo->IsBodyAndParamScopeMerged())
  3128. {
  3129. if (paramScope->GetIsObject())
  3130. {
  3131. paramScope->SetLocation(funcInfo->frameObjRegister);
  3132. }
  3133. else
  3134. {
  3135. paramScope->SetLocation(funcInfo->frameSlotsRegister);
  3136. }
  3137. }
  3138. if (bodyScope->GetIsObject())
  3139. {
  3140. // Win8 908700: Disable under F12 debugger because there are too many cached scopes holding onto locals.
  3141. funcInfo->SetHasCachedScope(
  3142. !PHASE_OFF(Js::CachedScopePhase, funcInfo->byteCodeFunction) &&
  3143. !funcInfo->Escapes() &&
  3144. funcInfo->frameObjRegister != Js::Constants::NoRegister &&
  3145. !ApplyEnclosesArgs(pnodeFnc, this) &&
  3146. funcInfo->IsBodyAndParamScopeMerged() && // There is eval in the param scope
  3147. !pnodeFnc->HasDefaultArguments() &&
  3148. !pnodeFnc->HasDestructuredParams() &&
  3149. (PHASE_FORCE(Js::CachedScopePhase, funcInfo->byteCodeFunction) || !IsInDebugMode())
  3150. #if ENABLE_TTD
  3151. && !funcInfo->GetParsedFunctionBody()->GetScriptContext()->GetThreadContext()->IsRuntimeInTTDMode()
  3152. #endif
  3153. );
  3154. if (funcInfo->GetHasCachedScope())
  3155. {
  3156. Assert(funcInfo->funcObjRegister == Js::Constants::NoRegister);
  3157. Symbol *funcSym = funcInfo->root->GetFuncSymbol();
  3158. if (funcSym && funcSym->GetIsFuncExpr())
  3159. {
  3160. if (funcSym->GetLocation() == Js::Constants::NoRegister)
  3161. {
  3162. funcInfo->funcObjRegister = funcInfo->NextVarRegister();
  3163. }
  3164. else
  3165. {
  3166. funcInfo->funcObjRegister = funcSym->GetLocation();
  3167. }
  3168. }
  3169. else
  3170. {
  3171. funcInfo->funcObjRegister = funcInfo->NextVarRegister();
  3172. }
  3173. Assert(funcInfo->funcObjRegister != Js::Constants::NoRegister);
  3174. }
  3175. ParseNode *pnode;
  3176. Symbol *sym;
  3177. if (funcInfo->GetHasArguments())
  3178. {
  3179. // Process function's formal parameters
  3180. MapFormals(pnodeFnc, [&](ParseNode *pnode)
  3181. {
  3182. if (pnode->IsVarLetOrConst())
  3183. {
  3184. pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo);
  3185. }
  3186. });
  3187. MapFormalsFromPattern(pnodeFnc, [&](ParseNode *pnode) { pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo); });
  3188. // Only allocate scope slot for "arguments" when really necessary. "hasDeferredChild"
  3189. // doesn't require scope slot for "arguments" because inner functions can't access
  3190. // outer function's arguments directly.
  3191. sym = funcInfo->GetArgumentsSymbol();
  3192. Assert(sym);
  3193. if (sym->NeedsSlotAlloc(this, funcInfo))
  3194. {
  3195. sym->EnsureScopeSlot(this, funcInfo);
  3196. }
  3197. }
  3198. sym = funcInfo->root->GetFuncSymbol();
  3199. if (sym && sym->NeedsSlotAlloc(this, funcInfo))
  3200. {
  3201. if (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject())
  3202. {
  3203. sym->SetScopeSlot(0);
  3204. }
  3205. else if (funcInfo->GetFuncExprNameReference())
  3206. {
  3207. sym->EnsureScopeSlot(this, funcInfo);
  3208. }
  3209. }
  3210. if (!funcInfo->GetHasArguments())
  3211. {
  3212. Symbol *formal;
  3213. Js::ArgSlot pos = 1;
  3214. auto moveArgToReg = [&](ParseNode *pnode)
  3215. {
  3216. if (pnode->IsVarLetOrConst())
  3217. {
  3218. formal = pnode->AsParseNodeVar()->sym;
  3219. // Get the param from its argument position into its assigned register.
  3220. // The position should match the location; otherwise, it has been shadowed by parameter with the same name.
  3221. if (formal->GetLocation() + 1 == pos)
  3222. {
  3223. pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo);
  3224. }
  3225. }
  3226. pos++;
  3227. };
  3228. MapFormals(pnodeFnc, moveArgToReg);
  3229. MapFormalsFromPattern(pnodeFnc, [&](ParseNode *pnode) { pnode->AsParseNodeVar()->sym->EnsureScopeSlot(this, funcInfo); });
  3230. }
  3231. for (pnode = pnodeFnc->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  3232. {
  3233. sym = pnode->AsParseNodeVar()->sym;
  3234. if (!(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  3235. {
  3236. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  3237. {
  3238. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  3239. }
  3240. if (sym->GetSymbolType() == STVariable && !sym->IsArguments())
  3241. {
  3242. sym->EnsureScopeSlot(this, funcInfo);
  3243. }
  3244. }
  3245. }
  3246. auto ensureFncDeclScopeSlots = [&](ParseNode *pnodeScope)
  3247. {
  3248. for (pnode = pnodeScope; pnode;)
  3249. {
  3250. switch (pnode->nop)
  3251. {
  3252. case knopFncDecl:
  3253. if (pnode->AsParseNodeFnc()->IsDeclaration())
  3254. {
  3255. EnsureFncDeclScopeSlot(pnode->AsParseNodeFnc(), funcInfo);
  3256. }
  3257. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  3258. break;
  3259. case knopBlock:
  3260. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  3261. break;
  3262. case knopCatch:
  3263. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  3264. break;
  3265. case knopWith:
  3266. pnode = pnode->AsParseNodeWith()->pnodeNext;
  3267. break;
  3268. }
  3269. }
  3270. };
  3271. pnodeFnc->MapContainerScopes(ensureFncDeclScopeSlots);
  3272. if (pnodeFnc->pnodeBody)
  3273. {
  3274. Assert(pnodeFnc->pnodeScopes->nop == knopBlock);
  3275. this->EnsureLetConstScopeSlots(pnodeFnc->pnodeBodyScope, funcInfo);
  3276. }
  3277. }
  3278. else
  3279. {
  3280. ParseNode *pnode;
  3281. Symbol *sym;
  3282. pnodeFnc->MapContainerScopes([&](ParseNode *pnodeScope) { this->EnsureFncScopeSlots(pnodeScope, funcInfo); });
  3283. for (pnode = pnodeFnc->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  3284. {
  3285. sym = pnode->AsParseNodeVar()->sym;
  3286. if (!(pnode->AsParseNodeVar()->isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  3287. {
  3288. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  3289. {
  3290. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  3291. }
  3292. if (sym->GetSymbolType() == STVariable && sym->NeedsSlotAlloc(this, funcInfo) && !sym->IsArguments())
  3293. {
  3294. sym->EnsureScopeSlot(this, funcInfo);
  3295. }
  3296. }
  3297. }
  3298. auto ensureScopeSlot = [&](ParseNode *pnode)
  3299. {
  3300. if (pnode->IsVarLetOrConst())
  3301. {
  3302. sym = pnode->AsParseNodeVar()->sym;
  3303. if (sym->GetSymbolType() == STFormal && sym->NeedsSlotAlloc(this, funcInfo))
  3304. {
  3305. sym->EnsureScopeSlot(this, funcInfo);
  3306. }
  3307. }
  3308. };
  3309. // Process function's formal parameters
  3310. MapFormals(pnodeFnc, ensureScopeSlot);
  3311. MapFormalsFromPattern(pnodeFnc, ensureScopeSlot);
  3312. if (funcInfo->GetHasArguments())
  3313. {
  3314. sym = funcInfo->GetArgumentsSymbol();
  3315. Assert(sym);
  3316. // There is no eval so the arguments may be captured in a lambda.
  3317. // But we cannot relay on slots getting allocated while the lambda is emitted as the function body may be reparsed.
  3318. sym->EnsureScopeSlot(this, funcInfo);
  3319. }
  3320. if (pnodeFnc->pnodeBody)
  3321. {
  3322. this->EnsureLetConstScopeSlots(pnodeFnc->pnodeScopes, funcInfo);
  3323. this->EnsureLetConstScopeSlots(pnodeFnc->pnodeBodyScope, funcInfo);
  3324. }
  3325. }
  3326. // When we have split scope and body scope does not have any scope slots allocated, we don't have to mark the body scope as mustinstantiate.
  3327. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  3328. {
  3329. bodyScope->SetMustInstantiate(true);
  3330. }
  3331. else if (pnodeFnc->IsBodyAndParamScopeMerged() || bodyScope->GetScopeSlotCount() != 0)
  3332. {
  3333. bodyScope->SetMustInstantiate(funcInfo->frameSlotsRegister != Js::Constants::NoRegister);
  3334. }
  3335. if (!pnodeFnc->IsBodyAndParamScopeMerged())
  3336. {
  3337. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  3338. {
  3339. paramScope->SetMustInstantiate(true);
  3340. }
  3341. else
  3342. {
  3343. // In the case of function expression being captured in the param scope the hasownlocalinclosure will be false for param scope,
  3344. // as function expression symbol stays in the function expression scope. We don't have to set mustinstantiate for param scope in that case.
  3345. paramScope->SetMustInstantiate(paramScope->GetHasOwnLocalInClosure());
  3346. }
  3347. }
  3348. }
  3349. else
  3350. {
  3351. bool newScopeForEval = (funcInfo->byteCodeFunction->GetIsStrictMode() && (this->GetFlags() & fscrEval));
  3352. if (newScopeForEval)
  3353. {
  3354. Assert(bodyScope->GetIsObject());
  3355. }
  3356. }
  3357. }
  3358. if (!funcInfo->IsBodyAndParamScopeMerged())
  3359. {
  3360. ParseNodeBlock * paramBlock = pnodeFnc->pnodeScopes;
  3361. Assert(paramBlock->blockType == Parameter);
  3362. PushScope(paramScope);
  3363. // While emitting the functions we have to stop when we see the body scope block.
  3364. // Otherwise functions defined in the body scope will not be able to get the right references.
  3365. this->EmitScopeList(paramBlock->pnodeScopes, pnodeFnc->pnodeBodyScope);
  3366. Assert(this->GetCurrentScope() == paramScope);
  3367. }
  3368. PushScope(bodyScope);
  3369. }
  3370. void ByteCodeGenerator::EmitModuleExportAccess(Symbol* sym, Js::OpCode opcode, Js::RegSlot location, FuncInfo* funcInfo)
  3371. {
  3372. if (EnsureSymbolModuleSlots(sym, funcInfo))
  3373. {
  3374. this->Writer()->SlotI2(opcode, location, sym->GetModuleIndex(), sym->GetScopeSlot());
  3375. }
  3376. else
  3377. {
  3378. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(ERRInvalidExportName));
  3379. if (opcode == Js::OpCode::LdModuleSlot)
  3380. {
  3381. this->Writer()->Reg1(Js::OpCode::LdUndef, location);
  3382. }
  3383. }
  3384. }
  3385. bool ByteCodeGenerator::EnsureSymbolModuleSlots(Symbol* sym, FuncInfo* funcInfo)
  3386. {
  3387. Assert(sym->GetIsModuleExportStorage());
  3388. if (sym->GetModuleIndex() != Js::Constants::NoProperty && sym->GetScopeSlot() != Js::Constants::NoProperty)
  3389. {
  3390. return true;
  3391. }
  3392. Js::JavascriptLibrary* library = this->GetScriptContext()->GetLibrary();
  3393. library->EnsureModuleRecordList();
  3394. uint moduleIndex = this->GetModuleID();
  3395. uint moduleSlotIndex;
  3396. Js::SourceTextModuleRecord* moduleRecord = library->GetModuleRecord(moduleIndex);
  3397. if (sym->GetIsModuleImport())
  3398. {
  3399. Js::PropertyId localImportNameId = sym->EnsurePosition(funcInfo);
  3400. Js::ModuleNameRecord* moduleNameRecord = nullptr;
  3401. if (!moduleRecord->ResolveImport(localImportNameId, &moduleNameRecord))
  3402. {
  3403. return false;
  3404. }
  3405. AnalysisAssert(moduleNameRecord != nullptr);
  3406. Assert(moduleNameRecord->module->IsSourceTextModuleRecord());
  3407. Js::SourceTextModuleRecord* resolvedModuleRecord =
  3408. (Js::SourceTextModuleRecord*)PointerValue(moduleNameRecord->module);
  3409. moduleIndex = resolvedModuleRecord->GetModuleId();
  3410. moduleSlotIndex = resolvedModuleRecord->GetLocalExportSlotIndexByLocalName(moduleNameRecord->bindingName);
  3411. }
  3412. else
  3413. {
  3414. Js::PropertyId exportNameId = sym->EnsurePosition(funcInfo);
  3415. moduleSlotIndex = moduleRecord->GetLocalExportSlotIndexByLocalName(exportNameId);
  3416. }
  3417. sym->SetModuleIndex(moduleIndex);
  3418. sym->SetScopeSlot(moduleSlotIndex);
  3419. return true;
  3420. }
  3421. void ByteCodeGenerator::EmitAssignmentToDefaultModuleExport(ParseNode* pnode, FuncInfo* funcInfo)
  3422. {
  3423. // We are assigning pnode to the default export of the current module.
  3424. uint moduleIndex = this->GetModuleID();
  3425. Js::JavascriptLibrary* library = this->GetScriptContext()->GetLibrary();
  3426. library->EnsureModuleRecordList();
  3427. Js::SourceTextModuleRecord* moduleRecord = library->GetModuleRecord(moduleIndex);
  3428. uint moduleSlotIndex = moduleRecord->GetLocalExportSlotIndexByExportName(Js::PropertyIds::default_);
  3429. this->Writer()->SlotI2(Js::OpCode::StModuleSlot, pnode->location, moduleIndex, moduleSlotIndex);
  3430. }
  3431. void ByteCodeGenerator::EnsureLetConstScopeSlots(ParseNodeBlock *pnodeBlock, FuncInfo *funcInfo)
  3432. {
  3433. bool callsEval = pnodeBlock->GetCallsEval() || pnodeBlock->GetChildCallsEval();
  3434. auto ensureLetConstSlots = ([this, funcInfo, callsEval](ParseNode *pnode)
  3435. {
  3436. Symbol *sym = pnode->AsParseNodeVar()->sym;
  3437. if (callsEval || sym->NeedsSlotAlloc(this, funcInfo))
  3438. {
  3439. sym->EnsureScopeSlot(this, funcInfo);
  3440. this->ProcessCapturedSym(sym);
  3441. }
  3442. });
  3443. IterateBlockScopedVariables(pnodeBlock, ensureLetConstSlots);
  3444. }
  3445. void ByteCodeGenerator::EnsureFncScopeSlots(ParseNode *pnode, FuncInfo *funcInfo)
  3446. {
  3447. while (pnode)
  3448. {
  3449. switch (pnode->nop)
  3450. {
  3451. case knopFncDecl:
  3452. if (pnode->AsParseNodeFnc()->IsDeclaration())
  3453. {
  3454. this->CheckFncDeclScopeSlot(pnode->AsParseNodeFnc(), funcInfo);
  3455. }
  3456. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  3457. break;
  3458. case knopBlock:
  3459. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  3460. break;
  3461. case knopCatch:
  3462. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  3463. break;
  3464. case knopWith:
  3465. pnode = pnode->AsParseNodeWith()->pnodeNext;
  3466. break;
  3467. }
  3468. }
  3469. }
  3470. void ByteCodeGenerator::EndEmitFunction(ParseNodeFnc *pnodeFnc)
  3471. {
  3472. Assert(pnodeFnc->nop == knopFncDecl || pnodeFnc->nop == knopProg);
  3473. Assert(pnodeFnc->nop == knopFncDecl && currentScope->GetEnclosingScope() != nullptr || pnodeFnc->nop == knopProg);
  3474. PopScope(); // function body
  3475. FuncInfo *funcInfo = pnodeFnc->funcInfo;
  3476. Scope* paramScope = funcInfo->paramScope;
  3477. if (!funcInfo->IsBodyAndParamScopeMerged())
  3478. {
  3479. Assert(this->GetCurrentScope() == paramScope);
  3480. PopScope(); // Pop the param scope
  3481. }
  3482. if (funcInfo->byteCodeFunction->IsFunctionParsed() && funcInfo->root->pnodeBody != nullptr)
  3483. {
  3484. // StartEmitFunction omits the matching PushScope for already-parsed functions.
  3485. // TODO: Refactor Start and EndEmitFunction for clarity.
  3486. Scope *scope = funcInfo->funcExprScope;
  3487. if (scope && scope->GetMustInstantiate())
  3488. {
  3489. Assert(currentScope == scope);
  3490. PopScope();
  3491. }
  3492. }
  3493. Assert(funcInfo == this->TopFuncInfo());
  3494. PopFuncInfo(_u("EndEmitFunction"));
  3495. }
  3496. void ByteCodeGenerator::StartEmitCatch(ParseNodeCatch *pnodeCatch)
  3497. {
  3498. Assert(pnodeCatch->nop == knopCatch);
  3499. Scope *scope = pnodeCatch->scope;
  3500. FuncInfo *funcInfo = scope->GetFunc();
  3501. // 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).
  3502. if (funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval() || (this->flags & (fscrEval | fscrImplicitThis)))
  3503. {
  3504. scope->SetIsObject();
  3505. }
  3506. ParseNode * pnodeParam = pnodeCatch->GetParam();
  3507. if (pnodeParam->nop == knopParamPattern)
  3508. {
  3509. scope->SetCapturesAll(funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval());
  3510. scope->SetMustInstantiate(scope->Count() > 0 && (scope->GetMustInstantiate() || scope->GetCapturesAll() || funcInfo->IsGlobalFunction()));
  3511. Parser::MapBindIdentifier(pnodeParam->AsParseNodeParamPattern()->pnode1, [&](ParseNodePtr item)
  3512. {
  3513. Symbol *sym = item->AsParseNodeVar()->sym;
  3514. if (funcInfo->IsGlobalFunction())
  3515. {
  3516. sym->SetIsGlobalCatch(true);
  3517. }
  3518. Assert(sym->GetScopeSlot() == Js::Constants::NoProperty);
  3519. if (sym->NeedsSlotAlloc(this, funcInfo))
  3520. {
  3521. sym->EnsureScopeSlot(this, funcInfo);
  3522. }
  3523. });
  3524. // In the case of pattern we will always going to push the scope.
  3525. PushScope(scope);
  3526. }
  3527. else
  3528. {
  3529. Symbol *sym = pnodeParam->AsParseNodeName()->sym;
  3530. // Catch object is stored in the catch scope if there may be an ambiguous lookup or a var declaration that hides it.
  3531. scope->SetCapturesAll(funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval() || sym->GetHasNonLocalReference());
  3532. scope->SetMustInstantiate(scope->GetCapturesAll() || funcInfo->IsGlobalFunction());
  3533. if (funcInfo->IsGlobalFunction())
  3534. {
  3535. sym->SetIsGlobalCatch(true);
  3536. }
  3537. if (scope->GetMustInstantiate())
  3538. {
  3539. if (sym->IsInSlot(this, funcInfo))
  3540. {
  3541. // Since there is only one symbol we are pushing to slot.
  3542. // Also in order to make IsInSlot to return true - forcing the sym-has-non-local-reference.
  3543. this->ProcessCapturedSym(sym);
  3544. sym->EnsureScopeSlot(this, funcInfo);
  3545. }
  3546. }
  3547. PushScope(scope);
  3548. }
  3549. }
  3550. void ByteCodeGenerator::EndEmitCatch(ParseNodeCatch *pnodeCatch)
  3551. {
  3552. Assert(pnodeCatch->nop == knopCatch);
  3553. Assert(currentScope == pnodeCatch->scope);
  3554. PopScope();
  3555. }
  3556. void ByteCodeGenerator::StartEmitBlock(ParseNodeBlock *pnodeBlock)
  3557. {
  3558. if (!BlockHasOwnScope(pnodeBlock, this))
  3559. {
  3560. return;
  3561. }
  3562. Assert(pnodeBlock->nop == knopBlock);
  3563. PushBlock(pnodeBlock);
  3564. Scope *scope = pnodeBlock->scope;
  3565. if (pnodeBlock->GetCallsEval() || pnodeBlock->GetChildCallsEval() || (this->flags & (fscrEval | fscrImplicitThis)))
  3566. {
  3567. Assert(scope->GetIsObject());
  3568. }
  3569. // TODO: Consider nested deferred parsing.
  3570. if (scope->GetMustInstantiate())
  3571. {
  3572. FuncInfo *funcInfo = scope->GetFunc();
  3573. this->EnsureFncScopeSlots(pnodeBlock->pnodeScopes, funcInfo);
  3574. this->EnsureLetConstScopeSlots(pnodeBlock, funcInfo);
  3575. PushScope(scope);
  3576. }
  3577. }
  3578. void ByteCodeGenerator::EndEmitBlock(ParseNodeBlock *pnodeBlock)
  3579. {
  3580. if (!BlockHasOwnScope(pnodeBlock, this))
  3581. {
  3582. return;
  3583. }
  3584. Assert(pnodeBlock->nop == knopBlock);
  3585. Scope *scope = pnodeBlock->scope;
  3586. if (scope && scope->GetMustInstantiate())
  3587. {
  3588. Assert(currentScope == pnodeBlock->scope);
  3589. PopScope();
  3590. }
  3591. PopBlock();
  3592. }
  3593. void ByteCodeGenerator::StartEmitWith(ParseNode *pnodeWith)
  3594. {
  3595. Assert(pnodeWith->nop == knopWith);
  3596. Scope *scope = pnodeWith->AsParseNodeWith()->scope;
  3597. AssertOrFailFast(scope->GetIsObject());
  3598. PushScope(scope);
  3599. }
  3600. void ByteCodeGenerator::EndEmitWith(ParseNode *pnodeWith)
  3601. {
  3602. Assert(pnodeWith->nop == knopWith);
  3603. Assert(currentScope == pnodeWith->AsParseNodeWith()->scope);
  3604. PopScope();
  3605. }
  3606. Js::RegSlot ByteCodeGenerator::PrependLocalScopes(Js::RegSlot evalEnv, Js::RegSlot tempLoc, FuncInfo *funcInfo)
  3607. {
  3608. Scope *currScope = this->currentScope;
  3609. Scope *funcScope = funcInfo->GetCurrentChildScope() ? funcInfo->GetCurrentChildScope() : funcInfo->GetBodyScope();
  3610. if (currScope == funcScope)
  3611. {
  3612. return evalEnv;
  3613. }
  3614. bool acquireTempLoc = tempLoc == Js::Constants::NoRegister;
  3615. if (acquireTempLoc)
  3616. {
  3617. tempLoc = funcInfo->AcquireTmpRegister();
  3618. }
  3619. // The with/catch objects must be prepended to the environment we pass to eval() or to a func declared inside with,
  3620. // but the list must first be reversed so that innermost scopes appear first in the list.
  3621. while (currScope != funcScope)
  3622. {
  3623. Scope *innerScope;
  3624. for (innerScope = currScope; innerScope->GetEnclosingScope() != funcScope; innerScope = innerScope->GetEnclosingScope())
  3625. ;
  3626. if (innerScope->GetMustInstantiate())
  3627. {
  3628. if (!innerScope->HasInnerScopeIndex())
  3629. {
  3630. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  3631. {
  3632. this->m_writer.Reg2(Js::OpCode::LdInnerFrameDisplayNoParent, tempLoc, innerScope->GetLocation());
  3633. }
  3634. else
  3635. {
  3636. this->m_writer.Reg3(Js::OpCode::LdInnerFrameDisplay, tempLoc, innerScope->GetLocation(), evalEnv);
  3637. }
  3638. }
  3639. else
  3640. {
  3641. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  3642. {
  3643. this->m_writer.Reg1Unsigned1(Js::OpCode::LdIndexedFrameDisplayNoParent, tempLoc, innerScope->GetInnerScopeIndex());
  3644. }
  3645. else
  3646. {
  3647. this->m_writer.Reg2Int1(Js::OpCode::LdIndexedFrameDisplay, tempLoc, evalEnv, innerScope->GetInnerScopeIndex());
  3648. }
  3649. }
  3650. evalEnv = tempLoc;
  3651. }
  3652. funcScope = innerScope;
  3653. }
  3654. if (acquireTempLoc)
  3655. {
  3656. funcInfo->ReleaseTmpRegister(tempLoc);
  3657. }
  3658. return evalEnv;
  3659. }
  3660. void ByteCodeGenerator::EmitLoadInstance(Symbol *sym, IdentPtr pid, Js::RegSlot *pThisLocation, Js::RegSlot *pInstLocation, FuncInfo *funcInfo)
  3661. {
  3662. Js::ByteCodeLabel doneLabel = 0;
  3663. bool fLabelDefined = false;
  3664. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  3665. Js::RegSlot thisLocation = *pThisLocation;
  3666. Js::RegSlot instLocation = *pInstLocation;
  3667. Js::PropertyId envIndex = -1;
  3668. Scope *scope = nullptr;
  3669. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  3670. Assert(symScope);
  3671. if (sym != nullptr && sym->GetIsModuleExportStorage())
  3672. {
  3673. *pInstLocation = Js::Constants::NoRegister;
  3674. return;
  3675. }
  3676. for (;;)
  3677. {
  3678. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  3679. if (scope == this->globalScope)
  3680. {
  3681. break;
  3682. }
  3683. if (scope != symScope)
  3684. {
  3685. // We're not sure where the function is (eval/with/etc).
  3686. // So we're going to need registers to hold the instance where we (dynamically) find
  3687. // the function, and possibly to hold the "this" pointer we will pass to it.
  3688. // Assign them here so that they can't overlap with the scopeLocation assigned below.
  3689. // Otherwise we wind up with temp lifetime confusion in the IRBuilder. (Win8 281689)
  3690. if (instLocation == Js::Constants::NoRegister)
  3691. {
  3692. instLocation = funcInfo->AcquireTmpRegister();
  3693. // The "this" pointer will not be the same as the instance, so give it its own register.
  3694. thisLocation = funcInfo->AcquireTmpRegister();
  3695. }
  3696. }
  3697. if (envIndex == -1)
  3698. {
  3699. Assert(funcInfo == scope->GetFunc());
  3700. scopeLocation = scope->GetLocation();
  3701. }
  3702. if (scope == symScope)
  3703. {
  3704. break;
  3705. }
  3706. // Found a scope to which the property may have been added.
  3707. Assert(scope && scope->GetIsDynamic());
  3708. if (!fLabelDefined)
  3709. {
  3710. fLabelDefined = true;
  3711. doneLabel = this->m_writer.DefineLabel();
  3712. }
  3713. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  3714. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  3715. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  3716. if (envIndex != -1)
  3717. {
  3718. this->m_writer.BrEnvProperty(
  3719. Js::OpCode::BrOnNoEnvProperty, nextLabel,
  3720. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  3721. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  3722. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  3723. AssertOrFailFast(scope->GetIsObject());
  3724. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, tmpReg,
  3725. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  3726. Js::OpCode op = unwrapWithObj ? Js::OpCode::UnwrapWithObj : Js::OpCode::Ld_A;
  3727. this->m_writer.Reg2(op, instLocation, tmpReg);
  3728. if (thisLocation != Js::Constants::NoRegister)
  3729. {
  3730. this->m_writer.Reg2(op, thisLocation, tmpReg);
  3731. }
  3732. funcInfo->ReleaseTmpRegister(tmpReg);
  3733. }
  3734. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  3735. {
  3736. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  3737. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  3738. Assert(!unwrapWithObj);
  3739. AssertOrFailFast(scope->GetIsObject());
  3740. this->m_writer.Reg1(Js::OpCode::LdLocalObj, instLocation);
  3741. if (thisLocation != Js::Constants::NoRegister)
  3742. {
  3743. this->m_writer.Reg1(Js::OpCode::LdLocalObj, thisLocation);
  3744. }
  3745. }
  3746. else
  3747. {
  3748. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  3749. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  3750. Js::OpCode op = unwrapWithObj ? Js::OpCode::UnwrapWithObj : Js::OpCode::Ld_A;
  3751. this->m_writer.Reg2(op, instLocation, scopeLocation);
  3752. if (thisLocation != Js::Constants::NoRegister)
  3753. {
  3754. this->m_writer.Reg2(op, thisLocation, scopeLocation);
  3755. }
  3756. }
  3757. this->m_writer.Br(doneLabel);
  3758. this->m_writer.MarkLabel(nextLabel);
  3759. }
  3760. if (sym == nullptr || sym->GetIsGlobal())
  3761. {
  3762. if (this->flags & (fscrEval | fscrImplicitThis))
  3763. {
  3764. // Load of a symbol with unknown scope from within eval.
  3765. // Get it from the closure environment.
  3766. if (instLocation == Js::Constants::NoRegister)
  3767. {
  3768. instLocation = funcInfo->AcquireTmpRegister();
  3769. }
  3770. // TODO: It should be possible to avoid this double call to ScopedLdInst by having it return both
  3771. // results at once. The reason for the uncertainty here is that we don't know whether the callee
  3772. // belongs to a "with" object. If it does, we have to pass the "with" object as "this"; in all other
  3773. // cases, we pass "undefined". For now, there are apparently no significant performance issues.
  3774. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  3775. if (thisLocation == Js::Constants::NoRegister)
  3776. {
  3777. thisLocation = funcInfo->AcquireTmpRegister();
  3778. }
  3779. this->m_writer.ScopedProperty2(Js::OpCode::ScopedLdInst, instLocation,
  3780. funcInfo->FindOrAddReferencedPropertyId(propertyId), thisLocation);
  3781. }
  3782. else
  3783. {
  3784. if (instLocation == Js::Constants::NoRegister)
  3785. {
  3786. instLocation = ByteCodeGenerator::RootObjectRegister;
  3787. }
  3788. else
  3789. {
  3790. this->m_writer.Reg2(Js::OpCode::Ld_A, instLocation, ByteCodeGenerator::RootObjectRegister);
  3791. }
  3792. if (thisLocation == Js::Constants::NoRegister)
  3793. {
  3794. thisLocation = funcInfo->undefinedConstantRegister;
  3795. }
  3796. else
  3797. {
  3798. this->m_writer.Reg2(Js::OpCode::Ld_A, thisLocation, funcInfo->undefinedConstantRegister);
  3799. }
  3800. }
  3801. }
  3802. else if (instLocation != Js::Constants::NoRegister)
  3803. {
  3804. if (envIndex != -1)
  3805. {
  3806. AssertOrFailFast(scope->GetIsObject());
  3807. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation,
  3808. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  3809. }
  3810. else if (scope->HasInnerScopeIndex())
  3811. {
  3812. this->m_writer.Reg1Unsigned1(Js::OpCode::LdInnerScope, instLocation, scope->GetInnerScopeIndex());
  3813. }
  3814. else if (symScope == funcInfo->GetParamScope())
  3815. {
  3816. Assert(funcInfo->frameObjRegister != Js::Constants::NoRegister && !funcInfo->IsBodyAndParamScopeMerged());
  3817. this->m_writer.Reg1(Js::OpCode::LdParamObj, instLocation);
  3818. }
  3819. else if (symScope != funcInfo->GetBodyScope())
  3820. {
  3821. this->m_writer.Reg2(Js::OpCode::Ld_A, instLocation, scopeLocation);
  3822. }
  3823. else
  3824. {
  3825. Assert(funcInfo->frameObjRegister != Js::Constants::NoRegister);
  3826. this->m_writer.Reg1(Js::OpCode::LdLocalObj, instLocation);
  3827. }
  3828. if (thisLocation != Js::Constants::NoRegister)
  3829. {
  3830. this->m_writer.Reg2(Js::OpCode::Ld_A, thisLocation, funcInfo->undefinedConstantRegister);
  3831. }
  3832. else
  3833. {
  3834. thisLocation = funcInfo->undefinedConstantRegister;
  3835. }
  3836. }
  3837. *pThisLocation = thisLocation;
  3838. *pInstLocation = instLocation;
  3839. if (fLabelDefined)
  3840. {
  3841. this->m_writer.MarkLabel(doneLabel);
  3842. }
  3843. }
  3844. void ByteCodeGenerator::EmitGlobalFncDeclInit(Js::RegSlot rhsLocation, Js::PropertyId propertyId, FuncInfo * funcInfo)
  3845. {
  3846. // Note: declared variables and assignments in the global function go to the root object directly.
  3847. if (this->flags & fscrEval)
  3848. {
  3849. // Func decl's always get their init values before any use, so we don't pre-initialize the property to undef.
  3850. // That means that we have to use ScopedInitFld so that we initialize the property on the right instance
  3851. // even if the instance doesn't have the property yet (i.e., collapse the init-to-undef and the store
  3852. // into one operation). See WOOB 1121763 and 1120973.
  3853. this->m_writer.ScopedProperty(Js::OpCode::ScopedInitFunc, rhsLocation,
  3854. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  3855. }
  3856. else
  3857. {
  3858. this->EmitPatchableRootProperty(Js::OpCode::InitRootFld, rhsLocation, propertyId, false, true, funcInfo);
  3859. }
  3860. }
  3861. void
  3862. ByteCodeGenerator::EmitPatchableRootProperty(Js::OpCode opcode,
  3863. Js::RegSlot regSlot, Js::PropertyId propertyId, bool isLoadMethod, bool isStore, FuncInfo * funcInfo)
  3864. {
  3865. uint cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, isLoadMethod, isStore);
  3866. this->m_writer.PatchableRootProperty(opcode, regSlot, cacheId, isLoadMethod, isStore);
  3867. }
  3868. void ByteCodeGenerator::EmitLocalPropInit(Js::RegSlot rhsLocation, Symbol *sym, FuncInfo *funcInfo)
  3869. {
  3870. Scope *scope = sym->GetScope();
  3871. // Check consistency of sym->IsInSlot.
  3872. Assert(sym->NeedsSlotAlloc(this, funcInfo) || sym->GetScopeSlot() == Js::Constants::NoProperty);
  3873. // Arrived at the scope in which the property was defined.
  3874. if (sym->NeedsSlotAlloc(this, funcInfo))
  3875. {
  3876. // The property is in memory rather than register. We'll have to load it from the slots.
  3877. if (scope->GetIsObject())
  3878. {
  3879. Assert(!this->TopFuncInfo()->GetParsedFunctionBody()->DoStackNestedFunc());
  3880. Js::PropertyId propertyId = sym->EnsurePosition(this);
  3881. Js::RegSlot objReg;
  3882. if (scope->HasInnerScopeIndex())
  3883. {
  3884. objReg = funcInfo->InnerScopeToRegSlot(scope);
  3885. }
  3886. else
  3887. {
  3888. objReg = scope->GetLocation();
  3889. }
  3890. uint cacheId = funcInfo->FindOrAddInlineCacheId(objReg, propertyId, false, true);
  3891. Js::OpCode op = this->GetInitFldOp(scope, objReg, funcInfo, sym->GetIsNonSimpleParameter());
  3892. if (objReg != Js::Constants::NoRegister && objReg == funcInfo->frameObjRegister)
  3893. {
  3894. this->m_writer.ElementP(op, rhsLocation, cacheId);
  3895. }
  3896. else if (scope->HasInnerScopeIndex())
  3897. {
  3898. this->m_writer.ElementPIndexed(op, rhsLocation, scope->GetInnerScopeIndex(), cacheId);
  3899. }
  3900. else
  3901. {
  3902. this->m_writer.PatchableProperty(op, rhsLocation, scope->GetLocation(), cacheId);
  3903. }
  3904. }
  3905. else
  3906. {
  3907. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  3908. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  3909. Js::RegSlot slotReg = scope->GetCanMerge() ? funcInfo->frameSlotsRegister : scope->GetLocation();
  3910. // Now store the property to its slot.
  3911. Js::OpCode op = this->GetStSlotOp(scope, -1, slotReg, false, funcInfo);
  3912. if (slotReg != Js::Constants::NoRegister && slotReg == funcInfo->frameSlotsRegister)
  3913. {
  3914. this->m_writer.SlotI1(op, rhsLocation, slot + Js::ScopeSlots::FirstSlotIndex);
  3915. }
  3916. else
  3917. {
  3918. this->m_writer.SlotI2(op, rhsLocation, scope->GetInnerScopeIndex(), slot + Js::ScopeSlots::FirstSlotIndex);
  3919. }
  3920. }
  3921. }
  3922. if (sym->GetLocation() != Js::Constants::NoRegister && rhsLocation != sym->GetLocation())
  3923. {
  3924. this->m_writer.Reg2(Js::OpCode::Ld_A, sym->GetLocation(), rhsLocation);
  3925. }
  3926. }
  3927. Js::OpCode
  3928. ByteCodeGenerator::GetStSlotOp(Scope *scope, int envIndex, Js::RegSlot scopeLocation, bool chkBlockVar, FuncInfo *funcInfo)
  3929. {
  3930. Js::OpCode op;
  3931. if (envIndex != -1)
  3932. {
  3933. if (scope->GetIsObject())
  3934. {
  3935. op = Js::OpCode::StEnvObjSlot;
  3936. }
  3937. else
  3938. {
  3939. op = Js::OpCode::StEnvSlot;
  3940. }
  3941. }
  3942. else if (scopeLocation != Js::Constants::NoRegister &&
  3943. scopeLocation == funcInfo->frameSlotsRegister)
  3944. {
  3945. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  3946. {
  3947. // Symbol is from the param scope of a split scope function and we are emitting the body.
  3948. // We should use the param scope's bytecode now.
  3949. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  3950. op = Js::OpCode::StParamSlot;
  3951. }
  3952. else
  3953. {
  3954. op = Js::OpCode::StLocalSlot;
  3955. }
  3956. }
  3957. else if (scopeLocation != Js::Constants::NoRegister &&
  3958. scopeLocation == funcInfo->frameObjRegister)
  3959. {
  3960. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  3961. {
  3962. // Symbol is from the param scope of a split scope function and we are emitting the body.
  3963. // We should use the param scope's bytecode now.
  3964. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  3965. op = Js::OpCode::StParamObjSlot;
  3966. }
  3967. else
  3968. {
  3969. op = Js::OpCode::StLocalObjSlot;
  3970. }
  3971. }
  3972. else
  3973. {
  3974. Assert(scope->HasInnerScopeIndex());
  3975. if (scope->GetIsObject())
  3976. {
  3977. op = Js::OpCode::StInnerObjSlot;
  3978. }
  3979. else
  3980. {
  3981. op = Js::OpCode::StInnerSlot;
  3982. }
  3983. }
  3984. if (chkBlockVar)
  3985. {
  3986. op = this->ToChkUndeclOp(op);
  3987. }
  3988. return op;
  3989. }
  3990. Js::OpCode
  3991. ByteCodeGenerator::GetInitFldOp(Scope *scope, Js::RegSlot scopeLocation, FuncInfo *funcInfo, bool letDecl)
  3992. {
  3993. Js::OpCode op;
  3994. if (scopeLocation != Js::Constants::NoRegister &&
  3995. scopeLocation == funcInfo->frameObjRegister)
  3996. {
  3997. op = letDecl ? Js::OpCode::InitLocalLetFld : Js::OpCode::InitLocalFld;
  3998. }
  3999. else if (scope->HasInnerScopeIndex())
  4000. {
  4001. op = letDecl ? Js::OpCode::InitInnerLetFld : Js::OpCode::InitInnerFld;
  4002. }
  4003. else
  4004. {
  4005. op = letDecl ? Js::OpCode::InitLetFld : Js::OpCode::InitFld;
  4006. }
  4007. return op;
  4008. }
  4009. void ByteCodeGenerator::EmitPropStore(Js::RegSlot rhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool isLetDecl, bool isConstDecl, bool isFncDeclVar, bool skipUseBeforeDeclarationCheck)
  4010. {
  4011. Js::ByteCodeLabel doneLabel = 0;
  4012. bool fLabelDefined = false;
  4013. Js::PropertyId envIndex = -1;
  4014. Scope *symScope = sym == nullptr || sym->GetIsGlobal() ? this->globalScope : sym->GetScope();
  4015. Assert(symScope);
  4016. // isFncDeclVar denotes that the symbol being stored to here is the var
  4017. // binding of a function declaration and we know we want to store directly
  4018. // to it, skipping over any dynamic scopes that may lie in between.
  4019. Scope *scope = nullptr;
  4020. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4021. bool scopeAcquired = false;
  4022. Js::OpCode op;
  4023. if (sym && sym->GetIsModuleExportStorage())
  4024. {
  4025. if (!isConstDecl && sym->GetDecl() && sym->GetDecl()->nop == knopConstDecl)
  4026. {
  4027. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4028. }
  4029. EmitModuleExportAccess(sym, Js::OpCode::StModuleSlot, rhsLocation, funcInfo);
  4030. return;
  4031. }
  4032. if (isFncDeclVar)
  4033. {
  4034. // async functions allow for the fncDeclVar to be in the body or parameter scope
  4035. // of the parent function, so we need to calculate envIndex in lieu of the while
  4036. // loop below.
  4037. do
  4038. {
  4039. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4040. } while (scope != symScope);
  4041. Assert(scope == symScope);
  4042. scopeLocation = scope->GetLocation();
  4043. }
  4044. while (!isFncDeclVar)
  4045. {
  4046. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4047. if (scope == this->globalScope)
  4048. {
  4049. break;
  4050. }
  4051. if (envIndex == -1)
  4052. {
  4053. Assert(funcInfo == scope->GetFunc());
  4054. scopeLocation = scope->GetLocation();
  4055. }
  4056. if (scope == symScope)
  4057. {
  4058. break;
  4059. }
  4060. // Found a scope to which the property may have been added.
  4061. Assert(scope && scope->GetIsDynamic());
  4062. if (!fLabelDefined)
  4063. {
  4064. fLabelDefined = true;
  4065. doneLabel = this->m_writer.DefineLabel();
  4066. }
  4067. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4068. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4069. Js::RegSlot unwrappedScopeLocation = scopeLocation;
  4070. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4071. if (envIndex != -1)
  4072. {
  4073. this->m_writer.BrEnvProperty(
  4074. Js::OpCode::BrOnNoEnvProperty,
  4075. nextLabel,
  4076. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4077. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4078. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4079. AssertOrFailFast(scope->GetIsObject());
  4080. this->m_writer.SlotI1(
  4081. Js::OpCode::LdEnvObj,
  4082. instLocation,
  4083. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4084. if (unwrapWithObj)
  4085. {
  4086. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4087. }
  4088. this->m_writer.PatchableProperty(
  4089. Js::OpCode::StFld,
  4090. rhsLocation,
  4091. instLocation,
  4092. funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, true));
  4093. funcInfo->ReleaseTmpRegister(instLocation);
  4094. }
  4095. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4096. {
  4097. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4098. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4099. Assert(!unwrapWithObj);
  4100. this->m_writer.ElementP(Js::OpCode::StLocalFld, rhsLocation,
  4101. funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true));
  4102. }
  4103. else
  4104. {
  4105. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4106. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4107. if (unwrapWithObj)
  4108. {
  4109. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4110. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4111. scopeLocation = unwrappedScopeLocation;
  4112. }
  4113. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  4114. this->m_writer.PatchableProperty(Js::OpCode::StFld, rhsLocation, scopeLocation, cacheId);
  4115. if (unwrapWithObj)
  4116. {
  4117. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4118. }
  4119. }
  4120. this->m_writer.Br(doneLabel);
  4121. this->m_writer.MarkLabel(nextLabel);
  4122. }
  4123. // Arrived at the scope in which the property was defined.
  4124. if (!skipUseBeforeDeclarationCheck && sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo)
  4125. {
  4126. EmitUseBeforeDeclarationRuntimeError(this, Js::Constants::NoRegister);
  4127. // Intentionally continue on to do normal EmitPropStore behavior so
  4128. // that the bytecode ends up well-formed for the backend. This is
  4129. // in contrast to EmitPropLoad and EmitPropTypeof where they both
  4130. // tell EmitUseBeforeDeclarationRuntimeError to emit a LdUndef in place
  4131. // of their load and then they skip emitting their own bytecode.
  4132. // Potayto potahto.
  4133. }
  4134. if (sym == nullptr || sym->GetIsGlobal())
  4135. {
  4136. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4137. bool isConsoleScopeLetConst = this->IsConsoleScopeEval() && (isLetDecl || isConstDecl);
  4138. if (this->flags & fscrEval)
  4139. {
  4140. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4141. {
  4142. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->frameDisplayRegister, propertyId, false, true);
  4143. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo, isConsoleScopeLetConst), rhsLocation, cacheId);
  4144. }
  4145. else
  4146. {
  4147. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, true);
  4148. // In "eval", store to a symbol with unknown scope goes through the closure environment.
  4149. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo, isConsoleScopeLetConst), rhsLocation, cacheId);
  4150. }
  4151. }
  4152. else if (this->flags & fscrImplicitThis)
  4153. {
  4154. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, true);
  4155. // In HTML event handler, store to a symbol with unknown scope goes through the closure environment.
  4156. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo, isConsoleScopeLetConst), rhsLocation, cacheId);
  4157. }
  4158. else
  4159. {
  4160. this->EmitPatchableRootProperty(GetStFldOpCode(funcInfo, true, isLetDecl, isConstDecl, false), rhsLocation, propertyId, false, true, funcInfo);
  4161. }
  4162. }
  4163. else if (sym->GetIsFuncExpr())
  4164. {
  4165. // Store to function expr variable.
  4166. // strict mode: we need to throw type error
  4167. if (funcInfo->byteCodeFunction->GetIsStrictMode())
  4168. {
  4169. // Note that in this case the sym's location belongs to the parent function, so we can't use it.
  4170. // It doesn't matter which register we use, as long as it's valid for this function.
  4171. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_CantAssignToReadOnly));
  4172. }
  4173. }
  4174. else if (sym->IsInSlot(this, funcInfo) || envIndex != -1)
  4175. {
  4176. if (!isConstDecl && sym->GetIsConst())
  4177. {
  4178. // This is a case where const reassignment can't be proven statically (e.g., eval, with) so
  4179. // we have to catch it at runtime.
  4180. this->m_writer.W1(
  4181. Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4182. }
  4183. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4184. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4185. bool chkBlockVar = !isLetDecl && !isConstDecl && NeedCheckBlockVar(sym, scope, funcInfo);
  4186. // The property is in memory rather than register. We'll have to load it from the slots.
  4187. op = this->GetStSlotOp(scope, envIndex, scopeLocation, chkBlockVar, funcInfo);
  4188. if (envIndex != -1)
  4189. {
  4190. this->m_writer.SlotI2(op, rhsLocation,
  4191. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var),
  4192. slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex));
  4193. }
  4194. else if (scopeLocation != Js::Constants::NoRegister &&
  4195. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4196. {
  4197. this->m_writer.SlotI1(op, rhsLocation,
  4198. slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex));
  4199. }
  4200. else
  4201. {
  4202. Assert(scope->HasInnerScopeIndex());
  4203. this->m_writer.SlotI2(op, rhsLocation, scope->GetInnerScopeIndex(),
  4204. slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex));
  4205. }
  4206. if (this->ShouldTrackDebuggerMetadata() && (isLetDecl || isConstDecl))
  4207. {
  4208. Js::PropertyId location = scope->GetIsObject() ? sym->GetLocation() : slot;
  4209. this->UpdateDebuggerPropertyInitializationOffset(location, sym->GetPosition(), false);
  4210. }
  4211. }
  4212. else if (isConstDecl)
  4213. {
  4214. this->m_writer.Reg2(Js::OpCode::InitConst, sym->GetLocation(), rhsLocation);
  4215. if (this->ShouldTrackDebuggerMetadata())
  4216. {
  4217. this->UpdateDebuggerPropertyInitializationOffset(sym->GetLocation(), sym->GetPosition());
  4218. }
  4219. }
  4220. else
  4221. {
  4222. if (!isConstDecl && sym->GetDecl() && sym->GetDecl()->nop == knopConstDecl)
  4223. {
  4224. // This is a case where const reassignment can't be proven statically (e.g., eval, with) so
  4225. // we have to catch it at runtime.
  4226. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4227. }
  4228. if (rhsLocation != sym->GetLocation())
  4229. {
  4230. this->m_writer.Reg2(Js::OpCode::Ld_A, sym->GetLocation(), rhsLocation);
  4231. if (this->ShouldTrackDebuggerMetadata() && isLetDecl)
  4232. {
  4233. this->UpdateDebuggerPropertyInitializationOffset(sym->GetLocation(), sym->GetPosition());
  4234. }
  4235. }
  4236. }
  4237. if (fLabelDefined)
  4238. {
  4239. this->m_writer.MarkLabel(doneLabel);
  4240. }
  4241. if (scopeAcquired)
  4242. {
  4243. funcInfo->ReleaseTmpRegister(scopeLocation);
  4244. }
  4245. }
  4246. Js::OpCode
  4247. ByteCodeGenerator::GetLdSlotOp(Scope *scope, int envIndex, Js::RegSlot scopeLocation, FuncInfo *funcInfo)
  4248. {
  4249. Js::OpCode op;
  4250. if (envIndex != -1)
  4251. {
  4252. if (scope->GetIsObject())
  4253. {
  4254. op = Js::OpCode::LdEnvObjSlot;
  4255. }
  4256. else
  4257. {
  4258. op = Js::OpCode::LdEnvSlot;
  4259. }
  4260. }
  4261. else if (scopeLocation != Js::Constants::NoRegister &&
  4262. scopeLocation == funcInfo->frameSlotsRegister)
  4263. {
  4264. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  4265. {
  4266. // Symbol is from the param scope of a split scope function and we are emitting the body.
  4267. // We should use the param scope's bytecode now.
  4268. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  4269. op = Js::OpCode::LdParamSlot;
  4270. }
  4271. else
  4272. {
  4273. op = Js::OpCode::LdLocalSlot;
  4274. }
  4275. }
  4276. else if (scopeLocation != Js::Constants::NoRegister &&
  4277. scopeLocation == funcInfo->frameObjRegister)
  4278. {
  4279. if (scope->GetScopeType() == ScopeType_Parameter && scope != scope->GetFunc()->GetCurrentChildScope())
  4280. {
  4281. // Symbol is from the param scope of a split scope function and we are emitting the body.
  4282. // We should use the param scope's bytecode now.
  4283. Assert(!funcInfo->IsBodyAndParamScopeMerged());
  4284. op = Js::OpCode::LdParamObjSlot;
  4285. }
  4286. else
  4287. {
  4288. op = Js::OpCode::LdLocalObjSlot;
  4289. }
  4290. }
  4291. else if (scope->HasInnerScopeIndex())
  4292. {
  4293. if (scope->GetIsObject())
  4294. {
  4295. op = Js::OpCode::LdInnerObjSlot;
  4296. }
  4297. else
  4298. {
  4299. op = Js::OpCode::LdInnerSlot;
  4300. }
  4301. }
  4302. else
  4303. {
  4304. AssertOrFailFast(scope->GetIsObject());
  4305. op = Js::OpCode::LdObjSlot;
  4306. }
  4307. return op;
  4308. }
  4309. bool ByteCodeGenerator::ShouldLoadConstThis(FuncInfo* funcInfo)
  4310. {
  4311. #if DBG
  4312. // We should load a const 'this' binding if the following holds
  4313. // - The function has a 'this' name node
  4314. // - We are in a global or global lambda function
  4315. // - The function has no 'this' symbol (an indirect eval would have this symbol)
  4316. if (funcInfo->thisConstantRegister != Js::Constants::NoRegister)
  4317. {
  4318. Assert((funcInfo->IsLambda() || funcInfo->IsGlobalFunction())
  4319. && !funcInfo->GetThisSymbol()
  4320. && !(this->flags & fscrEval));
  4321. }
  4322. #endif
  4323. return funcInfo->thisConstantRegister != Js::Constants::NoRegister;
  4324. }
  4325. void ByteCodeGenerator::EmitPropLoadThis(Js::RegSlot lhsLocation, ParseNodeSpecialName *pnodeSpecialName, FuncInfo *funcInfo, bool chkUndecl)
  4326. {
  4327. Symbol* sym = pnodeSpecialName->sym;
  4328. if (!sym && this->ShouldLoadConstThis(funcInfo))
  4329. {
  4330. this->Writer()->Reg2(Js::OpCode::Ld_A, lhsLocation, funcInfo->thisConstantRegister);
  4331. }
  4332. else
  4333. {
  4334. this->EmitPropLoad(lhsLocation, pnodeSpecialName->sym, pnodeSpecialName->pid, funcInfo, true);
  4335. if ((!sym || sym->GetNeedDeclaration()) && chkUndecl)
  4336. {
  4337. this->Writer()->Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4338. }
  4339. }
  4340. }
  4341. void ByteCodeGenerator::EmitPropStoreForSpecialSymbol(Js::RegSlot rhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool init)
  4342. {
  4343. if (!funcInfo->IsGlobalFunction() || (this->flags & fscrEval))
  4344. {
  4345. if (init)
  4346. {
  4347. EmitLocalPropInit(rhsLocation, sym, funcInfo);
  4348. }
  4349. else
  4350. {
  4351. EmitPropStore(rhsLocation, sym, pid, funcInfo, false, false, false, true);
  4352. }
  4353. }
  4354. }
  4355. void ByteCodeGenerator::EmitPropLoad(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool skipUseBeforeDeclarationCheck)
  4356. {
  4357. // If sym belongs to a parent frame, get it from the closure environment.
  4358. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4359. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4360. // Otherwise, just copy the value to the lhsLocation.
  4361. Js::ByteCodeLabel doneLabel = 0;
  4362. bool fLabelDefined = false;
  4363. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4364. Js::PropertyId envIndex = -1;
  4365. Scope *scope = nullptr;
  4366. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4367. Assert(symScope);
  4368. if (sym && sym->GetIsModuleExportStorage())
  4369. {
  4370. EmitModuleExportAccess(sym, Js::OpCode::LdModuleSlot, lhsLocation, funcInfo);
  4371. return;
  4372. }
  4373. for (;;)
  4374. {
  4375. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4376. if (scope == this->globalScope)
  4377. {
  4378. break;
  4379. }
  4380. scopeLocation = scope->GetLocation();
  4381. if (scope == symScope)
  4382. {
  4383. break;
  4384. }
  4385. // Found a scope to which the property may have been added.
  4386. Assert(scope && scope->GetIsDynamic());
  4387. if (!fLabelDefined)
  4388. {
  4389. fLabelDefined = true;
  4390. doneLabel = this->m_writer.DefineLabel();
  4391. }
  4392. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4393. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4394. Js::RegSlot unwrappedScopeLocation = Js::Constants::NoRegister;
  4395. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4396. if (envIndex != -1)
  4397. {
  4398. this->m_writer.BrEnvProperty(
  4399. Js::OpCode::BrOnNoEnvProperty,
  4400. nextLabel,
  4401. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4402. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4403. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4404. AssertOrFailFast(scope->GetIsObject());
  4405. this->m_writer.SlotI1(
  4406. Js::OpCode::LdEnvObj,
  4407. instLocation,
  4408. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4409. if (unwrapWithObj)
  4410. {
  4411. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4412. }
  4413. this->m_writer.PatchableProperty(
  4414. Js::OpCode::LdFld,
  4415. lhsLocation,
  4416. instLocation,
  4417. funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, false));
  4418. funcInfo->ReleaseTmpRegister(instLocation);
  4419. }
  4420. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4421. {
  4422. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4423. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4424. Assert(!unwrapWithObj);
  4425. this->m_writer.ElementP(Js::OpCode::LdLocalFld, lhsLocation,
  4426. funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, false));
  4427. }
  4428. else
  4429. {
  4430. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4431. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4432. if (unwrapWithObj)
  4433. {
  4434. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4435. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4436. scopeLocation = unwrappedScopeLocation;
  4437. }
  4438. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, false);
  4439. this->m_writer.PatchableProperty(Js::OpCode::LdFld, lhsLocation, scopeLocation, cacheId);
  4440. if (unwrapWithObj)
  4441. {
  4442. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4443. }
  4444. }
  4445. this->m_writer.Br(doneLabel);
  4446. this->m_writer.MarkLabel(nextLabel);
  4447. }
  4448. // Arrived at the scope in which the property was defined.
  4449. if (sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo && !skipUseBeforeDeclarationCheck)
  4450. {
  4451. // Ensure this symbol has a slot if it needs one.
  4452. if (sym->IsInSlot(this, funcInfo))
  4453. {
  4454. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4455. funcInfo->FindOrAddSlotProfileId(scope, slot);
  4456. }
  4457. if (skipUseBeforeDeclarationCheck)
  4458. {
  4459. if (lhsLocation != Js::Constants::NoRegister)
  4460. {
  4461. this->m_writer.Reg1(Js::OpCode::InitUndecl, lhsLocation);
  4462. }
  4463. }
  4464. else
  4465. {
  4466. EmitUseBeforeDeclarationRuntimeError(this, lhsLocation);
  4467. }
  4468. }
  4469. else if (sym == nullptr || sym->GetIsGlobal())
  4470. {
  4471. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4472. if (this->flags & fscrEval)
  4473. {
  4474. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4475. {
  4476. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->frameDisplayRegister, propertyId, false, false);
  4477. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4478. }
  4479. else
  4480. {
  4481. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, false);
  4482. // Load of a symbol with unknown scope from within eval
  4483. // Get it from the closure environment.
  4484. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4485. }
  4486. }
  4487. else if (this->flags & fscrImplicitThis)
  4488. {
  4489. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, false);
  4490. // Load of a symbol with unknown scope from within event handler.
  4491. // Get it from the closure environment.
  4492. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4493. }
  4494. else
  4495. {
  4496. // Special case non-writable built-ins
  4497. // TODO: support non-writable global property in general by detecting what attribute the property have current?
  4498. // But can't be done if we are byte code serialized, because the attribute might be different for use fields
  4499. // next time we run. May want to catch that in the JIT.
  4500. Js::OpCode opcode = Js::OpCode::LdRootFld;
  4501. // These properties are non-writable
  4502. switch (propertyId)
  4503. {
  4504. case Js::PropertyIds::NaN:
  4505. opcode = Js::OpCode::LdNaN;
  4506. break;
  4507. case Js::PropertyIds::Infinity:
  4508. opcode = Js::OpCode::LdInfinity;
  4509. break;
  4510. case Js::PropertyIds::undefined:
  4511. opcode = Js::OpCode::LdUndef;
  4512. break;
  4513. case Js::PropertyIds::__chakraLibrary:
  4514. if (CONFIG_FLAG(LdChakraLib)) {
  4515. opcode = Js::OpCode::LdChakraLib;
  4516. }
  4517. break;
  4518. }
  4519. if (opcode == Js::OpCode::LdRootFld)
  4520. {
  4521. this->EmitPatchableRootProperty(Js::OpCode::LdRootFld, lhsLocation, propertyId, false, false, funcInfo);
  4522. }
  4523. else
  4524. {
  4525. this->Writer()->Reg1(opcode, lhsLocation);
  4526. }
  4527. }
  4528. }
  4529. else if (sym->IsInSlot(this, funcInfo) || envIndex != -1)
  4530. {
  4531. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4532. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4533. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(scope, slot);
  4534. bool chkBlockVar = NeedCheckBlockVar(sym, scope, funcInfo);
  4535. Js::OpCode op;
  4536. // Now get the property from its slot.
  4537. op = this->GetLdSlotOp(scope, envIndex, scopeLocation, funcInfo);
  4538. slot = slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  4539. if (envIndex != -1)
  4540. {
  4541. this->m_writer.SlotI2(op, lhsLocation, envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var), slot, profileId);
  4542. }
  4543. else if (scopeLocation != Js::Constants::NoRegister &&
  4544. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4545. {
  4546. this->m_writer.SlotI1(op, lhsLocation, slot, profileId);
  4547. }
  4548. else if (scope->HasInnerScopeIndex())
  4549. {
  4550. this->m_writer.SlotI2(op, lhsLocation, scope->GetInnerScopeIndex(), slot, profileId);
  4551. }
  4552. else
  4553. {
  4554. AssertOrFailFast(scope->GetIsObject());
  4555. this->m_writer.Slot(op, lhsLocation, scopeLocation, slot, profileId);
  4556. }
  4557. if (chkBlockVar)
  4558. {
  4559. this->m_writer.Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4560. }
  4561. }
  4562. else
  4563. {
  4564. if (lhsLocation != sym->GetLocation())
  4565. {
  4566. this->m_writer.Reg2(Js::OpCode::Ld_A, lhsLocation, sym->GetLocation());
  4567. }
  4568. if (sym->GetIsBlockVar() && ((sym->GetDecl()->nop == knopLetDecl || sym->GetDecl()->nop == knopConstDecl) && sym->GetDecl()->AsParseNodeVar()->isSwitchStmtDecl))
  4569. {
  4570. this->m_writer.Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4571. }
  4572. }
  4573. if (fLabelDefined)
  4574. {
  4575. this->m_writer.MarkLabel(doneLabel);
  4576. }
  4577. }
  4578. bool ByteCodeGenerator::NeedCheckBlockVar(Symbol* sym, Scope* scope, FuncInfo* funcInfo) const
  4579. {
  4580. bool tdz = sym->GetIsBlockVar()
  4581. && (scope->GetFunc() != funcInfo || ((sym->GetDecl()->nop == knopLetDecl || sym->GetDecl()->nop == knopConstDecl) && sym->GetDecl()->AsParseNodeVar()->isSwitchStmtDecl));
  4582. return tdz || sym->GetIsNonSimpleParameter();
  4583. }
  4584. void ByteCodeGenerator::EmitPropDelete(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo)
  4585. {
  4586. // If sym belongs to a parent frame, delete it from the closure environment.
  4587. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4588. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4589. // Otherwise, just return false.
  4590. Js::ByteCodeLabel doneLabel = 0;
  4591. bool fLabelDefined = false;
  4592. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4593. Js::PropertyId envIndex = -1;
  4594. Scope *scope = nullptr;
  4595. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4596. Assert(symScope);
  4597. for (;;)
  4598. {
  4599. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4600. if (scope == this->globalScope)
  4601. {
  4602. scopeLocation = ByteCodeGenerator::RootObjectRegister;
  4603. }
  4604. else if (envIndex == -1)
  4605. {
  4606. Assert(funcInfo == scope->GetFunc());
  4607. scopeLocation = scope->GetLocation();
  4608. }
  4609. if (scope == symScope)
  4610. {
  4611. break;
  4612. }
  4613. // Found a scope to which the property may have been added.
  4614. Assert(scope && scope->GetIsDynamic());
  4615. if (!fLabelDefined)
  4616. {
  4617. fLabelDefined = true;
  4618. doneLabel = this->m_writer.DefineLabel();
  4619. }
  4620. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4621. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4622. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4623. if (envIndex != -1)
  4624. {
  4625. this->m_writer.BrEnvProperty(
  4626. Js::OpCode::BrOnNoEnvProperty,
  4627. nextLabel,
  4628. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4629. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4630. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4631. AssertOrFailFast(scope->GetIsObject());
  4632. this->m_writer.SlotI1(
  4633. Js::OpCode::LdEnvObj,
  4634. instLocation,
  4635. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4636. if (unwrapWithObj)
  4637. {
  4638. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4639. }
  4640. this->m_writer.Property(Js::OpCode::DeleteFld, lhsLocation, instLocation,
  4641. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4642. funcInfo->ReleaseTmpRegister(instLocation);
  4643. }
  4644. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4645. {
  4646. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4647. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4648. Assert(!unwrapWithObj);
  4649. this->m_writer.ElementU(Js::OpCode::DeleteLocalFld, lhsLocation,
  4650. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4651. }
  4652. else
  4653. {
  4654. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4655. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4656. Js::RegSlot unwrappedScopeLocation = Js::Constants::NoRegister;
  4657. if (unwrapWithObj)
  4658. {
  4659. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4660. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4661. scopeLocation = unwrappedScopeLocation;
  4662. }
  4663. this->m_writer.Property(Js::OpCode::DeleteFld, lhsLocation, scopeLocation,
  4664. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4665. if (unwrapWithObj)
  4666. {
  4667. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4668. }
  4669. }
  4670. this->m_writer.Br(doneLabel);
  4671. this->m_writer.MarkLabel(nextLabel);
  4672. }
  4673. // Arrived at the scope in which the property was defined.
  4674. if (sym == nullptr || sym->GetIsGlobal())
  4675. {
  4676. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4677. if (this->flags & (fscrEval | fscrImplicitThis))
  4678. {
  4679. this->m_writer.ScopedProperty(Js::OpCode::ScopedDeleteFld, lhsLocation,
  4680. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4681. }
  4682. else
  4683. {
  4684. this->m_writer.Property(Js::OpCode::DeleteRootFld, lhsLocation, ByteCodeGenerator::RootObjectRegister,
  4685. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4686. }
  4687. }
  4688. else
  4689. {
  4690. // The delete will look like a non-local reference, so make sure a slot is reserved.
  4691. sym->EnsureScopeSlot(this, funcInfo);
  4692. this->m_writer.Reg1(Js::OpCode::LdFalse, lhsLocation);
  4693. }
  4694. if (fLabelDefined)
  4695. {
  4696. this->m_writer.MarkLabel(doneLabel);
  4697. }
  4698. }
  4699. void ByteCodeGenerator::EmitTypeOfFld(FuncInfo * funcInfo, Js::PropertyId propertyId, Js::RegSlot value, Js::RegSlot instance, Js::OpCode ldFldOp)
  4700. {
  4701. uint cacheId;
  4702. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  4703. switch (ldFldOp)
  4704. {
  4705. case Js::OpCode::LdRootFldForTypeOf:
  4706. cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, false, false);
  4707. this->Writer()->PatchableRootProperty(ldFldOp, tmpReg, cacheId, false, false);
  4708. break;
  4709. case Js::OpCode::LdLocalFld:
  4710. case Js::OpCode::ScopedLdFldForTypeOf:
  4711. cacheId = funcInfo->FindOrAddInlineCacheId(instance, propertyId, false, false);
  4712. this->Writer()->ElementP(ldFldOp, tmpReg, cacheId);
  4713. break;
  4714. default:
  4715. cacheId = funcInfo->FindOrAddInlineCacheId(instance, propertyId, false, false);
  4716. this->Writer()->PatchableProperty(ldFldOp, tmpReg, instance, cacheId);
  4717. break;
  4718. }
  4719. this->Writer()->Reg2(Js::OpCode::Typeof, value, tmpReg);
  4720. funcInfo->ReleaseTmpRegister(tmpReg);
  4721. }
  4722. void ByteCodeGenerator::EmitPropTypeof(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo)
  4723. {
  4724. // If sym belongs to a parent frame, delete it from the closure environment.
  4725. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4726. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4727. // Otherwise, just return false
  4728. Js::ByteCodeLabel doneLabel = 0;
  4729. bool fLabelDefined = false;
  4730. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4731. Js::PropertyId envIndex = -1;
  4732. Scope *scope = nullptr;
  4733. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4734. Assert(symScope);
  4735. if (sym && sym->GetIsModuleExportStorage())
  4736. {
  4737. Js::RegSlot tmpLocation = funcInfo->AcquireTmpRegister();
  4738. EmitModuleExportAccess(sym, Js::OpCode::LdModuleSlot, tmpLocation, funcInfo);
  4739. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, tmpLocation);
  4740. funcInfo->ReleaseTmpRegister(tmpLocation);
  4741. return;
  4742. }
  4743. for (;;)
  4744. {
  4745. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4746. if (scope == this->globalScope)
  4747. {
  4748. scopeLocation = ByteCodeGenerator::RootObjectRegister;
  4749. }
  4750. else if (envIndex == -1)
  4751. {
  4752. Assert(funcInfo == scope->GetFunc());
  4753. scopeLocation = scope->GetLocation();
  4754. }
  4755. if (scope == symScope)
  4756. {
  4757. break;
  4758. }
  4759. // Found a scope to which the property may have been added.
  4760. Assert(scope && scope->GetIsDynamic());
  4761. if (!fLabelDefined)
  4762. {
  4763. fLabelDefined = true;
  4764. doneLabel = this->m_writer.DefineLabel();
  4765. }
  4766. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4767. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4768. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4769. if (envIndex != -1)
  4770. {
  4771. this->m_writer.BrEnvProperty(Js::OpCode::BrOnNoEnvProperty, nextLabel,
  4772. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4773. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4774. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4775. AssertOrFailFast(scope->GetIsObject());
  4776. this->m_writer.SlotI1(Js::OpCode::LdEnvObj,
  4777. instLocation,
  4778. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4779. if (unwrapWithObj)
  4780. {
  4781. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4782. }
  4783. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, instLocation, Js::OpCode::LdFldForTypeOf);
  4784. funcInfo->ReleaseTmpRegister(instLocation);
  4785. }
  4786. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4787. {
  4788. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4789. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4790. Assert(!unwrapWithObj);
  4791. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, scopeLocation, Js::OpCode::LdLocalFld);
  4792. }
  4793. else
  4794. {
  4795. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4796. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4797. Js::RegSlot unwrappedScopeLocation = Js::Constants::NoRegister;
  4798. if (unwrapWithObj)
  4799. {
  4800. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4801. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4802. scopeLocation = unwrappedScopeLocation;
  4803. }
  4804. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, scopeLocation, Js::OpCode::LdFldForTypeOf);
  4805. if (unwrapWithObj)
  4806. {
  4807. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4808. }
  4809. }
  4810. this->m_writer.Br(doneLabel);
  4811. this->m_writer.MarkLabel(nextLabel);
  4812. }
  4813. // Arrived at the scope in which the property was defined.
  4814. if (sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo)
  4815. {
  4816. // Ensure this symbol has a slot if it needs one.
  4817. if (sym->IsInSlot(this, funcInfo))
  4818. {
  4819. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4820. funcInfo->FindOrAddSlotProfileId(scope, slot);
  4821. }
  4822. EmitUseBeforeDeclarationRuntimeError(this, lhsLocation);
  4823. }
  4824. else if (sym == nullptr || sym->GetIsGlobal())
  4825. {
  4826. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4827. if (this->flags & fscrEval)
  4828. {
  4829. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4830. {
  4831. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->frameDisplayRegister, Js::OpCode::ScopedLdFldForTypeOf);
  4832. }
  4833. else
  4834. {
  4835. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->GetEnvRegister(), Js::OpCode::ScopedLdFldForTypeOf);
  4836. }
  4837. }
  4838. else if (this->flags & fscrImplicitThis)
  4839. {
  4840. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->GetEnvRegister(), Js::OpCode::ScopedLdFldForTypeOf);
  4841. }
  4842. else
  4843. {
  4844. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, ByteCodeGenerator::RootObjectRegister, Js::OpCode::LdRootFldForTypeOf);
  4845. }
  4846. }
  4847. else if (sym->IsInSlot(this, funcInfo) || envIndex != -1)
  4848. {
  4849. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4850. Js::PropertyId slot = sym->EnsureScopeSlot(this, funcInfo);
  4851. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(scope, slot);
  4852. Js::RegSlot tmpLocation = funcInfo->AcquireTmpRegister();
  4853. bool chkBlockVar = NeedCheckBlockVar(sym, scope, funcInfo);
  4854. Js::OpCode op;
  4855. op = this->GetLdSlotOp(scope, envIndex, scopeLocation, funcInfo);
  4856. slot = slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  4857. if (envIndex != -1)
  4858. {
  4859. this->m_writer.SlotI2(op, tmpLocation, envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var), slot, profileId);
  4860. }
  4861. else if (scopeLocation != Js::Constants::NoRegister &&
  4862. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4863. {
  4864. this->m_writer.SlotI1(op, tmpLocation, slot, profileId);
  4865. }
  4866. else if (scope->HasInnerScopeIndex())
  4867. {
  4868. this->m_writer.SlotI2(op, tmpLocation, scope->GetInnerScopeIndex(), slot, profileId);
  4869. }
  4870. else
  4871. {
  4872. AssertOrFailFast(scope->GetIsObject());
  4873. this->m_writer.Slot(op, tmpLocation, scopeLocation, slot, profileId);
  4874. }
  4875. if (chkBlockVar)
  4876. {
  4877. this->m_writer.Reg1(Js::OpCode::ChkUndecl, tmpLocation);
  4878. }
  4879. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, tmpLocation);
  4880. funcInfo->ReleaseTmpRegister(tmpLocation);
  4881. }
  4882. else
  4883. {
  4884. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, sym->GetLocation());
  4885. }
  4886. if (fLabelDefined)
  4887. {
  4888. this->m_writer.MarkLabel(doneLabel);
  4889. }
  4890. }
  4891. void ByteCodeGenerator::EnsureNoRedeclarations(ParseNodeBlock *pnodeBlock, FuncInfo *funcInfo)
  4892. {
  4893. // Emit dynamic runtime checks for variable re-declarations. Only necessary for global functions (script or eval).
  4894. // In eval only var declarations can cause redeclaration, and only in non-strict mode, because let/const variables
  4895. // remain local to the eval code.
  4896. Assert(pnodeBlock->nop == knopBlock);
  4897. Assert(pnodeBlock->blockType == PnodeBlockType::Global || pnodeBlock->scope->GetScopeType() == ScopeType_GlobalEvalBlock);
  4898. if (!(this->flags & fscrEvalCode))
  4899. {
  4900. IterateBlockScopedVariables(pnodeBlock, [this](ParseNode *pnode)
  4901. {
  4902. FuncInfo *funcInfo = this->TopFuncInfo();
  4903. Symbol *sym = pnode->AsParseNodeVar()->sym;
  4904. Assert(sym->GetIsGlobal());
  4905. Js::PropertyId propertyId = sym->EnsurePosition(this);
  4906. this->m_writer.ElementRootU(Js::OpCode::EnsureNoRootFld, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4907. });
  4908. }
  4909. auto emitRedeclCheck = [this](Symbol * sym, FuncInfo * funcInfo)
  4910. {
  4911. Js::PropertyId propertyId = sym->EnsurePosition(this);
  4912. if (this->flags & fscrEval)
  4913. {
  4914. if (!funcInfo->byteCodeFunction->GetIsStrictMode())
  4915. {
  4916. this->m_writer.ScopedProperty(Js::OpCode::ScopedEnsureNoRedeclFld, ByteCodeGenerator::RootObjectRegister,
  4917. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4918. }
  4919. }
  4920. else
  4921. {
  4922. this->m_writer.ElementRootU(Js::OpCode::EnsureNoRootRedeclFld, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4923. }
  4924. };
  4925. // scan for function declarations
  4926. // these behave like "var" declarations
  4927. for (ParseNodePtr pnode = pnodeBlock->pnodeScopes; pnode;)
  4928. {
  4929. switch (pnode->nop) {
  4930. case knopFncDecl:
  4931. if (pnode->AsParseNodeFnc()->IsDeclaration())
  4932. {
  4933. emitRedeclCheck(pnode->AsParseNodeFnc()->pnodeName->sym, funcInfo);
  4934. }
  4935. pnode = pnode->AsParseNodeFnc()->pnodeNext;
  4936. break;
  4937. case knopBlock:
  4938. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  4939. break;
  4940. case knopCatch:
  4941. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  4942. break;
  4943. case knopWith:
  4944. pnode = pnode->AsParseNodeWith()->pnodeNext;
  4945. break;
  4946. default:
  4947. Assert(UNREACHED);
  4948. }
  4949. }
  4950. // scan for var declarations
  4951. for (ParseNode *pnode = funcInfo->root->pnodeVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  4952. {
  4953. Symbol* sym = pnode->AsParseNodeVar()->sym;
  4954. if (sym == nullptr || pnode->AsParseNodeVar()->isBlockScopeFncDeclVar || sym->IsSpecialSymbol())
  4955. continue;
  4956. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  4957. {
  4958. // The init node was bound to the catch object, because it's inside a catch and has the
  4959. // same name as the catch object. But we want to define a user var at function scope,
  4960. // so find the right symbol. (We'll still assign the RHS value to the catch object symbol.)
  4961. // This also applies to a var declaration in the same scope as a let declaration.
  4962. // Assert that catch cannot be at function scope and let and var at function scope is redeclaration error.
  4963. Assert(sym->GetIsCatch() || funcInfo->bodyScope != sym->GetScope());
  4964. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  4965. Assert(sym && !sym->GetIsCatch() && !sym->GetIsBlockVar());
  4966. }
  4967. Assert(sym->GetIsGlobal());
  4968. if (sym->GetSymbolType() == STVariable)
  4969. {
  4970. emitRedeclCheck(sym, funcInfo);
  4971. }
  4972. }
  4973. }
  4974. void ByteCodeGenerator::RecordAllIntConstants(FuncInfo * funcInfo)
  4975. {
  4976. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  4977. funcInfo->constantToRegister.Map([byteCodeFunction](unsigned int val, Js::RegSlot location)
  4978. {
  4979. byteCodeFunction->RecordIntConstant(byteCodeFunction->MapRegSlot(location), val);
  4980. });
  4981. }
  4982. void ByteCodeGenerator::RecordAllStrConstants(FuncInfo * funcInfo)
  4983. {
  4984. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  4985. funcInfo->stringToRegister.Map([byteCodeFunction](IdentPtr pid, Js::RegSlot location)
  4986. {
  4987. byteCodeFunction->RecordStrConstant(byteCodeFunction->MapRegSlot(location), pid->Psz(), pid->Cch(), pid->IsUsedInLdElem());
  4988. });
  4989. }
  4990. void ByteCodeGenerator::RecordAllStringTemplateCallsiteConstants(FuncInfo* funcInfo)
  4991. {
  4992. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  4993. funcInfo->stringTemplateCallsiteRegisterMap.Map([byteCodeFunction](ParseNodePtr pnode, Js::RegSlot location)
  4994. {
  4995. Js::ScriptContext* scriptContext = byteCodeFunction->GetScriptContext();
  4996. Js::JavascriptLibrary* library = scriptContext->GetLibrary();
  4997. Js::RecyclableObject* callsiteObject = library->TryGetStringTemplateCallsiteObject(pnode);
  4998. if (callsiteObject == nullptr)
  4999. {
  5000. Js::RecyclableObject* rawArray = ByteCodeGenerator::BuildArrayFromStringList(pnode->AsParseNodeStrTemplate()->pnodeStringRawLiterals, pnode->AsParseNodeStrTemplate()->countStringLiterals, scriptContext);
  5001. rawArray->Freeze();
  5002. callsiteObject = ByteCodeGenerator::BuildArrayFromStringList(pnode->AsParseNodeStrTemplate()->pnodeStringLiterals, pnode->AsParseNodeStrTemplate()->countStringLiterals, scriptContext);
  5003. callsiteObject->SetPropertyWithAttributes(Js::PropertyIds::raw, rawArray, PropertyNone, nullptr);
  5004. callsiteObject->Freeze();
  5005. library->AddStringTemplateCallsiteObject(callsiteObject);
  5006. }
  5007. byteCodeFunction->RecordConstant(byteCodeFunction->MapRegSlot(location), callsiteObject);
  5008. });
  5009. }
  5010. bool IsApplyArgs(ParseNodeCall* callNode)
  5011. {
  5012. ParseNode* target = callNode->pnodeTarget;
  5013. ParseNode* args = callNode->pnodeArgs;
  5014. if ((target != nullptr) && (target->nop == knopDot))
  5015. {
  5016. ParseNode* lhsNode = target->AsParseNodeBin()->pnode1;
  5017. if ((lhsNode != nullptr) && ((lhsNode->nop == knopDot) || (lhsNode->nop == knopName)) && !IsArguments(lhsNode))
  5018. {
  5019. ParseNode* nameNode = target->AsParseNodeBin()->pnode2;
  5020. if (nameNode != nullptr)
  5021. {
  5022. bool nameIsApply = nameNode->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::apply;
  5023. if (nameIsApply && args != nullptr && args->nop == knopList)
  5024. {
  5025. ParseNode* arg1 = args->AsParseNodeBin()->pnode1;
  5026. ParseNode* arg2 = args->AsParseNodeBin()->pnode2;
  5027. if ((arg1 != nullptr) && ByteCodeGenerator::IsThis(arg1) && (arg2 != nullptr) && (arg2->nop == knopName) && (arg2->AsParseNodeName()->sym != nullptr))
  5028. {
  5029. return arg2->AsParseNodeName()->sym->IsArguments();
  5030. }
  5031. }
  5032. }
  5033. }
  5034. }
  5035. return false;
  5036. }
  5037. void PostCheckApplyEnclosesArgs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, ApplyCheck* applyCheck)
  5038. {
  5039. if ((pnode == nullptr) || (!applyCheck->matches))
  5040. {
  5041. return;
  5042. }
  5043. if (pnode->nop == knopCall)
  5044. {
  5045. if ((!pnode->isUsed) && IsApplyArgs(pnode->AsParseNodeCall()))
  5046. {
  5047. if (!applyCheck->insideApplyCall)
  5048. {
  5049. applyCheck->matches = false;
  5050. }
  5051. applyCheck->insideApplyCall = false;
  5052. }
  5053. }
  5054. }
  5055. void CheckApplyEnclosesArgs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, ApplyCheck* applyCheck)
  5056. {
  5057. if ((pnode == nullptr) || (!applyCheck->matches))
  5058. {
  5059. return;
  5060. }
  5061. switch (pnode->nop)
  5062. {
  5063. case knopName:
  5064. {
  5065. Symbol* sym = pnode->AsParseNodeName()->sym;
  5066. if (sym != nullptr)
  5067. {
  5068. if (sym->IsArguments())
  5069. {
  5070. if (!applyCheck->insideApplyCall)
  5071. {
  5072. applyCheck->matches = false;
  5073. }
  5074. }
  5075. }
  5076. break;
  5077. }
  5078. case knopCall:
  5079. if ((!pnode->isUsed) && IsApplyArgs(pnode->AsParseNodeCall()))
  5080. {
  5081. // no nested apply calls
  5082. if (applyCheck->insideApplyCall)
  5083. {
  5084. applyCheck->matches = false;
  5085. }
  5086. else
  5087. {
  5088. applyCheck->insideApplyCall = true;
  5089. applyCheck->sawApply = true;
  5090. pnode->AsParseNodeCall()->isApplyCall = true;
  5091. }
  5092. }
  5093. break;
  5094. }
  5095. }
  5096. unsigned int CountArguments(ParseNode *pnode, BOOL *pSideEffect = nullptr)
  5097. {
  5098. // If the caller passed us a pSideEffect, it wants to know whether there are potential
  5099. // side-effects in the argument list. We need to know this so that the call target
  5100. // operands can be preserved if necessary.
  5101. // For now, treat any non-leaf op as a potential side-effect. This causes no detectable slowdowns,
  5102. // but we can be more precise if we need to be.
  5103. if (pSideEffect)
  5104. {
  5105. *pSideEffect = FALSE;
  5106. }
  5107. unsigned int argCount = 1;
  5108. if (pnode != nullptr)
  5109. {
  5110. while (pnode->nop == knopList)
  5111. {
  5112. argCount++;
  5113. if (pSideEffect && !(ParseNode::Grfnop(pnode->AsParseNodeBin()->pnode1->nop) & fnopLeaf))
  5114. {
  5115. *pSideEffect = TRUE;
  5116. }
  5117. pnode = pnode->AsParseNodeBin()->pnode2;
  5118. }
  5119. argCount++;
  5120. if (pSideEffect && !(ParseNode::Grfnop(pnode->nop) & fnopLeaf))
  5121. {
  5122. *pSideEffect = TRUE;
  5123. }
  5124. }
  5125. AssertOrFailFastMsg(argCount < Js::Constants::UShortMaxValue, "Number of allowed arguments are already capped at parser level");
  5126. return argCount;
  5127. }
  5128. void SaveOpndValue(ParseNode *pnode, FuncInfo *funcInfo)
  5129. {
  5130. // Save a local name to a register other than its home location.
  5131. // This guards against side-effects in cases like x.foo(x = bar()).
  5132. Symbol *sym = nullptr;
  5133. if (pnode->nop == knopName)
  5134. {
  5135. sym = pnode->AsParseNodeName()->sym;
  5136. }
  5137. else if (pnode->nop == knopComputedName)
  5138. {
  5139. ParseNode *pnode1 = pnode->AsParseNodeUni()->pnode1;
  5140. if (pnode1->nop == knopName)
  5141. {
  5142. sym = pnode1->AsParseNodeName()->sym;
  5143. }
  5144. }
  5145. if (sym == nullptr)
  5146. {
  5147. return;
  5148. }
  5149. // If the target is a local being kept in its home location,
  5150. // protect the target's value in the event the home location is overwritten.
  5151. if (pnode->location != Js::Constants::NoRegister &&
  5152. sym->GetScope()->GetFunc() == funcInfo &&
  5153. pnode->location == sym->GetLocation())
  5154. {
  5155. pnode->location = funcInfo->AcquireTmpRegister();
  5156. }
  5157. }
  5158. void ByteCodeGenerator::StartStatement(ParseNode* node)
  5159. {
  5160. Assert(TopFuncInfo() != nullptr);
  5161. m_writer.StartStatement(node, TopFuncInfo()->curTmpReg - TopFuncInfo()->firstTmpReg);
  5162. }
  5163. void ByteCodeGenerator::EndStatement(ParseNode* node)
  5164. {
  5165. m_writer.EndStatement(node);
  5166. }
  5167. void ByteCodeGenerator::StartSubexpression(ParseNode* node)
  5168. {
  5169. Assert(TopFuncInfo() != nullptr);
  5170. m_writer.StartSubexpression(node);
  5171. }
  5172. void ByteCodeGenerator::EndSubexpression(ParseNode* node)
  5173. {
  5174. m_writer.EndSubexpression(node);
  5175. }
  5176. void EmitReference(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  5177. {
  5178. // Generate code for the LHS of an assignment.
  5179. switch (pnode->nop)
  5180. {
  5181. case knopDot:
  5182. Emit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  5183. break;
  5184. case knopIndex:
  5185. Emit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  5186. Emit(pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo, false);
  5187. break;
  5188. case knopName:
  5189. break;
  5190. case knopArrayPattern:
  5191. case knopObjectPattern:
  5192. break;
  5193. case knopCall:
  5194. case knopNew:
  5195. // Emit the operands of a call that will be used as a LHS.
  5196. // These have to be emitted before the RHS, but they have to persist until
  5197. // the end of the expression.
  5198. // Emit the call target operands first.
  5199. switch (pnode->AsParseNodeCall()->pnodeTarget->nop)
  5200. {
  5201. case knopDot:
  5202. case knopIndex:
  5203. funcInfo->AcquireLoc(pnode->AsParseNodeCall()->pnodeTarget);
  5204. EmitReference(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5205. break;
  5206. case knopName:
  5207. {
  5208. Symbol *sym = pnode->AsParseNodeCall()->pnodeTarget->AsParseNodeName()->sym;
  5209. if (!sym || sym->GetLocation() == Js::Constants::NoRegister)
  5210. {
  5211. funcInfo->AcquireLoc(pnode->AsParseNodeCall()->pnodeTarget);
  5212. }
  5213. if (sym && (sym->IsInSlot(byteCodeGenerator, funcInfo) || sym->GetScope()->GetFunc() != funcInfo))
  5214. {
  5215. // Can't get the value from the assigned register, so load it here.
  5216. EmitLoad(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5217. }
  5218. else
  5219. {
  5220. // EmitLoad will check for needsDeclaration and emit the Use Before Declaration error
  5221. // bytecode op as necessary, but EmitReference does not check this (by design). So we
  5222. // must manually check here.
  5223. EmitUseBeforeDeclaration(pnode->AsParseNodeCall()->pnodeTarget->AsParseNodeName()->sym, byteCodeGenerator, funcInfo);
  5224. EmitReference(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5225. }
  5226. break;
  5227. }
  5228. default:
  5229. EmitLoad(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo);
  5230. break;
  5231. }
  5232. // Now the arg list. We evaluate everything now and emit the ArgOut's later.
  5233. if (pnode->AsParseNodeCall()->pnodeArgs)
  5234. {
  5235. ParseNode *pnodeArg = pnode->AsParseNodeCall()->pnodeArgs;
  5236. while (pnodeArg->nop == knopList)
  5237. {
  5238. Emit(pnodeArg->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  5239. pnodeArg = pnodeArg->AsParseNodeBin()->pnode2;
  5240. }
  5241. Emit(pnodeArg, byteCodeGenerator, funcInfo, false);
  5242. }
  5243. if (pnode->AsParseNodeCall()->isSuperCall)
  5244. {
  5245. Emit(pnode->AsParseNodeSuperCall()->pnodeThis, byteCodeGenerator, funcInfo, false);
  5246. Emit(pnode->AsParseNodeSuperCall()->pnodeNewTarget, byteCodeGenerator, funcInfo, false);
  5247. }
  5248. break;
  5249. default:
  5250. Emit(pnode, byteCodeGenerator, funcInfo, false);
  5251. break;
  5252. }
  5253. }
  5254. void EmitGetIterator(Js::RegSlot iteratorLocation, Js::RegSlot iterableLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5255. void EmitIteratorNext(Js::RegSlot itemLocation, Js::RegSlot iteratorLocation, Js::RegSlot nextInputLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5256. void EmitIteratorClose(Js::RegSlot iteratorLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5257. void EmitIteratorComplete(Js::RegSlot doneLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5258. void EmitIteratorValue(Js::RegSlot valueLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5259. void EmitDestructuredElement(ParseNode *elem, Js::RegSlot sourceLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo *funcInfo)
  5260. {
  5261. switch (elem->nop)
  5262. {
  5263. case knopVarDecl:
  5264. case knopLetDecl:
  5265. case knopConstDecl:
  5266. // We manually need to set NeedDeclaration since the node won't be visited.
  5267. elem->AsParseNodeVar()->sym->SetNeedDeclaration(false);
  5268. break;
  5269. default:
  5270. EmitReference(elem, byteCodeGenerator, funcInfo);
  5271. }
  5272. EmitAssignment(nullptr, elem, sourceLocation, byteCodeGenerator, funcInfo);
  5273. funcInfo->ReleaseReference(elem);
  5274. }
  5275. void EmitDestructuredRestArray(ParseNode *elem,
  5276. Js::RegSlot iteratorLocation,
  5277. Js::RegSlot shouldCallReturnFunctionLocation,
  5278. Js::RegSlot shouldCallReturnFunctionLocationFinally,
  5279. ByteCodeGenerator *byteCodeGenerator,
  5280. FuncInfo *funcInfo)
  5281. {
  5282. Js::RegSlot restArrayLocation = funcInfo->AcquireTmpRegister();
  5283. bool isAssignmentTarget = !(elem->AsParseNodeUni()->pnode1->IsPattern() || elem->AsParseNodeUni()->pnode1->IsVarLetOrConst());
  5284. if (isAssignmentTarget)
  5285. {
  5286. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  5287. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  5288. EmitReference(elem->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo);
  5289. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5290. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5291. }
  5292. byteCodeGenerator->Writer()->Reg1Unsigned1(
  5293. Js::OpCode::NewScArray,
  5294. restArrayLocation,
  5295. ByteCodeGenerator::DefaultArraySize);
  5296. // BytecodeGen can't convey to IRBuilder that some of the temporaries used here are live. When we
  5297. // have a rest parameter, a counter is used in a loop for the array index, but there is no way to
  5298. // convey this is live on the back edge.
  5299. // As a workaround, we have a persistent var reg that is used for the loop counter
  5300. Js::RegSlot counterLocation = elem->location;
  5301. // TODO[ianhall]: Is calling EnregisterConstant() during Emit phase allowed?
  5302. Js::RegSlot zeroConstantReg = byteCodeGenerator->EnregisterConstant(0);
  5303. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, counterLocation, zeroConstantReg);
  5304. // loopTop:
  5305. Js::ByteCodeLabel loopTop = byteCodeGenerator->Writer()->DefineLabel();
  5306. byteCodeGenerator->Writer()->MarkLabel(loopTop);
  5307. Js::RegSlot itemLocation = funcInfo->AcquireTmpRegister();
  5308. EmitIteratorNext(itemLocation, iteratorLocation, Js::Constants::NoRegister, byteCodeGenerator, funcInfo);
  5309. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  5310. EmitIteratorComplete(doneLocation, itemLocation, byteCodeGenerator, funcInfo);
  5311. Js::ByteCodeLabel iteratorDone = byteCodeGenerator->Writer()->DefineLabel();
  5312. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, iteratorDone, doneLocation);
  5313. Js::RegSlot valueLocation = funcInfo->AcquireTmpRegister();
  5314. EmitIteratorValue(valueLocation, itemLocation, byteCodeGenerator, funcInfo);
  5315. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  5316. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  5317. byteCodeGenerator->Writer()->Element(
  5318. ByteCodeGenerator::GetStElemIOpCode(funcInfo),
  5319. valueLocation, restArrayLocation, counterLocation);
  5320. funcInfo->ReleaseTmpRegister(valueLocation);
  5321. funcInfo->ReleaseTmpRegister(doneLocation);
  5322. funcInfo->ReleaseTmpRegister(itemLocation);
  5323. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Incr_A, counterLocation, counterLocation);
  5324. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5325. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5326. byteCodeGenerator->Writer()->Br(loopTop);
  5327. // iteratorDone:
  5328. byteCodeGenerator->Writer()->MarkLabel(iteratorDone);
  5329. ParseNode *restElem = elem->AsParseNodeUni()->pnode1;
  5330. if (isAssignmentTarget)
  5331. {
  5332. EmitAssignment(nullptr, restElem, restArrayLocation, byteCodeGenerator, funcInfo);
  5333. funcInfo->ReleaseReference(restElem);
  5334. }
  5335. else
  5336. {
  5337. EmitDestructuredElement(restElem, restArrayLocation, byteCodeGenerator, funcInfo);
  5338. }
  5339. funcInfo->ReleaseTmpRegister(restArrayLocation);
  5340. }
  5341. void EmitDestructuredArray(
  5342. ParseNode *lhs,
  5343. Js::RegSlot rhsLocation,
  5344. ByteCodeGenerator *byteCodeGenerator,
  5345. FuncInfo *funcInfo);
  5346. void EmitIteratorCloseIfNotDone(Js::RegSlot iteratorLocation, Js::RegSlot doneLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  5347. {
  5348. Js::ByteCodeLabel skipCloseLabel = byteCodeGenerator->Writer()->DefineLabel();
  5349. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, skipCloseLabel, doneLocation);
  5350. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5351. byteCodeGenerator->Writer()->MarkLabel(skipCloseLabel);
  5352. }
  5353. /*
  5354. EmitDestructuredArray(lhsArray, rhs):
  5355. iterator = rhs[@@iterator]
  5356. if lhsArray empty
  5357. return
  5358. for each element in lhsArray except rest
  5359. value = iterator.next()
  5360. if element is a nested destructured array
  5361. EmitDestructuredArray(element, value)
  5362. else
  5363. if value is undefined and there is an initializer
  5364. evaluate initializer
  5365. evaluate element reference
  5366. element = initializer
  5367. else
  5368. element = value
  5369. if lhsArray has a rest element
  5370. rest = []
  5371. while iterator is not done
  5372. value = iterator.next()
  5373. rest.append(value)
  5374. */
  5375. void EmitDestructuredArrayCore(
  5376. ParseNode *list,
  5377. Js::RegSlot iteratorLocation,
  5378. Js::RegSlot shouldCallReturnFunctionLocation,
  5379. Js::RegSlot shouldCallReturnFunctionLocationFinally,
  5380. ByteCodeGenerator *byteCodeGenerator,
  5381. FuncInfo *funcInfo
  5382. )
  5383. {
  5384. Assert(list != nullptr);
  5385. ParseNode *elem = nullptr;
  5386. while (list != nullptr)
  5387. {
  5388. ParseNode *init = nullptr;
  5389. if (list->nop == knopList)
  5390. {
  5391. elem = list->AsParseNodeBin()->pnode1;
  5392. }
  5393. else
  5394. {
  5395. elem = list;
  5396. }
  5397. if (elem->nop == knopEllipsis)
  5398. {
  5399. break;
  5400. }
  5401. switch (elem->nop)
  5402. {
  5403. case knopAsg:
  5404. // An assignment node will always have an initializer
  5405. init = elem->AsParseNodeBin()->pnode2;
  5406. elem = elem->AsParseNodeBin()->pnode1;
  5407. break;
  5408. case knopVarDecl:
  5409. case knopLetDecl:
  5410. case knopConstDecl:
  5411. init = elem->AsParseNodeVar()->pnodeInit;
  5412. break;
  5413. default:
  5414. break;
  5415. }
  5416. byteCodeGenerator->StartStatement(elem);
  5417. bool isAssignmentTarget = !(elem->IsPattern() || elem->IsVarLetOrConst());
  5418. if (isAssignmentTarget)
  5419. {
  5420. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  5421. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  5422. EmitReference(elem, byteCodeGenerator, funcInfo);
  5423. }
  5424. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5425. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5426. Js::RegSlot itemLocation = funcInfo->AcquireTmpRegister();
  5427. EmitIteratorNext(itemLocation, iteratorLocation, Js::Constants::NoRegister, byteCodeGenerator, funcInfo);
  5428. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  5429. EmitIteratorComplete(doneLocation, itemLocation, byteCodeGenerator, funcInfo);
  5430. if (elem->nop == knopEmpty)
  5431. {
  5432. if (list->nop == knopList)
  5433. {
  5434. list = list->AsParseNodeBin()->pnode2;
  5435. funcInfo->ReleaseTmpRegister(doneLocation);
  5436. funcInfo->ReleaseTmpRegister(itemLocation);
  5437. continue;
  5438. }
  5439. else
  5440. {
  5441. Assert(list->nop == knopEmpty);
  5442. EmitIteratorCloseIfNotDone(iteratorLocation, doneLocation, byteCodeGenerator, funcInfo);
  5443. funcInfo->ReleaseTmpRegister(doneLocation);
  5444. funcInfo->ReleaseTmpRegister(itemLocation);
  5445. break;
  5446. }
  5447. }
  5448. // If the iterator hasn't completed, skip assigning undefined.
  5449. Js::ByteCodeLabel iteratorAlreadyDone = byteCodeGenerator->Writer()->DefineLabel();
  5450. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, iteratorAlreadyDone, doneLocation);
  5451. // We're not done with the iterator, so assign the .next() value.
  5452. Js::RegSlot valueLocation = funcInfo->AcquireTmpRegister();
  5453. EmitIteratorValue(valueLocation, itemLocation, byteCodeGenerator, funcInfo);
  5454. Js::ByteCodeLabel beforeDefaultAssign = byteCodeGenerator->Writer()->DefineLabel();
  5455. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  5456. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  5457. byteCodeGenerator->Writer()->Br(beforeDefaultAssign);
  5458. // iteratorAlreadyDone:
  5459. byteCodeGenerator->Writer()->MarkLabel(iteratorAlreadyDone);
  5460. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocation, funcInfo->undefinedConstantRegister);
  5461. // beforeDefaultAssign:
  5462. byteCodeGenerator->Writer()->MarkLabel(beforeDefaultAssign);
  5463. if (elem->IsPattern())
  5464. {
  5465. // If we get an undefined value and have an initializer, use it in place of undefined.
  5466. if (init != nullptr)
  5467. {
  5468. /*
  5469. the IR builder uses two symbols for a temp register in the if else path
  5470. R9 <- R3
  5471. if (...)
  5472. R9 <- R2
  5473. R10 = R9.<property> // error -> IR creates a new lifetime for the if path, and the direct path dest is not referenced
  5474. hence we have to create a new temp
  5475. TEMP REG USED TO FIX THIS PRODUCES THIS
  5476. R9 <- R3
  5477. if (BrEq_A R9, R3)
  5478. R10 <- R2 :
  5479. else
  5480. R10 <- R9 : skipdefault
  5481. ... = R10[@@iterator] : loadIter
  5482. */
  5483. // Temp Register
  5484. Js::RegSlot valueLocationTmp = funcInfo->AcquireTmpRegister();
  5485. byteCodeGenerator->StartStatement(init);
  5486. Js::ByteCodeLabel skipDefault = byteCodeGenerator->Writer()->DefineLabel();
  5487. Js::ByteCodeLabel loadIter = byteCodeGenerator->Writer()->DefineLabel();
  5488. // check value is undefined
  5489. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrNeq_A, skipDefault, valueLocation, funcInfo->undefinedConstantRegister);
  5490. // Evaluate the default expression and assign it.
  5491. Emit(init, byteCodeGenerator, funcInfo, false);
  5492. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocationTmp, init->location);
  5493. funcInfo->ReleaseLoc(init);
  5494. // jmp to loadIter
  5495. byteCodeGenerator->Writer()->Br(loadIter);
  5496. // skipDefault:
  5497. byteCodeGenerator->Writer()->MarkLabel(skipDefault);
  5498. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocationTmp, valueLocation);
  5499. // loadIter:
  5500. // @@iterator
  5501. byteCodeGenerator->Writer()->MarkLabel(loadIter);
  5502. byteCodeGenerator->EndStatement(init);
  5503. if (elem->nop == knopObjectPattern)
  5504. {
  5505. EmitDestructuredObject(elem, valueLocationTmp, byteCodeGenerator, funcInfo);
  5506. }
  5507. else
  5508. {
  5509. // Recursively emit a destructured array using the current .next() as the RHS.
  5510. EmitDestructuredArray(elem, valueLocationTmp, byteCodeGenerator, funcInfo);
  5511. }
  5512. funcInfo->ReleaseTmpRegister(valueLocationTmp);
  5513. }
  5514. else
  5515. {
  5516. if (elem->nop == knopObjectPattern)
  5517. {
  5518. EmitDestructuredObject(elem, valueLocation, byteCodeGenerator, funcInfo);
  5519. }
  5520. else
  5521. {
  5522. // Recursively emit a destructured array using the current .next() as the RHS.
  5523. EmitDestructuredArray(elem, valueLocation, byteCodeGenerator, funcInfo);
  5524. }
  5525. }
  5526. }
  5527. else
  5528. {
  5529. EmitDestructuredValueOrInitializer(elem, valueLocation, init, isAssignmentTarget, byteCodeGenerator, funcInfo);
  5530. }
  5531. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5532. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5533. if (list->nop != knopList)
  5534. {
  5535. EmitIteratorCloseIfNotDone(iteratorLocation, doneLocation, byteCodeGenerator, funcInfo);
  5536. }
  5537. funcInfo->ReleaseTmpRegister(valueLocation);
  5538. funcInfo->ReleaseTmpRegister(doneLocation);
  5539. funcInfo->ReleaseTmpRegister(itemLocation);
  5540. if (isAssignmentTarget)
  5541. {
  5542. funcInfo->ReleaseReference(elem);
  5543. }
  5544. byteCodeGenerator->EndStatement(elem);
  5545. if (list->nop == knopList)
  5546. {
  5547. list = list->AsParseNodeBin()->pnode2;
  5548. }
  5549. else
  5550. {
  5551. break;
  5552. }
  5553. }
  5554. // If we saw a rest element, emit the rest array.
  5555. if (elem != nullptr && elem->nop == knopEllipsis)
  5556. {
  5557. EmitDestructuredRestArray(elem,
  5558. iteratorLocation,
  5559. shouldCallReturnFunctionLocation,
  5560. shouldCallReturnFunctionLocationFinally,
  5561. byteCodeGenerator,
  5562. funcInfo);
  5563. }
  5564. }
  5565. // Generating
  5566. // try {
  5567. // CallIteratorClose
  5568. // } catch (e) {
  5569. // do nothing
  5570. // }
  5571. void EmitTryCatchAroundClose(
  5572. Js::RegSlot iteratorLocation,
  5573. Js::ByteCodeLabel endLabel,
  5574. ByteCodeGenerator *byteCodeGenerator,
  5575. FuncInfo *funcInfo)
  5576. {
  5577. Js::ByteCodeLabel catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  5578. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  5579. //
  5580. // There is no need to add TryScopeRecord here as we are going to call 'return' function and there is not yield expression here.
  5581. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5582. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5583. byteCodeGenerator->Writer()->Br(endLabel);
  5584. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  5585. Js::RegSlot catchParamLocation = funcInfo->AcquireTmpRegister();
  5586. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, catchParamLocation);
  5587. funcInfo->ReleaseTmpRegister(catchParamLocation);
  5588. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5589. }
  5590. struct ByteCodeGenerator::TryScopeRecord : public JsUtil::DoublyLinkedListElement<TryScopeRecord>
  5591. {
  5592. Js::OpCode op;
  5593. Js::ByteCodeLabel label;
  5594. Js::RegSlot reg1;
  5595. Js::RegSlot reg2;
  5596. TryScopeRecord(Js::OpCode op, Js::ByteCodeLabel label) : op(op), label(label), reg1(Js::Constants::NoRegister), reg2(Js::Constants::NoRegister) { }
  5597. TryScopeRecord(Js::OpCode op, Js::ByteCodeLabel label, Js::RegSlot r1, Js::RegSlot r2) : op(op), label(label), reg1(r1), reg2(r2) { }
  5598. };
  5599. // Generating
  5600. // catch(e) {
  5601. // if (shouldCallReturn)
  5602. // CallReturnWhichWrappedByTryCatch
  5603. // throw e;
  5604. // }
  5605. void EmitTopLevelCatch(Js::ByteCodeLabel catchLabel,
  5606. Js::RegSlot iteratorLocation,
  5607. Js::RegSlot shouldCallReturnLocation,
  5608. Js::RegSlot shouldCallReturnLocationFinally,
  5609. ByteCodeGenerator *byteCodeGenerator,
  5610. FuncInfo *funcInfo)
  5611. {
  5612. Js::ByteCodeLabel afterCatchBlockLabel = byteCodeGenerator->Writer()->DefineLabel();
  5613. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5614. byteCodeGenerator->Writer()->Br(afterCatchBlockLabel);
  5615. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  5616. Js::RegSlot catchParamLocation = funcInfo->AcquireTmpRegister();
  5617. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, catchParamLocation);
  5618. ByteCodeGenerator::TryScopeRecord tryRecForCatch(Js::OpCode::ResumeCatch, catchLabel);
  5619. if (funcInfo->byteCodeFunction->IsCoroutine())
  5620. {
  5621. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForCatch);
  5622. }
  5623. Js::ByteCodeLabel skipCallCloseLabel = byteCodeGenerator->Writer()->DefineLabel();
  5624. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, skipCallCloseLabel, shouldCallReturnLocation);
  5625. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnLocationFinally);
  5626. EmitTryCatchAroundClose(iteratorLocation, skipCallCloseLabel, byteCodeGenerator, funcInfo);
  5627. byteCodeGenerator->Writer()->MarkLabel(skipCallCloseLabel);
  5628. // Rethrow the exception.
  5629. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Throw, catchParamLocation);
  5630. funcInfo->ReleaseTmpRegister(catchParamLocation);
  5631. if (funcInfo->byteCodeFunction->IsCoroutine())
  5632. {
  5633. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  5634. }
  5635. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5636. byteCodeGenerator->Writer()->MarkLabel(afterCatchBlockLabel);
  5637. }
  5638. // Generating
  5639. // finally {
  5640. // if (shouldCallReturn)
  5641. // CallReturn
  5642. // }
  5643. void EmitTopLevelFinally(Js::ByteCodeLabel finallyLabel,
  5644. Js::RegSlot iteratorLocation,
  5645. Js::RegSlot shouldCallReturnLocation,
  5646. Js::RegSlot yieldExceptionLocation,
  5647. Js::RegSlot yieldOffsetLocation,
  5648. ByteCodeGenerator *byteCodeGenerator,
  5649. FuncInfo *funcInfo)
  5650. {
  5651. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  5652. Js::ByteCodeLabel afterFinallyBlockLabel = byteCodeGenerator->Writer()->DefineLabel();
  5653. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5654. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  5655. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  5656. byteCodeGenerator->Writer()->Br(afterFinallyBlockLabel);
  5657. byteCodeGenerator->Writer()->MarkLabel(finallyLabel);
  5658. byteCodeGenerator->Writer()->Empty(Js::OpCode::Finally);
  5659. ByteCodeGenerator::TryScopeRecord tryRecForFinally(Js::OpCode::ResumeFinally, finallyLabel, yieldExceptionLocation, yieldOffsetLocation);
  5660. if (isCoroutine)
  5661. {
  5662. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForFinally);
  5663. }
  5664. Js::ByteCodeLabel skipCallCloseLabel = byteCodeGenerator->Writer()->DefineLabel();
  5665. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, skipCallCloseLabel, shouldCallReturnLocation);
  5666. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5667. byteCodeGenerator->Writer()->MarkLabel(skipCallCloseLabel);
  5668. if (isCoroutine)
  5669. {
  5670. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  5671. funcInfo->ReleaseTmpRegister(yieldOffsetLocation);
  5672. funcInfo->ReleaseTmpRegister(yieldExceptionLocation);
  5673. }
  5674. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  5675. byteCodeGenerator->Writer()->Empty(Js::OpCode::LeaveNull);
  5676. byteCodeGenerator->Writer()->MarkLabel(afterFinallyBlockLabel);
  5677. }
  5678. void EmitCatchAndFinallyBlocks(Js::ByteCodeLabel catchLabel,
  5679. Js::ByteCodeLabel finallyLabel,
  5680. Js::RegSlot iteratorLocation,
  5681. Js::RegSlot shouldCallReturnFunctionLocation,
  5682. Js::RegSlot shouldCallReturnFunctionLocationFinally,
  5683. Js::RegSlot yieldExceptionLocation,
  5684. Js::RegSlot yieldOffsetLocation,
  5685. ByteCodeGenerator *byteCodeGenerator,
  5686. FuncInfo *funcInfo
  5687. )
  5688. {
  5689. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  5690. if (isCoroutine)
  5691. {
  5692. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  5693. }
  5694. EmitTopLevelCatch(catchLabel,
  5695. iteratorLocation,
  5696. shouldCallReturnFunctionLocation,
  5697. shouldCallReturnFunctionLocationFinally,
  5698. byteCodeGenerator,
  5699. funcInfo);
  5700. if (isCoroutine)
  5701. {
  5702. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  5703. }
  5704. EmitTopLevelFinally(finallyLabel,
  5705. iteratorLocation,
  5706. shouldCallReturnFunctionLocationFinally,
  5707. yieldExceptionLocation,
  5708. yieldOffsetLocation,
  5709. byteCodeGenerator,
  5710. funcInfo);
  5711. funcInfo->ReleaseTmpRegister(shouldCallReturnFunctionLocationFinally);
  5712. funcInfo->ReleaseTmpRegister(shouldCallReturnFunctionLocation);
  5713. }
  5714. // Emit a wrapper try..finaly block around the destructuring elements
  5715. void EmitDestructuredArray(
  5716. ParseNode *lhs,
  5717. Js::RegSlot rhsLocation,
  5718. ByteCodeGenerator *byteCodeGenerator,
  5719. FuncInfo *funcInfo)
  5720. {
  5721. byteCodeGenerator->StartStatement(lhs);
  5722. Js::RegSlot iteratorLocation = funcInfo->AcquireTmpRegister();
  5723. EmitGetIterator(iteratorLocation, rhsLocation, byteCodeGenerator, funcInfo);
  5724. Assert(lhs->nop == knopArrayPattern);
  5725. ParseNode *list = lhs->AsParseNodeArrLit()->pnode1;
  5726. if (list == nullptr)
  5727. { // Handline this case ([] = obj);
  5728. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5729. // No elements to bind or assign.
  5730. funcInfo->ReleaseTmpRegister(iteratorLocation);
  5731. byteCodeGenerator->EndStatement(lhs);
  5732. return;
  5733. }
  5734. // This variable facilitates on when to call the return function (which is Iterator close). When we are emitting bytecode for destructuring element
  5735. // this variable will be set to true.
  5736. Js::RegSlot shouldCallReturnFunctionLocation = funcInfo->AcquireTmpRegister();
  5737. Js::RegSlot shouldCallReturnFunctionLocationFinally = funcInfo->AcquireTmpRegister();
  5738. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5739. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5740. byteCodeGenerator->SetHasFinally(true);
  5741. byteCodeGenerator->SetHasTry(true);
  5742. byteCodeGenerator->TopFuncInfo()->byteCodeFunction->SetDontInline(true);
  5743. Js::RegSlot regException = Js::Constants::NoRegister;
  5744. Js::RegSlot regOffset = Js::Constants::NoRegister;
  5745. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  5746. if (isCoroutine)
  5747. {
  5748. regException = funcInfo->AcquireTmpRegister();
  5749. regOffset = funcInfo->AcquireTmpRegister();
  5750. }
  5751. // Insert try node here
  5752. Js::ByteCodeLabel finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  5753. Js::ByteCodeLabel catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  5754. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  5755. ByteCodeGenerator::TryScopeRecord tryRecForTryFinally(Js::OpCode::TryFinallyWithYield, finallyLabel);
  5756. if (isCoroutine)
  5757. {
  5758. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  5759. tryRecForTryFinally.reg1 = regException;
  5760. tryRecForTryFinally.reg2 = regOffset;
  5761. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTryFinally);
  5762. }
  5763. else
  5764. {
  5765. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  5766. }
  5767. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  5768. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryCatch, catchLabel);
  5769. if (isCoroutine)
  5770. {
  5771. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  5772. }
  5773. EmitDestructuredArrayCore(list,
  5774. iteratorLocation,
  5775. shouldCallReturnFunctionLocation,
  5776. shouldCallReturnFunctionLocationFinally,
  5777. byteCodeGenerator,
  5778. funcInfo);
  5779. EmitCatchAndFinallyBlocks(catchLabel,
  5780. finallyLabel,
  5781. iteratorLocation,
  5782. shouldCallReturnFunctionLocation,
  5783. shouldCallReturnFunctionLocationFinally,
  5784. regException,
  5785. regOffset,
  5786. byteCodeGenerator,
  5787. funcInfo);
  5788. funcInfo->ReleaseTmpRegister(iteratorLocation);
  5789. byteCodeGenerator->EndStatement(lhs);
  5790. }
  5791. void EmitNameInvoke(Js::RegSlot lhsLocation,
  5792. Js::RegSlot objectLocation,
  5793. ParseNodePtr nameNode,
  5794. ByteCodeGenerator* byteCodeGenerator,
  5795. FuncInfo* funcInfo)
  5796. {
  5797. Assert(nameNode != nullptr);
  5798. if (nameNode->nop == knopComputedName)
  5799. {
  5800. ParseNodePtr pnode1 = nameNode->AsParseNodeUni()->pnode1;
  5801. Emit(pnode1, byteCodeGenerator, funcInfo, false/*isConstructorCall*/);
  5802. byteCodeGenerator->Writer()->Element(Js::OpCode::LdElemI_A, lhsLocation, objectLocation, pnode1->location);
  5803. funcInfo->ReleaseLoc(pnode1);
  5804. }
  5805. else
  5806. {
  5807. Assert(nameNode->nop == knopStr);
  5808. Js::PropertyId propertyId = nameNode->AsParseNodeStr()->pid->GetPropertyId();
  5809. uint cacheId = funcInfo->FindOrAddInlineCacheId(objectLocation, propertyId, false/*isLoadMethod*/, false/*isStore*/);
  5810. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, lhsLocation, objectLocation, cacheId);
  5811. }
  5812. }
  5813. void EmitDestructuredValueOrInitializer(ParseNodePtr lhsElementNode,
  5814. Js::RegSlot rhsLocation,
  5815. ParseNodePtr initializer,
  5816. bool isNonPatternAssignmentTarget,
  5817. ByteCodeGenerator *byteCodeGenerator,
  5818. FuncInfo *funcInfo)
  5819. {
  5820. // 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
  5821. Js::ByteCodeLabel useDefault = -1;
  5822. Js::ByteCodeLabel end = -1;
  5823. Js::RegSlot rhsLocationTmp = rhsLocation;
  5824. if (initializer != nullptr)
  5825. {
  5826. rhsLocationTmp = funcInfo->AcquireTmpRegister();
  5827. useDefault = byteCodeGenerator->Writer()->DefineLabel();
  5828. end = byteCodeGenerator->Writer()->DefineLabel();
  5829. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, useDefault, rhsLocation, funcInfo->undefinedConstantRegister);
  5830. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocationTmp, rhsLocation);
  5831. byteCodeGenerator->Writer()->Br(end);
  5832. byteCodeGenerator->Writer()->MarkLabel(useDefault);
  5833. Emit(initializer, byteCodeGenerator, funcInfo, false/*isConstructorCall*/);
  5834. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocationTmp, initializer->location);
  5835. funcInfo->ReleaseLoc(initializer);
  5836. byteCodeGenerator->Writer()->MarkLabel(end);
  5837. }
  5838. if (lhsElementNode->nop == knopArrayPattern)
  5839. {
  5840. EmitDestructuredArray(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5841. }
  5842. else if (lhsElementNode->nop == knopObjectPattern)
  5843. {
  5844. EmitDestructuredObject(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5845. }
  5846. else if (isNonPatternAssignmentTarget)
  5847. {
  5848. EmitAssignment(nullptr, lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5849. }
  5850. else
  5851. {
  5852. EmitDestructuredElement(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  5853. }
  5854. if (initializer != nullptr)
  5855. {
  5856. funcInfo->ReleaseTmpRegister(rhsLocationTmp);
  5857. }
  5858. }
  5859. void EmitDestructuredObjectMember(ParseNodePtr memberNode,
  5860. Js::RegSlot rhsLocation,
  5861. ByteCodeGenerator *byteCodeGenerator,
  5862. FuncInfo *funcInfo)
  5863. {
  5864. Assert(memberNode->nop == knopObjectPatternMember);
  5865. Js::RegSlot nameLocation = funcInfo->AcquireTmpRegister();
  5866. EmitNameInvoke(nameLocation, rhsLocation, memberNode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo);
  5867. // Imagine we are transforming
  5868. // {x:x1} = {} to x1 = {}.x (here x1 is the second node of the member but that is our lhsnode)
  5869. ParseNodePtr lhsElementNode = memberNode->AsParseNodeBin()->pnode2;
  5870. ParseNodePtr init = nullptr;
  5871. if (lhsElementNode->IsVarLetOrConst())
  5872. {
  5873. init = lhsElementNode->AsParseNodeVar()->pnodeInit;
  5874. }
  5875. else if (lhsElementNode->nop == knopAsg)
  5876. {
  5877. init = lhsElementNode->AsParseNodeBin()->pnode2;
  5878. lhsElementNode = lhsElementNode->AsParseNodeBin()->pnode1;
  5879. }
  5880. EmitDestructuredValueOrInitializer(lhsElementNode, nameLocation, init, false /*isNonPatternAssignmentTarget*/, byteCodeGenerator, funcInfo);
  5881. funcInfo->ReleaseTmpRegister(nameLocation);
  5882. }
  5883. void EmitDestructuredObject(ParseNode *lhs,
  5884. Js::RegSlot rhsLocationOrig,
  5885. ByteCodeGenerator *byteCodeGenerator,
  5886. FuncInfo *funcInfo)
  5887. {
  5888. Assert(lhs->nop == knopObjectPattern);
  5889. ParseNodePtr pnode1 = lhs->AsParseNodeUni()->pnode1;
  5890. byteCodeGenerator->StartStatement(lhs);
  5891. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  5892. Js::RegSlot rhsLocation = funcInfo->AcquireTmpRegister();
  5893. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocation, rhsLocationOrig);
  5894. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrNeq_A, skipThrow, rhsLocation, funcInfo->undefinedConstantRegister);
  5895. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ObjectCoercible));
  5896. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  5897. if (pnode1 != nullptr)
  5898. {
  5899. Assert(pnode1->nop == knopList || pnode1->nop == knopObjectPatternMember);
  5900. ParseNodePtr current = pnode1;
  5901. while (current->nop == knopList)
  5902. {
  5903. ParseNodePtr memberNode = current->AsParseNodeBin()->pnode1;
  5904. EmitDestructuredObjectMember(memberNode, rhsLocation, byteCodeGenerator, funcInfo);
  5905. current = current->AsParseNodeBin()->pnode2;
  5906. }
  5907. EmitDestructuredObjectMember(current, rhsLocation, byteCodeGenerator, funcInfo);
  5908. }
  5909. funcInfo->ReleaseTmpRegister(rhsLocation);
  5910. byteCodeGenerator->EndStatement(lhs);
  5911. }
  5912. void EmitAssignment(
  5913. ParseNode *asgnNode,
  5914. ParseNode *lhs,
  5915. Js::RegSlot rhsLocation,
  5916. ByteCodeGenerator *byteCodeGenerator,
  5917. FuncInfo *funcInfo)
  5918. {
  5919. switch (lhs->nop)
  5920. {
  5921. // assignment to a local or global variable
  5922. case knopVarDecl:
  5923. case knopLetDecl:
  5924. case knopConstDecl:
  5925. {
  5926. Symbol *sym = lhs->AsParseNodeVar()->sym;
  5927. Assert(sym != nullptr);
  5928. byteCodeGenerator->EmitPropStore(rhsLocation, sym, nullptr, funcInfo, lhs->nop == knopLetDecl, lhs->nop == knopConstDecl);
  5929. break;
  5930. }
  5931. case knopName:
  5932. {
  5933. // Special names like 'this' or 'new.target' cannot be assigned to
  5934. ParseNodeName * pnodeNameLhs = lhs->AsParseNodeName();
  5935. if (pnodeNameLhs->IsSpecialName())
  5936. {
  5937. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  5938. }
  5939. else
  5940. {
  5941. byteCodeGenerator->EmitPropStore(rhsLocation, pnodeNameLhs->sym, pnodeNameLhs->pid, funcInfo);
  5942. }
  5943. break;
  5944. }
  5945. // x.y =
  5946. case knopDot:
  5947. {
  5948. // PutValue(x, "y", rhs)
  5949. Js::PropertyId propertyId = lhs->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  5950. if (ByteCodeGenerator::IsSuper(lhs->AsParseNodeBin()->pnode1))
  5951. {
  5952. Emit(lhs->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  5953. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, lhs->AsParseNodeBin()->pnode1->location, funcInfo);
  5954. funcInfo->ReleaseLoc(lhs->AsParseNodeSuperReference()->pnodeThis);
  5955. uint cacheId = funcInfo->FindOrAddInlineCacheId(tmpReg, propertyId, false, true);
  5956. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(Js::OpCode::StSuperFld, rhsLocation, tmpReg, lhs->AsParseNodeSuperReference()->pnodeThis->location, cacheId);
  5957. }
  5958. else
  5959. {
  5960. uint cacheId = funcInfo->FindOrAddInlineCacheId(lhs->AsParseNodeBin()->pnode1->location, propertyId, false, true);
  5961. byteCodeGenerator->Writer()->PatchableProperty(
  5962. ByteCodeGenerator::GetStFldOpCode(funcInfo, false, false, false, false), rhsLocation, lhs->AsParseNodeBin()->pnode1->location, cacheId);
  5963. }
  5964. break;
  5965. }
  5966. case knopIndex:
  5967. {
  5968. Js::RegSlot targetLocation = lhs->AsParseNodeBin()->pnode1->location;
  5969. if (ByteCodeGenerator::IsSuper(lhs->AsParseNodeBin()->pnode1))
  5970. {
  5971. // We need to emit the 'this' node for the super reference even if we aren't planning to use the 'this' value.
  5972. // This is because we might be in a derived class constructor where we haven't yet called super() to bind the 'this' value.
  5973. // See ecma262 abstract operation 'MakeSuperPropertyReference'
  5974. Emit(lhs->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  5975. funcInfo->ReleaseLoc(lhs->AsParseNodeSuperReference()->pnodeThis);
  5976. targetLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, targetLocation, funcInfo);
  5977. }
  5978. byteCodeGenerator->Writer()->Element(
  5979. ByteCodeGenerator::GetStElemIOpCode(funcInfo),
  5980. rhsLocation, targetLocation, lhs->AsParseNodeBin()->pnode2->location);
  5981. break;
  5982. }
  5983. case knopObjectPattern:
  5984. {
  5985. Assert(byteCodeGenerator->IsES6DestructuringEnabled());
  5986. // Copy the rhs value to be the result of the assignment if needed.
  5987. if (asgnNode != nullptr)
  5988. {
  5989. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  5990. }
  5991. return EmitDestructuredObject(lhs, rhsLocation, byteCodeGenerator, funcInfo);
  5992. }
  5993. case knopArrayPattern:
  5994. {
  5995. Assert(byteCodeGenerator->IsES6DestructuringEnabled());
  5996. // Copy the rhs value to be the result of the assignment if needed.
  5997. if (asgnNode != nullptr)
  5998. {
  5999. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  6000. }
  6001. return EmitDestructuredArray(lhs, rhsLocation, byteCodeGenerator, funcInfo);
  6002. }
  6003. case knopArray:
  6004. case knopObject:
  6005. // Assignment to array/object can get through to byte code gen when the parser fails to convert destructuring
  6006. // assignment to pattern (because of structural mismatch between LHS & RHS?). Revisit when we nail
  6007. // down early vs. runtime errors for destructuring.
  6008. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  6009. break;
  6010. default:
  6011. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  6012. break;
  6013. }
  6014. if (asgnNode != nullptr)
  6015. {
  6016. // We leave it up to the caller to pass this node only if the assignment expression is used.
  6017. if (asgnNode->location != rhsLocation)
  6018. {
  6019. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  6020. }
  6021. }
  6022. }
  6023. void EmitLoad(
  6024. ParseNode *lhs,
  6025. ByteCodeGenerator *byteCodeGenerator,
  6026. FuncInfo *funcInfo)
  6027. {
  6028. // Emit the instructions to load the value into the LHS location. Do not assign/free any temps
  6029. // in the process.
  6030. // We usually get here as part of an op-equiv expression: x.y += z;
  6031. // In such a case, x has to be emitted first, then the value of x.y loaded (by this function), then z emitted.
  6032. switch (lhs->nop)
  6033. {
  6034. // load of a local or global variable
  6035. case knopName:
  6036. {
  6037. funcInfo->AcquireLoc(lhs);
  6038. byteCodeGenerator->EmitPropLoad(lhs->location, lhs->AsParseNodeName()->sym, lhs->AsParseNodeName()->pid, funcInfo);
  6039. break;
  6040. }
  6041. // = x.y
  6042. case knopDot:
  6043. {
  6044. // get field id for "y"
  6045. Js::PropertyId propertyId = lhs->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6046. funcInfo->AcquireLoc(lhs);
  6047. EmitReference(lhs, byteCodeGenerator, funcInfo);
  6048. uint cacheId = funcInfo->FindOrAddInlineCacheId(lhs->AsParseNodeBin()->pnode1->location, propertyId, false, false);
  6049. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, lhs->location, lhs->AsParseNodeBin()->pnode1->location, cacheId);
  6050. break;
  6051. }
  6052. case knopIndex:
  6053. funcInfo->AcquireLoc(lhs);
  6054. EmitReference(lhs, byteCodeGenerator, funcInfo);
  6055. byteCodeGenerator->Writer()->Element(
  6056. Js::OpCode::LdElemI_A, lhs->location, lhs->AsParseNodeBin()->pnode1->location, lhs->AsParseNodeBin()->pnode2->location);
  6057. break;
  6058. // f(x) +=
  6059. case knopCall:
  6060. {
  6061. ParseNodeCall * pnodeCallLhs = lhs->AsParseNodeCall();
  6062. if (pnodeCallLhs->pnodeTarget->nop == knopImport)
  6063. {
  6064. ParseNodePtr args = pnodeCallLhs->pnodeArgs;
  6065. Assert(CountArguments(args) == 2); // import() takes one argument
  6066. Emit(args, byteCodeGenerator, funcInfo, false);
  6067. funcInfo->ReleaseLoc(args);
  6068. funcInfo->AcquireLoc(pnodeCallLhs);
  6069. byteCodeGenerator->Writer()->Reg2(Js::OpCode::ImportCall, pnodeCallLhs->location, args->location);
  6070. }
  6071. else
  6072. {
  6073. funcInfo->AcquireLoc(pnodeCallLhs);
  6074. EmitReference(pnodeCallLhs, byteCodeGenerator, funcInfo);
  6075. EmitCall(pnodeCallLhs, byteCodeGenerator, funcInfo, /*fReturnValue=*/ false, /*fEvaluateComponents=*/ false);
  6076. }
  6077. break;
  6078. }
  6079. default:
  6080. funcInfo->AcquireLoc(lhs);
  6081. Emit(lhs, byteCodeGenerator, funcInfo, false);
  6082. break;
  6083. }
  6084. }
  6085. void EmitList(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  6086. {
  6087. if (pnode != nullptr)
  6088. {
  6089. while (pnode->nop == knopList)
  6090. {
  6091. byteCodeGenerator->EmitTopLevelStatement(pnode->AsParseNodeBin()->pnode1, funcInfo, false);
  6092. pnode = pnode->AsParseNodeBin()->pnode2;
  6093. }
  6094. byteCodeGenerator->EmitTopLevelStatement(pnode, funcInfo, false);
  6095. }
  6096. }
  6097. void EmitOneArg(
  6098. ParseNode *pnode,
  6099. BOOL fAssignRegs,
  6100. ByteCodeGenerator *byteCodeGenerator,
  6101. FuncInfo *funcInfo,
  6102. Js::ProfileId callSiteId,
  6103. Js::ArgSlot &argIndex,
  6104. Js::ArgSlot &spreadIndex,
  6105. Js::RegSlot argTempLocation,
  6106. bool emitProfiledArgout,
  6107. Js::AuxArray<uint32> *spreadIndices = nullptr
  6108. )
  6109. {
  6110. bool noArgOuts = argTempLocation != Js::Constants::NoRegister;
  6111. // If this is a put, the arguments have already been evaluated (see EmitReference).
  6112. // We just need to emit the ArgOut instructions.
  6113. if (fAssignRegs)
  6114. {
  6115. Emit(pnode, byteCodeGenerator, funcInfo, false);
  6116. }
  6117. if (pnode->nop == knopEllipsis)
  6118. {
  6119. Assert(spreadIndices != nullptr);
  6120. spreadIndices->elements[spreadIndex++] = argIndex + 1; // account for 'this'
  6121. Js::RegSlot regVal = funcInfo->AcquireTmpRegister();
  6122. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, pnode->location);
  6123. if (noArgOuts)
  6124. {
  6125. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, argTempLocation, regVal);
  6126. }
  6127. else
  6128. {
  6129. byteCodeGenerator->Writer()->ArgOut<true>(argIndex + 1, regVal, callSiteId, emitProfiledArgout);
  6130. }
  6131. funcInfo->ReleaseTmpRegister(regVal);
  6132. }
  6133. else
  6134. {
  6135. if (noArgOuts)
  6136. {
  6137. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, argTempLocation, pnode->location);
  6138. }
  6139. else
  6140. {
  6141. byteCodeGenerator->Writer()->ArgOut<true>(argIndex + 1, pnode->location, callSiteId, emitProfiledArgout);
  6142. }
  6143. }
  6144. argIndex++;
  6145. if (fAssignRegs)
  6146. {
  6147. funcInfo->ReleaseLoc(pnode);
  6148. }
  6149. }
  6150. size_t EmitArgsWithArgOutsAtEnd(
  6151. ParseNode *pnode,
  6152. BOOL fAssignRegs,
  6153. ByteCodeGenerator *byteCodeGenerator,
  6154. FuncInfo *funcInfo,
  6155. Js::ProfileId callSiteId,
  6156. Js::RegSlot thisLocation,
  6157. Js::ArgSlot argsCountForStartCall,
  6158. bool emitProfiledArgouts,
  6159. Js::AuxArray<uint32> *spreadIndices = nullptr
  6160. )
  6161. {
  6162. AssertOrFailFast(pnode != nullptr);
  6163. Js::ArgSlot argIndex = 0;
  6164. Js::ArgSlot spreadIndex = 0;
  6165. Js::RegSlot argTempLocation = funcInfo->AcquireTmpRegister();
  6166. Js::RegSlot firstArgTempLocation = argTempLocation;
  6167. while (pnode->nop == knopList)
  6168. {
  6169. EmitOneArg(pnode->AsParseNodeBin()->pnode1, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, argTempLocation, false /*emitProfiledArgout*/, spreadIndices);
  6170. pnode = pnode->AsParseNodeBin()->pnode2;
  6171. argTempLocation = funcInfo->AcquireTmpRegister();
  6172. }
  6173. EmitOneArg(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, argTempLocation, false /*emitProfiledArgout*/, spreadIndices);
  6174. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argsCountForStartCall);
  6175. // Emit all argOuts now
  6176. if (thisLocation != Js::Constants::NoRegister)
  6177. {
  6178. // Emit the "this" object.
  6179. byteCodeGenerator->Writer()->ArgOut<true>(0, thisLocation, callSiteId, false /*emitProfiledArgouts*/);
  6180. }
  6181. for (Js::ArgSlot index = 0; index < argIndex; index++)
  6182. {
  6183. byteCodeGenerator->Writer()->ArgOut<true>(index + 1, firstArgTempLocation + index, callSiteId, emitProfiledArgouts);
  6184. }
  6185. // Now release all those temps register
  6186. for (Js::ArgSlot index = argIndex; index > 0; index--)
  6187. {
  6188. funcInfo->ReleaseTmpRegister(argTempLocation--);
  6189. }
  6190. return argIndex;
  6191. }
  6192. size_t EmitArgs(
  6193. ParseNode *pnode,
  6194. BOOL fAssignRegs,
  6195. ByteCodeGenerator *byteCodeGenerator,
  6196. FuncInfo *funcInfo,
  6197. Js::ProfileId callSiteId,
  6198. bool emitProfiledArgouts,
  6199. Js::AuxArray<uint32> *spreadIndices = nullptr
  6200. )
  6201. {
  6202. Js::ArgSlot argIndex = 0;
  6203. Js::ArgSlot spreadIndex = 0;
  6204. if (pnode != nullptr)
  6205. {
  6206. while (pnode->nop == knopList)
  6207. {
  6208. EmitOneArg(pnode->AsParseNodeBin()->pnode1, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, Js::Constants::NoRegister, emitProfiledArgouts, spreadIndices);
  6209. pnode = pnode->AsParseNodeBin()->pnode2;
  6210. }
  6211. EmitOneArg(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, argIndex, spreadIndex, Js::Constants::NoRegister, emitProfiledArgouts, spreadIndices);
  6212. }
  6213. return argIndex;
  6214. }
  6215. void EmitArgListStart(
  6216. Js::RegSlot thisLocation,
  6217. ByteCodeGenerator *byteCodeGenerator,
  6218. FuncInfo *funcInfo,
  6219. Js::ProfileId callSiteId)
  6220. {
  6221. if (thisLocation != Js::Constants::NoRegister)
  6222. {
  6223. // Emit the "this" object.
  6224. byteCodeGenerator->Writer()->ArgOut<true>(0, thisLocation, callSiteId, false /*emitProfiledArgout*/);
  6225. }
  6226. }
  6227. Js::ArgSlot EmitArgListEnd(
  6228. ParseNode *pnode,
  6229. Js::RegSlot thisLocation,
  6230. Js::RegSlot evalLocation,
  6231. Js::RegSlot newTargetLocation,
  6232. ByteCodeGenerator *byteCodeGenerator,
  6233. FuncInfo *funcInfo,
  6234. size_t argIndex,
  6235. Js::ProfileId callSiteId)
  6236. {
  6237. BOOL fEvalInModule = false;
  6238. BOOL fIsEval = (evalLocation != Js::Constants::NoRegister);
  6239. BOOL fHasNewTarget = (newTargetLocation != Js::Constants::NoRegister);
  6240. static const size_t maxExtraArgSlot = 4; // max(extraEvalArg, extraArg), where extraEvalArg==2 (moduleRoot,env), extraArg==4 (this, eval, evalInModule, newTarget)
  6241. AssertOrFailFastMsg(argIndex < Js::Constants::UShortMaxValue - maxExtraArgSlot, "Number of allowed arguments are already capped at parser level");
  6242. Js::ArgSlot argSlotIndex = (Js::ArgSlot) argIndex;
  6243. Js::ArgSlot evalIndex;
  6244. if (fIsEval && argSlotIndex > 0)
  6245. {
  6246. Assert(!fHasNewTarget);
  6247. // Pass the frame display as an extra argument to "eval".
  6248. // Do this only if eval is called with some args
  6249. Js::RegSlot evalEnv;
  6250. if (funcInfo->IsGlobalFunction() && !(funcInfo->GetIsStrictMode() && byteCodeGenerator->GetFlags() & fscrEval))
  6251. {
  6252. // Use current environment as the environment for the function being called when:
  6253. // - this is the root global function (not an eval's global function)
  6254. // - this is an eval's global function that is not in strict mode (see else block)
  6255. evalEnv = funcInfo->GetEnvRegister();
  6256. }
  6257. else
  6258. {
  6259. // Use the frame display as the environment for the function being called when:
  6260. // - this is not a global function and thus it will have its own scope
  6261. // - this is an eval's global function that is in strict mode, since in strict mode the eval's global function
  6262. // has its own scope
  6263. evalEnv = funcInfo->frameDisplayRegister;
  6264. }
  6265. evalEnv = byteCodeGenerator->PrependLocalScopes(evalEnv, evalLocation, funcInfo);
  6266. // Passing the FrameDisplay as an extra argument
  6267. evalIndex = argSlotIndex + 1;
  6268. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  6269. {
  6270. byteCodeGenerator->Writer()->ArgOutEnv(evalIndex);
  6271. }
  6272. else
  6273. {
  6274. byteCodeGenerator->Writer()->ArgOut<false>(evalIndex, evalEnv, callSiteId, false /*emitProfiledArgout*/);
  6275. }
  6276. }
  6277. if (fHasNewTarget)
  6278. {
  6279. Assert(!fIsEval);
  6280. byteCodeGenerator->Writer()->ArgOut<true>(argSlotIndex + 1, newTargetLocation, callSiteId, false /*emitProfiledArgout*/);
  6281. }
  6282. Js::ArgSlot argIntCount = argSlotIndex + 1 + (Js::ArgSlot)fIsEval + (Js::ArgSlot)fEvalInModule + (Js::ArgSlot)fHasNewTarget;
  6283. // eval and no args passed, return 1 as argument count
  6284. if (fIsEval && pnode == nullptr)
  6285. {
  6286. return 1;
  6287. }
  6288. return argIntCount;
  6289. }
  6290. Js::ArgSlot EmitArgList(
  6291. ParseNode *pnode,
  6292. Js::RegSlot thisLocation,
  6293. Js::RegSlot newTargetLocation,
  6294. BOOL fIsEval,
  6295. BOOL fAssignRegs,
  6296. ByteCodeGenerator *byteCodeGenerator,
  6297. FuncInfo *funcInfo,
  6298. Js::ProfileId callSiteId,
  6299. Js::ArgSlot argsCountForStartCall,
  6300. bool emitArgOutsAtEnd,
  6301. bool emitProfiledArgouts,
  6302. uint16 spreadArgCount = 0,
  6303. Js::AuxArray<uint32> **spreadIndices = nullptr)
  6304. {
  6305. // This function emits the arguments for a call.
  6306. // ArgOut's with uses immediately following defs.
  6307. if (!emitArgOutsAtEnd)
  6308. {
  6309. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argsCountForStartCall);
  6310. EmitArgListStart(thisLocation, byteCodeGenerator, funcInfo, callSiteId);
  6311. }
  6312. Js::RegSlot evalLocation = Js::Constants::NoRegister;
  6313. //
  6314. // If Emitting arguments for eval and assigning registers, get a tmpLocation for eval.
  6315. // This would be used while generating frameDisplay in EmitArgListEnd.
  6316. //
  6317. if (fIsEval)
  6318. {
  6319. evalLocation = funcInfo->AcquireTmpRegister();
  6320. }
  6321. if (spreadArgCount > 0)
  6322. {
  6323. const size_t extraAlloc = UInt32Math::Mul(spreadArgCount, sizeof(uint32));
  6324. Assert(spreadIndices != nullptr);
  6325. *spreadIndices = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<uint32>, spreadArgCount);
  6326. }
  6327. size_t argIndex = 0;
  6328. if (emitArgOutsAtEnd)
  6329. {
  6330. argIndex = EmitArgsWithArgOutsAtEnd(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, thisLocation, argsCountForStartCall, emitProfiledArgouts, spreadIndices == nullptr ? nullptr : *spreadIndices);
  6331. }
  6332. else
  6333. {
  6334. argIndex = EmitArgs(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, emitProfiledArgouts, spreadIndices == nullptr ? nullptr : *spreadIndices);
  6335. }
  6336. Js::ArgSlot argumentsCount = EmitArgListEnd(pnode, thisLocation, evalLocation, newTargetLocation, byteCodeGenerator, funcInfo, argIndex, callSiteId);
  6337. if (fIsEval)
  6338. {
  6339. funcInfo->ReleaseTmpRegister(evalLocation);
  6340. }
  6341. return argumentsCount;
  6342. }
  6343. void EmitConstantArgsToVarArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) Js::Var *vars, ParseNode *args, uint argCount)
  6344. {
  6345. uint index = 0;
  6346. while (args->nop == knopList && index < argCount)
  6347. {
  6348. if (args->AsParseNodeBin()->pnode1->nop == knopInt)
  6349. {
  6350. int value = args->AsParseNodeBin()->pnode1->AsParseNodeInt()->lw;
  6351. vars[index++] = Js::TaggedInt::ToVarUnchecked(value);
  6352. }
  6353. else if (args->AsParseNodeBin()->pnode1->nop == knopFlt)
  6354. {
  6355. Js::Var number = Js::JavascriptNumber::New(args->AsParseNodeBin()->pnode1->AsParseNodeFloat()->dbl, byteCodeGenerator->GetScriptContext());
  6356. #if ! FLOATVAR
  6357. byteCodeGenerator->GetScriptContext()->BindReference(number);
  6358. #endif
  6359. vars[index++] = number;
  6360. }
  6361. else
  6362. {
  6363. AnalysisAssert(false);
  6364. }
  6365. args = args->AsParseNodeBin()->pnode2;
  6366. }
  6367. if (index == argCount)
  6368. {
  6369. Assert(false);
  6370. Js::Throw::InternalError();
  6371. return;
  6372. }
  6373. if (args->nop == knopInt)
  6374. {
  6375. int value = args->AsParseNodeInt()->lw;
  6376. vars[index++] = Js::TaggedInt::ToVarUnchecked(value);
  6377. }
  6378. else if (args->nop == knopFlt)
  6379. {
  6380. Js::Var number = Js::JavascriptNumber::New(args->AsParseNodeFloat()->dbl, byteCodeGenerator->GetScriptContext());
  6381. #if ! FLOATVAR
  6382. byteCodeGenerator->GetScriptContext()->BindReference(number);
  6383. #endif
  6384. vars[index++] = number;
  6385. }
  6386. else
  6387. {
  6388. AnalysisAssert(false);
  6389. }
  6390. }
  6391. void EmitConstantArgsToIntArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) int32 *vars, ParseNode *args, uint argCount)
  6392. {
  6393. uint index = 0;
  6394. while (args->nop == knopList && index < argCount)
  6395. {
  6396. Assert(args->AsParseNodeBin()->pnode1->nop == knopInt);
  6397. vars[index++] = args->AsParseNodeBin()->pnode1->AsParseNodeInt()->lw;
  6398. args = args->AsParseNodeBin()->pnode2;
  6399. }
  6400. if (index >= argCount)
  6401. {
  6402. Js::Throw::InternalError();
  6403. return;
  6404. }
  6405. Assert(args->nop == knopInt);
  6406. vars[index++] = args->AsParseNodeInt()->lw;
  6407. Assert(index == argCount);
  6408. }
  6409. void EmitConstantArgsToFltArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) double *vars, ParseNode *args, uint argCount)
  6410. {
  6411. uint index = 0;
  6412. while (args->nop == knopList && index < argCount)
  6413. {
  6414. OpCode nop = args->AsParseNodeBin()->pnode1->nop;
  6415. if (nop == knopInt)
  6416. {
  6417. vars[index++] = (double)args->AsParseNodeBin()->pnode1->AsParseNodeInt()->lw;
  6418. }
  6419. else
  6420. {
  6421. Assert(nop == knopFlt);
  6422. vars[index++] = args->AsParseNodeBin()->pnode1->AsParseNodeFloat()->dbl;
  6423. }
  6424. args = args->AsParseNodeBin()->pnode2;
  6425. }
  6426. if (index >= argCount)
  6427. {
  6428. Js::Throw::InternalError();
  6429. return;
  6430. }
  6431. if (args->nop == knopInt)
  6432. {
  6433. vars[index++] = (double)args->AsParseNodeInt()->lw;
  6434. }
  6435. else
  6436. {
  6437. Assert(args->nop == knopFlt);
  6438. vars[index++] = args->AsParseNodeFloat()->dbl;
  6439. }
  6440. Assert(index == argCount);
  6441. }
  6442. //
  6443. // Called when we have new Ctr(constant, constant...)
  6444. //
  6445. Js::ArgSlot EmitNewObjectOfConstants(
  6446. ParseNode *pnode,
  6447. ByteCodeGenerator *byteCodeGenerator,
  6448. FuncInfo *funcInfo,
  6449. unsigned int argCount)
  6450. {
  6451. EmitArgListStart(Js::Constants::NoRegister, byteCodeGenerator, funcInfo, Js::Constants::NoProfileId);
  6452. // Create the vars array
  6453. Js::VarArrayVarCount *vars = AnewPlus(byteCodeGenerator->GetAllocator(), UInt32Math::Mul((argCount - 1), sizeof(Js::Var)), Js::VarArrayVarCount, Js::TaggedInt::ToVarUnchecked(argCount - 1));
  6454. // Emit all constants to the vars array
  6455. EmitConstantArgsToVarArray(byteCodeGenerator, vars->elements, pnode->AsParseNodeCall()->pnodeArgs, argCount - 1);
  6456. // Finish the arg list
  6457. Js::ArgSlot actualArgCount = EmitArgListEnd(
  6458. pnode->AsParseNodeCall()->pnodeArgs,
  6459. Js::Constants::NoRegister,
  6460. Js::Constants::NoRegister,
  6461. Js::Constants::NoRegister,
  6462. byteCodeGenerator,
  6463. funcInfo,
  6464. argCount - 1,
  6465. Js::Constants::NoProfileId);
  6466. // Make sure the cacheId to regSlot map in the ByteCodeWriter is left in a consistent state after writing NewScObject_A
  6467. byteCodeGenerator->Writer()->RemoveEntryForRegSlotFromCacheIdMap(pnode->AsParseNodeCall()->pnodeTarget->location);
  6468. // Generate the opcode with vars
  6469. byteCodeGenerator->Writer()->AuxiliaryContext(
  6470. Js::OpCode::NewScObject_A,
  6471. funcInfo->AcquireLoc(pnode),
  6472. vars,
  6473. UInt32Math::MulAdd<sizeof(Js::Var), sizeof(Js::VarArray)>((argCount-1)),
  6474. pnode->AsParseNodeCall()->pnodeTarget->location);
  6475. AdeletePlus(byteCodeGenerator->GetAllocator(), UInt32Math::Mul((argCount-1), sizeof(Js::VarArrayVarCount)), vars);
  6476. return actualArgCount;
  6477. }
  6478. void EmitMethodFld(bool isRoot, bool isScoped, Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, bool registerCacheIdForCall = true)
  6479. {
  6480. Js::OpCode opcode;
  6481. if (!isRoot)
  6482. {
  6483. if (callObjLocation == funcInfo->frameObjRegister)
  6484. {
  6485. opcode = Js::OpCode::LdLocalMethodFld;
  6486. }
  6487. else
  6488. {
  6489. opcode = Js::OpCode::LdMethodFld;
  6490. }
  6491. }
  6492. else if (isScoped)
  6493. {
  6494. opcode = Js::OpCode::ScopedLdMethodFld;
  6495. }
  6496. else
  6497. {
  6498. opcode = Js::OpCode::LdRootMethodFld;
  6499. }
  6500. if (isScoped || !isRoot)
  6501. {
  6502. Assert(isScoped || !isRoot || callObjLocation == ByteCodeGenerator::RootObjectRegister);
  6503. uint cacheId = funcInfo->FindOrAddInlineCacheId(callObjLocation, propertyId, true, false);
  6504. if (callObjLocation == funcInfo->frameObjRegister)
  6505. {
  6506. byteCodeGenerator->Writer()->ElementP(opcode, location, cacheId, false /*isCtor*/, registerCacheIdForCall);
  6507. }
  6508. else
  6509. {
  6510. byteCodeGenerator->Writer()->PatchableProperty(opcode, location, callObjLocation, cacheId, false /*isCtor*/, registerCacheIdForCall);
  6511. }
  6512. }
  6513. else
  6514. {
  6515. uint cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, true, false);
  6516. byteCodeGenerator->Writer()->PatchableRootProperty(opcode, location, cacheId, true, false, registerCacheIdForCall);
  6517. }
  6518. }
  6519. void EmitMethodFld(ParseNode *pnode, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, bool registerCacheIdForCall = true)
  6520. {
  6521. // Load a call target of the form x.y(). (Call target may be a plain knopName if we're getting it from
  6522. // the global object, etc.)
  6523. bool isRoot = pnode->nop == knopName && (pnode->AsParseNodeName()->sym == nullptr || pnode->AsParseNodeName()->sym->GetIsGlobal());
  6524. bool isScoped = (byteCodeGenerator->GetFlags() & fscrEval) != 0 ||
  6525. (isRoot && callObjLocation != ByteCodeGenerator::RootObjectRegister);
  6526. EmitMethodFld(isRoot, isScoped, pnode->location, callObjLocation, propertyId, byteCodeGenerator, funcInfo, registerCacheIdForCall);
  6527. }
  6528. // lhs.apply(this, arguments);
  6529. void EmitApplyCall(ParseNodeCall* pnodeCall, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue)
  6530. {
  6531. ParseNode* applyNode = pnodeCall->pnodeTarget;
  6532. ParseNode* thisNode = pnodeCall->pnodeArgs->AsParseNodeBin()->pnode1;
  6533. Assert(applyNode->nop == knopDot);
  6534. ParseNode* funcNode = applyNode->AsParseNodeBin()->pnode1;
  6535. Js::ByteCodeLabel slowPath = byteCodeGenerator->Writer()->DefineLabel();
  6536. Js::ByteCodeLabel afterSlowPath = byteCodeGenerator->Writer()->DefineLabel();
  6537. Js::ByteCodeLabel argsAlreadyCreated = byteCodeGenerator->Writer()->DefineLabel();
  6538. Assert(applyNode->nop == knopDot);
  6539. Emit(funcNode, byteCodeGenerator, funcInfo, false);
  6540. funcInfo->AcquireLoc(applyNode);
  6541. Js::PropertyId propertyId = applyNode->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6542. // As we won't be emitting a call instruction for apply, no need to register the cacheId for apply
  6543. // load to be associated with the call. This is also required, as in the absence of a corresponding
  6544. // call for apply, we won't remove the entry for "apply" cacheId from
  6545. // ByteCodeWriter::callRegToLdFldCacheIndexMap, which is contrary to our assumption that we would
  6546. // have removed an entry from a map upon seeing its corresponding call.
  6547. EmitMethodFld(applyNode, funcNode->location, propertyId, byteCodeGenerator, funcInfo, false /*registerCacheIdForCall*/);
  6548. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  6549. Assert(argSym && argSym->IsArguments());
  6550. Js::RegSlot argumentsLoc = argSym->GetLocation();
  6551. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdArgumentsFromFrame, argumentsLoc);
  6552. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrNotNull_A, argsAlreadyCreated, argumentsLoc);
  6553. // If apply is overridden, bail to slow path.
  6554. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFncNeqApply, slowPath, applyNode->location);
  6555. // Note: acquire and release a temp register for this stack arg pointer instead of trying to stash it
  6556. // in funcInfo->stackArgReg. Otherwise, we'll needlessly load and store it in jitted loop bodies and
  6557. // may crash if we try to unbox it on the store.
  6558. Js::RegSlot stackArgReg = funcInfo->AcquireTmpRegister();
  6559. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdStackArgPtr, stackArgReg);
  6560. Js::RegSlot argCountLocation = funcInfo->AcquireTmpRegister();
  6561. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdArgCnt, argCountLocation);
  6562. byteCodeGenerator->Writer()->Reg5(Js::OpCode::ApplyArgs, funcNode->location, funcNode->location, thisNode->location, stackArgReg, argCountLocation);
  6563. funcInfo->ReleaseTmpRegister(argCountLocation);
  6564. funcInfo->ReleaseTmpRegister(stackArgReg);
  6565. funcInfo->ReleaseLoc(applyNode);
  6566. funcInfo->ReleaseLoc(funcNode);
  6567. // Clear these nodes as they are going to be used to re-generate the slow path.
  6568. VisitClearTmpRegs(applyNode, byteCodeGenerator, funcInfo);
  6569. VisitClearTmpRegs(funcNode, byteCodeGenerator, funcInfo);
  6570. byteCodeGenerator->Writer()->Br(afterSlowPath);
  6571. // slow path
  6572. byteCodeGenerator->Writer()->MarkLabel(slowPath);
  6573. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  6574. {
  6575. byteCodeGenerator->EmitScopeObjectInit(funcInfo);
  6576. }
  6577. byteCodeGenerator->LoadHeapArguments(funcInfo);
  6578. byteCodeGenerator->Writer()->MarkLabel(argsAlreadyCreated);
  6579. EmitCall(pnodeCall, byteCodeGenerator, funcInfo, fReturnValue, /*fEvaluateComponents*/true);
  6580. byteCodeGenerator->Writer()->MarkLabel(afterSlowPath);
  6581. }
  6582. void EmitMethodElem(ParseNode *pnode, Js::RegSlot callObjLocation, Js::RegSlot indexLocation, ByteCodeGenerator *byteCodeGenerator)
  6583. {
  6584. // Load a call target of the form x[y]().
  6585. byteCodeGenerator->Writer()->Element(Js::OpCode::LdMethodElem, pnode->location, callObjLocation, indexLocation);
  6586. }
  6587. void EmitCallTargetNoEvalComponents(
  6588. ParseNode *pnodeTarget,
  6589. BOOL fSideEffectArgs,
  6590. Js::RegSlot *thisLocation,
  6591. bool *releaseThisLocation,
  6592. Js::RegSlot *callObjLocation,
  6593. ByteCodeGenerator *byteCodeGenerator,
  6594. FuncInfo *funcInfo)
  6595. {
  6596. // We first get a reference to the call target, then evaluate the arguments, then
  6597. // evaluate the call target.
  6598. // - emit reference to target
  6599. // - copy instance to scratch reg if necessary.
  6600. // - assign this
  6601. // - assign instance for dynamic/global name
  6602. // - emit args
  6603. // - do call (CallFld/Elem/I)
  6604. *releaseThisLocation = true;
  6605. switch (pnodeTarget->nop)
  6606. {
  6607. case knopDot:
  6608. *thisLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6609. *callObjLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6610. break;
  6611. case knopIndex:
  6612. *thisLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6613. *callObjLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6614. break;
  6615. case knopName:
  6616. // If the call target is a name, do some extra work to get its instance and the "this" pointer.
  6617. byteCodeGenerator->EmitLoadInstance(pnodeTarget->AsParseNodeName()->sym, pnodeTarget->AsParseNodeName()->pid, thisLocation, callObjLocation, funcInfo);
  6618. if (*thisLocation == Js::Constants::NoRegister)
  6619. {
  6620. *thisLocation = funcInfo->undefinedConstantRegister;
  6621. }
  6622. break;
  6623. default:
  6624. *thisLocation = funcInfo->undefinedConstantRegister;
  6625. break;
  6626. }
  6627. }
  6628. void EmitCallTarget(
  6629. ParseNode *pnodeTarget,
  6630. BOOL fSideEffectArgs,
  6631. Js::RegSlot *thisLocation,
  6632. bool *releaseThisLocation,
  6633. Js::RegSlot *callObjLocation,
  6634. ByteCodeGenerator *byteCodeGenerator,
  6635. FuncInfo *funcInfo)
  6636. {
  6637. // - emit target
  6638. // - assign this
  6639. // - emit args
  6640. // - do call
  6641. // The call target is fully evaluated before the argument list. Note that we're not handling
  6642. // put-call cases here currently, as such cases only apply to host objects
  6643. // and are very unlikely to behave differently depending on the order of evaluation.
  6644. *releaseThisLocation = true;
  6645. switch (pnodeTarget->nop)
  6646. {
  6647. case knopDot:
  6648. {
  6649. ParseNodeBin * pnodeBinTarget = pnodeTarget->AsParseNodeBin();
  6650. funcInfo->AcquireLoc(pnodeBinTarget);
  6651. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6652. // them from side-effects.
  6653. if (fSideEffectArgs)
  6654. {
  6655. // Though we're done with target evaluation after this point, still protect opnd1 from
  6656. // arg side-effects as it's the "this" pointer.
  6657. SaveOpndValue(pnodeBinTarget->pnode1, funcInfo);
  6658. }
  6659. Assert(pnodeBinTarget->pnode2->nop == knopName);
  6660. if ((pnodeBinTarget->pnode2->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::apply) || (pnodeTarget->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode() == Js::PropertyIds::call))
  6661. {
  6662. pnodeBinTarget->pnode1->SetIsCallApplyTargetLoad();
  6663. }
  6664. Emit(pnodeBinTarget->pnode1, byteCodeGenerator, funcInfo, false);
  6665. Js::PropertyId propertyId = pnodeBinTarget->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6666. Js::RegSlot protoLocation = pnodeBinTarget->pnode1->location;
  6667. if (ByteCodeGenerator::IsSuper(pnodeBinTarget->pnode1))
  6668. {
  6669. Emit(pnodeBinTarget->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  6670. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, protoLocation, funcInfo);
  6671. funcInfo->ReleaseLoc(pnodeBinTarget->AsParseNodeSuperReference()->pnodeThis);
  6672. funcInfo->ReleaseLoc(pnodeBinTarget->pnode1);
  6673. // Function calls on the 'super' object should maintain current 'this' pointer
  6674. *thisLocation = pnodeBinTarget->AsParseNodeSuperReference()->pnodeThis->location;
  6675. *releaseThisLocation = false;
  6676. }
  6677. else
  6678. {
  6679. *thisLocation = pnodeBinTarget->pnode1->location;
  6680. }
  6681. EmitMethodFld(pnodeBinTarget, protoLocation, propertyId, byteCodeGenerator, funcInfo);
  6682. break;
  6683. }
  6684. case knopIndex:
  6685. {
  6686. funcInfo->AcquireLoc(pnodeTarget);
  6687. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6688. // them from side-effects.
  6689. if (fSideEffectArgs || !(ParseNode::Grfnop(pnodeTarget->AsParseNodeBin()->pnode2->nop) & fnopLeaf))
  6690. {
  6691. // Though we're done with target evaluation after this point, still protect opnd1 from
  6692. // arg or opnd2 side-effects as it's the "this" pointer.
  6693. SaveOpndValue(pnodeTarget->AsParseNodeBin()->pnode1, funcInfo);
  6694. }
  6695. Emit(pnodeTarget->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  6696. Emit(pnodeTarget->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo, false);
  6697. Js::RegSlot indexLocation = pnodeTarget->AsParseNodeBin()->pnode2->location;
  6698. Js::RegSlot protoLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6699. if (ByteCodeGenerator::IsSuper(pnodeTarget->AsParseNodeBin()->pnode1))
  6700. {
  6701. Emit(pnodeTarget->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  6702. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, protoLocation, funcInfo);
  6703. funcInfo->ReleaseLoc(pnodeTarget->AsParseNodeSuperReference()->pnodeThis);
  6704. // Function calls on the 'super' object should maintain current 'this' pointer
  6705. *thisLocation = pnodeTarget->AsParseNodeSuperReference()->pnodeThis->location;
  6706. *releaseThisLocation = false;
  6707. }
  6708. else
  6709. {
  6710. *thisLocation = pnodeTarget->AsParseNodeBin()->pnode1->location;
  6711. }
  6712. EmitMethodElem(pnodeTarget, protoLocation, indexLocation, byteCodeGenerator);
  6713. funcInfo->ReleaseLoc(pnodeTarget->AsParseNodeBin()->pnode2); // don't release indexLocation until after we use it.
  6714. if (ByteCodeGenerator::IsSuper(pnodeTarget->AsParseNodeBin()->pnode1))
  6715. {
  6716. funcInfo->ReleaseLoc(pnodeTarget->AsParseNodeBin()->pnode1);
  6717. }
  6718. break;
  6719. }
  6720. case knopName:
  6721. {
  6722. ParseNodeName * pnodeNameTarget = pnodeTarget->AsParseNodeName();
  6723. if (!pnodeNameTarget->IsSpecialName())
  6724. {
  6725. funcInfo->AcquireLoc(pnodeNameTarget);
  6726. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6727. // them from side-effects.
  6728. if (fSideEffectArgs)
  6729. {
  6730. SaveOpndValue(pnodeNameTarget, funcInfo);
  6731. }
  6732. byteCodeGenerator->EmitLoadInstance(pnodeNameTarget->sym, pnodeNameTarget->pid, thisLocation, callObjLocation, funcInfo);
  6733. if (*callObjLocation != Js::Constants::NoRegister)
  6734. {
  6735. // Load the call target as a property of the instance.
  6736. Js::PropertyId propertyId = pnodeNameTarget->PropertyIdFromNameNode();
  6737. EmitMethodFld(pnodeNameTarget, *callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6738. break;
  6739. }
  6740. }
  6741. // FALL THROUGH to evaluate call target.
  6742. }
  6743. default:
  6744. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6745. // them from side-effects.
  6746. Emit(pnodeTarget, byteCodeGenerator, funcInfo, false);
  6747. *thisLocation = funcInfo->undefinedConstantRegister;
  6748. break;
  6749. }
  6750. // "This" pointer should have been assigned by the above.
  6751. Assert(*thisLocation != Js::Constants::NoRegister);
  6752. }
  6753. void EmitCallI(
  6754. ParseNodeCall *pnodeCall,
  6755. BOOL fEvaluateComponents,
  6756. BOOL fIsEval,
  6757. BOOL fHasNewTarget,
  6758. uint32 actualArgCount,
  6759. ByteCodeGenerator *byteCodeGenerator,
  6760. FuncInfo *funcInfo,
  6761. Js::ProfileId callSiteId,
  6762. Js::AuxArray<uint32> *spreadIndices = nullptr)
  6763. {
  6764. // Emit a call where the target is in a register, because it's either a local name or an expression we've
  6765. // already evaluated.
  6766. ParseNode *pnodeTarget = pnodeCall->pnodeTarget;
  6767. Js::OpCode op;
  6768. Js::CallFlags callFlags = Js::CallFlags::CallFlags_None;
  6769. uint spreadExtraAlloc = 0;
  6770. bool isSuperCall = pnodeCall->isSuperCall;
  6771. Js::ArgSlot actualArgSlotCount = (Js::ArgSlot) actualArgCount;
  6772. // check for integer overflow
  6773. if ((size_t)actualArgSlotCount != actualArgCount)
  6774. {
  6775. Js::Throw::OutOfMemory();
  6776. }
  6777. if (fEvaluateComponents && !isSuperCall)
  6778. {
  6779. // Release the call target operands we assigned above. If we didn't assign them here,
  6780. // we'll need them later, so we can't re-use them for the result of the call.
  6781. funcInfo->ReleaseLoc(pnodeTarget);
  6782. }
  6783. // Grab a register for the call result.
  6784. if (pnodeCall->isUsed)
  6785. {
  6786. funcInfo->AcquireLoc(pnodeCall);
  6787. }
  6788. if (fIsEval)
  6789. {
  6790. op = Js::OpCode::CallIExtendedFlags;
  6791. callFlags = Js::CallFlags::CallFlags_ExtraArg;
  6792. }
  6793. else
  6794. {
  6795. if (isSuperCall)
  6796. {
  6797. callFlags = Js::CallFlags_New;
  6798. }
  6799. if (fHasNewTarget)
  6800. {
  6801. callFlags = (Js::CallFlags) (callFlags | Js::CallFlags::CallFlags_ExtraArg | Js::CallFlags::CallFlags_NewTarget);
  6802. }
  6803. if (pnodeCall->spreadArgCount > 0)
  6804. {
  6805. op = (isSuperCall || fHasNewTarget) ? Js::OpCode::CallIExtendedFlags : Js::OpCode::CallIExtended;
  6806. }
  6807. else
  6808. {
  6809. op = (isSuperCall || fHasNewTarget) ? Js::OpCode::CallIFlags : Js::OpCode::CallI;
  6810. }
  6811. }
  6812. if (op == Js::OpCode::CallI || op == Js::OpCode::CallIFlags)
  6813. {
  6814. if (isSuperCall)
  6815. {
  6816. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdFuncObjProto, pnodeTarget->location, funcInfo);
  6817. byteCodeGenerator->Writer()->CallI(op, pnodeCall->location, tmpReg, actualArgSlotCount, callSiteId, callFlags);
  6818. }
  6819. else
  6820. {
  6821. byteCodeGenerator->Writer()->CallI(op, pnodeCall->location, pnodeTarget->location, actualArgSlotCount, callSiteId, callFlags);
  6822. }
  6823. }
  6824. else
  6825. {
  6826. uint spreadIndicesSize = 0;
  6827. Js::CallIExtendedOptions options = Js::CallIExtended_None;
  6828. if (pnodeCall->spreadArgCount > 0)
  6829. {
  6830. Assert(spreadIndices != nullptr);
  6831. spreadExtraAlloc = UInt32Math::Mul(spreadIndices->count, sizeof(uint32));
  6832. spreadIndicesSize = UInt32Math::Add(sizeof(*spreadIndices), spreadExtraAlloc);
  6833. options = Js::CallIExtended_SpreadArgs;
  6834. }
  6835. if (isSuperCall)
  6836. {
  6837. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdFuncObjProto, pnodeTarget->location, funcInfo);
  6838. byteCodeGenerator->Writer()->CallIExtended(op, pnodeCall->location, tmpReg, actualArgSlotCount, options, spreadIndices, spreadIndicesSize, callSiteId, callFlags);
  6839. }
  6840. else
  6841. {
  6842. byteCodeGenerator->Writer()->CallIExtended(op, pnodeCall->location, pnodeTarget->location, actualArgSlotCount, options, spreadIndices, spreadIndicesSize, callSiteId, callFlags);
  6843. }
  6844. }
  6845. if (pnodeCall->spreadArgCount > 0)
  6846. {
  6847. Assert(spreadExtraAlloc != 0);
  6848. AdeletePlus(byteCodeGenerator->GetAllocator(), spreadExtraAlloc, spreadIndices);
  6849. }
  6850. }
  6851. void EmitCallInstrNoEvalComponents(
  6852. ParseNodeCall *pnodeCall,
  6853. BOOL fIsEval,
  6854. Js::RegSlot thisLocation,
  6855. Js::RegSlot callObjLocation,
  6856. uint32 actualArgCount,
  6857. ByteCodeGenerator *byteCodeGenerator,
  6858. FuncInfo *funcInfo,
  6859. Js::ProfileId callSiteId,
  6860. Js::AuxArray<uint32> *spreadIndices = nullptr)
  6861. {
  6862. // Emit the call instruction. The call target is a reference at this point, and we evaluate
  6863. // it as part of doing the actual call.
  6864. // Note that we don't handle the (fEvaluateComponents == TRUE) case in this function.
  6865. // (This function is only called on the !fEvaluateComponents branch in EmitCall.)
  6866. ParseNode *pnodeTarget = pnodeCall->pnodeTarget;
  6867. switch (pnodeTarget->nop)
  6868. {
  6869. case knopDot:
  6870. {
  6871. Assert(pnodeTarget->AsParseNodeBin()->pnode2->nop == knopName);
  6872. Js::PropertyId propertyId = pnodeTarget->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  6873. EmitMethodFld(pnodeTarget, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6874. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6875. }
  6876. break;
  6877. case knopIndex:
  6878. {
  6879. EmitMethodElem(pnodeTarget, pnodeTarget->AsParseNodeBin()->pnode1->location, pnodeTarget->AsParseNodeBin()->pnode2->location, byteCodeGenerator);
  6880. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6881. }
  6882. break;
  6883. case knopName:
  6884. {
  6885. if (callObjLocation != Js::Constants::NoRegister)
  6886. {
  6887. // We still have to get the property from its instance, so emit CallFld.
  6888. if (thisLocation != callObjLocation)
  6889. {
  6890. funcInfo->ReleaseTmpRegister(thisLocation);
  6891. }
  6892. funcInfo->ReleaseTmpRegister(callObjLocation);
  6893. Js::PropertyId propertyId = pnodeTarget->AsParseNodeName()->PropertyIdFromNameNode();
  6894. EmitMethodFld(pnodeTarget, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6895. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6896. break;
  6897. }
  6898. }
  6899. // FALL THROUGH
  6900. default:
  6901. EmitCallI(pnodeCall, /*fEvaluateComponents*/ FALSE, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6902. break;
  6903. }
  6904. }
  6905. void EmitCallInstr(
  6906. ParseNodeCall *pnodeCall,
  6907. BOOL fIsEval,
  6908. BOOL fHasNewTarget,
  6909. Js::RegSlot thisLocation,
  6910. Js::RegSlot callObjLocation,
  6911. uint32 actualArgCount,
  6912. ByteCodeGenerator *byteCodeGenerator,
  6913. FuncInfo *funcInfo,
  6914. Js::ProfileId callSiteId,
  6915. Js::AuxArray<uint32> *spreadIndices = nullptr)
  6916. {
  6917. // Emit a call instruction. The call target has been fully evaluated already, so we always
  6918. // emit a CallI through the register that holds the target value.
  6919. // Note that we don't handle !fEvaluateComponents cases at this point.
  6920. // (This function is only called on the fEvaluateComponents branch in EmitCall.)
  6921. if (thisLocation != Js::Constants::NoRegister)
  6922. {
  6923. funcInfo->ReleaseTmpRegister(thisLocation);
  6924. }
  6925. if (callObjLocation != Js::Constants::NoRegister &&
  6926. callObjLocation != thisLocation)
  6927. {
  6928. funcInfo->ReleaseTmpRegister(callObjLocation);
  6929. }
  6930. EmitCallI(pnodeCall, /*fEvaluateComponents*/ TRUE, fIsEval, fHasNewTarget, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6931. }
  6932. void EmitNew(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  6933. {
  6934. Js::ArgSlot argCount = pnode->AsParseNodeCall()->argCount;
  6935. argCount++; // include "this"
  6936. BOOL fSideEffectArgs = FALSE;
  6937. unsigned int tmpCount = CountArguments(pnode->AsParseNodeCall()->pnodeArgs, &fSideEffectArgs);
  6938. AssertOrFailFastMsg(argCount == tmpCount, "argCount cannot overflow as max args capped at parser level");
  6939. byteCodeGenerator->StartStatement(pnode);
  6940. // Start call, allocate out param space
  6941. funcInfo->StartRecordingOutArgs(argCount);
  6942. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6943. // them from side-effects.
  6944. if (fSideEffectArgs)
  6945. {
  6946. SaveOpndValue(pnode->AsParseNodeCall()->pnodeTarget, funcInfo);
  6947. }
  6948. Emit(pnode->AsParseNodeCall()->pnodeTarget, byteCodeGenerator, funcInfo, false, true);
  6949. if (pnode->AsParseNodeCall()->pnodeArgs == nullptr)
  6950. {
  6951. funcInfo->ReleaseLoc(pnode->AsParseNodeCall()->pnodeTarget);
  6952. Js::OpCode op = (CreateNativeArrays(byteCodeGenerator, funcInfo)
  6953. && CallTargetIsArray(pnode->AsParseNodeCall()->pnodeTarget))
  6954. ? Js::OpCode::NewScObjArray : Js::OpCode::NewScObject;
  6955. Assert(argCount == 1);
  6956. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(op);
  6957. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argCount);
  6958. byteCodeGenerator->Writer()->CallI(op, funcInfo->AcquireLoc(pnode),
  6959. pnode->AsParseNodeCall()->pnodeTarget->location, argCount, callSiteId);
  6960. }
  6961. else
  6962. {
  6963. uint32 actualArgCount = 0;
  6964. if (IsCallOfConstants(pnode))
  6965. {
  6966. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argCount);
  6967. funcInfo->ReleaseLoc(pnode->AsParseNodeCall()->pnodeTarget);
  6968. actualArgCount = EmitNewObjectOfConstants(pnode, byteCodeGenerator, funcInfo, argCount);
  6969. }
  6970. else
  6971. {
  6972. Js::OpCode op;
  6973. if ((CreateNativeArrays(byteCodeGenerator, funcInfo) && CallTargetIsArray(pnode->AsParseNodeCall()->pnodeTarget)))
  6974. {
  6975. op = pnode->AsParseNodeCall()->spreadArgCount > 0 ? Js::OpCode::NewScObjArraySpread : Js::OpCode::NewScObjArray;
  6976. }
  6977. else
  6978. {
  6979. op = pnode->AsParseNodeCall()->spreadArgCount > 0 ? Js::OpCode::NewScObjectSpread : Js::OpCode::NewScObject;
  6980. }
  6981. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(op);
  6982. // Only emit profiled argouts if we're going to profile this call.
  6983. bool emitProfiledArgouts = callSiteId != byteCodeGenerator->GetCurrentCallSiteId();
  6984. Js::AuxArray<uint32> *spreadIndices = nullptr;
  6985. actualArgCount = EmitArgList(pnode->AsParseNodeCall()->pnodeArgs, Js::Constants::NoRegister, Js::Constants::NoRegister,
  6986. false, true, byteCodeGenerator, funcInfo, callSiteId, argCount, pnode->AsParseNodeCall()->hasDestructuring, emitProfiledArgouts, pnode->AsParseNodeCall()->spreadArgCount, &spreadIndices);
  6987. funcInfo->ReleaseLoc(pnode->AsParseNodeCall()->pnodeTarget);
  6988. if (pnode->AsParseNodeCall()->spreadArgCount > 0)
  6989. {
  6990. Assert(spreadIndices != nullptr);
  6991. uint spreadExtraAlloc = UInt32Math::Mul(spreadIndices->count, sizeof(uint32));
  6992. uint spreadIndicesSize = UInt32Math::Add(sizeof(*spreadIndices), spreadExtraAlloc);
  6993. byteCodeGenerator->Writer()->CallIExtended(op, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeCall()->pnodeTarget->location,
  6994. (uint16)actualArgCount, Js::CallIExtended_SpreadArgs,
  6995. spreadIndices, spreadIndicesSize, callSiteId);
  6996. }
  6997. else
  6998. {
  6999. byteCodeGenerator->Writer()->CallI(op, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeCall()->pnodeTarget->location,
  7000. (uint16)actualArgCount, callSiteId);
  7001. }
  7002. }
  7003. Assert(argCount == actualArgCount);
  7004. }
  7005. // End call, pop param space
  7006. funcInfo->EndRecordingOutArgs(argCount);
  7007. return;
  7008. }
  7009. void EmitCall(
  7010. ParseNodeCall * pnodeCall,
  7011. ByteCodeGenerator* byteCodeGenerator,
  7012. FuncInfo* funcInfo,
  7013. BOOL fReturnValue,
  7014. BOOL fEvaluateComponents,
  7015. Js::RegSlot overrideThisLocation,
  7016. Js::RegSlot newTargetLocation)
  7017. {
  7018. // If the call returns a float, we'll note this in the byte code.
  7019. Js::RegSlot thisLocation = Js::Constants::NoRegister;
  7020. Js::RegSlot callObjLocation = Js::Constants::NoRegister;
  7021. BOOL fHasNewTarget = newTargetLocation != Js::Constants::NoRegister;
  7022. BOOL fSideEffectArgs = FALSE;
  7023. BOOL fIsSuperCall = pnodeCall->isSuperCall;
  7024. ParseNode *pnodeTarget = pnodeCall->pnodeTarget;
  7025. ParseNode *pnodeArgs = pnodeCall->pnodeArgs;
  7026. uint16 spreadArgCount = pnodeCall->spreadArgCount;
  7027. if (CreateNativeArrays(byteCodeGenerator, funcInfo) && CallTargetIsArray(pnodeTarget)) {
  7028. // some minifiers (potentially incorrectly) assume that "v = new Array()" and "v = Array()" are equivalent,
  7029. // and replace the former with the latter to save 4 characters. What that means for us is that it, at least
  7030. // initially, uses the "Call" path. We want to guess that it _is_ just "new Array()" and change over to the
  7031. // "new" path, since then our native array handling can kick in.
  7032. /*EmitNew(pnode, byteCodeGenerator, funcInfo);
  7033. return;*/
  7034. }
  7035. unsigned int argCount = CountArguments(pnodeArgs, &fSideEffectArgs);
  7036. BOOL fIsEval = pnodeCall->isEvalCall;
  7037. Js::ArgSlot argSlotCount = (Js::ArgSlot)argCount;
  7038. if (fIsEval)
  7039. {
  7040. Assert(!fHasNewTarget);
  7041. //
  7042. // "eval" takes the closure environment as an extra argument
  7043. // Pass the closure env only if some argument is passed
  7044. // For just eval(), don't pass the closure environment
  7045. //
  7046. if (argCount > 1)
  7047. {
  7048. argCount++;
  7049. }
  7050. }
  7051. else if (fHasNewTarget)
  7052. {
  7053. // When we need to pass new.target explicitly, it is passed as an extra argument.
  7054. // This is similar to how eval passes an extra argument for the frame display and is
  7055. // used to support cases where we need to pass both 'this' and new.target as part of
  7056. // a function call.
  7057. // OpCode::LdNewTarget knows how to look at the call flags and fetch this argument.
  7058. argCount++;
  7059. }
  7060. // argCount indicates the total arguments count including the extra arguments.
  7061. // argSlotCount indicates the actual arguments count. So argCount should always never be les sthan argSlotCount.
  7062. if (argCount < (unsigned int)argSlotCount)
  7063. {
  7064. Js::Throw::OutOfMemory();
  7065. }
  7066. if (fReturnValue)
  7067. {
  7068. pnodeCall->isUsed = true;
  7069. }
  7070. //
  7071. // Set up the call.
  7072. //
  7073. bool releaseThisLocation = true;
  7074. // We already emit the call target for super calls in EmitSuperCall
  7075. if (!fIsSuperCall)
  7076. {
  7077. if (!fEvaluateComponents)
  7078. {
  7079. EmitCallTargetNoEvalComponents(pnodeTarget, fSideEffectArgs, &thisLocation, &releaseThisLocation, &callObjLocation, byteCodeGenerator, funcInfo);
  7080. }
  7081. else
  7082. {
  7083. EmitCallTarget(pnodeTarget, fSideEffectArgs, &thisLocation, &releaseThisLocation, &callObjLocation, byteCodeGenerator, funcInfo);
  7084. }
  7085. }
  7086. // If we are strictly overriding the this location, ignore what the call target set this location to.
  7087. if (overrideThisLocation != Js::Constants::NoRegister)
  7088. {
  7089. thisLocation = overrideThisLocation;
  7090. releaseThisLocation = false;
  7091. }
  7092. // Evaluate the arguments (nothing mode-specific here).
  7093. // Start call, allocate out param space
  7094. // We have to use the arguments count including the extra args to Start Call as we use it to allocated space for all the args
  7095. funcInfo->StartRecordingOutArgs(argCount);
  7096. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  7097. // Only emit profiled argouts if we're going to allocate callSiteInfo (on the DynamicProfileInfo) for this call.
  7098. bool emitProfiledArgouts = callSiteId != byteCodeGenerator->GetCurrentCallSiteId();
  7099. Js::AuxArray<uint32> *spreadIndices;
  7100. EmitArgList(pnodeArgs, thisLocation, newTargetLocation, fIsEval, fEvaluateComponents, byteCodeGenerator, funcInfo, callSiteId, (Js::ArgSlot)argCount, pnodeCall->hasDestructuring, emitProfiledArgouts, spreadArgCount, &spreadIndices);
  7101. if (!fEvaluateComponents)
  7102. {
  7103. EmitCallInstrNoEvalComponents(pnodeCall, fIsEval, thisLocation, callObjLocation, argSlotCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7104. }
  7105. else
  7106. {
  7107. EmitCallInstr(pnodeCall, fIsEval, fHasNewTarget, releaseThisLocation ? thisLocation : Js::Constants::NoRegister, callObjLocation, argSlotCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7108. }
  7109. // End call, pop param space
  7110. funcInfo->EndRecordingOutArgs((Js::ArgSlot)argCount);
  7111. }
  7112. void EmitInvoke(
  7113. Js::RegSlot location,
  7114. Js::RegSlot callObjLocation,
  7115. Js::PropertyId propertyId,
  7116. ByteCodeGenerator* byteCodeGenerator,
  7117. FuncInfo* funcInfo)
  7118. {
  7119. EmitMethodFld(false, false, location, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7120. funcInfo->StartRecordingOutArgs(1);
  7121. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  7122. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, 1);
  7123. EmitArgListStart(callObjLocation, byteCodeGenerator, funcInfo, callSiteId);
  7124. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallI, location, location, 1, callSiteId);
  7125. }
  7126. void EmitInvoke(
  7127. Js::RegSlot location,
  7128. Js::RegSlot callObjLocation,
  7129. Js::PropertyId propertyId,
  7130. ByteCodeGenerator* byteCodeGenerator,
  7131. FuncInfo* funcInfo,
  7132. Js::RegSlot arg1Location)
  7133. {
  7134. EmitMethodFld(false, false, location, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7135. funcInfo->StartRecordingOutArgs(2);
  7136. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  7137. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, 2);
  7138. EmitArgListStart(callObjLocation, byteCodeGenerator, funcInfo, callSiteId);
  7139. byteCodeGenerator->Writer()->ArgOut<true>(1, arg1Location, callSiteId, false /*emitProfiledArgout*/);
  7140. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallI, location, location, 2, callSiteId);
  7141. }
  7142. void EmitComputedFunctionNameVar(ParseNode *nameNode, ParseNodeFnc *exprNode, ByteCodeGenerator *byteCodeGenerator)
  7143. {
  7144. AssertMsg(exprNode != nullptr, "callers of this function should pass in a valid expression Node");
  7145. Assert(exprNode->HasComputedName());
  7146. if (nameNode == nullptr)
  7147. {
  7148. return;
  7149. }
  7150. if (exprNode->pnodeName == nullptr)
  7151. {
  7152. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SetComputedNameVar, exprNode->location, nameNode->location);
  7153. }
  7154. }
  7155. void EmitMemberNode(ParseNode *memberNode, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, ParseNode* parentNode, bool useStore, bool* isObjectEmpty = nullptr)
  7156. {
  7157. ParseNode *nameNode = memberNode->AsParseNodeBin()->pnode1;
  7158. ParseNode *exprNode = memberNode->AsParseNodeBin()->pnode2;
  7159. bool isFncDecl = exprNode->nop == knopFncDecl;
  7160. bool isClassMember = isFncDecl && exprNode->AsParseNodeFnc()->IsClassMember();
  7161. if (isFncDecl)
  7162. {
  7163. Assert(exprNode->AsParseNodeFnc()->HasHomeObj());
  7164. exprNode->AsParseNodeFnc()->SetHomeObjLocation(objectLocation);
  7165. }
  7166. // Moved SetComputedNameVar before LdFld of prototype because loading the prototype undefers the function TypeHandler
  7167. // which makes this bytecode too late to influence the function.name.
  7168. if (nameNode->nop == knopComputedName)
  7169. {
  7170. // Computed property name
  7171. // Transparently pass the name expr
  7172. // The Emit will replace this with a temp register if necessary to preserve the value.
  7173. nameNode->location = nameNode->AsParseNodeUni()->pnode1->location;
  7174. EmitBinaryOpnds(nameNode, exprNode, byteCodeGenerator, funcInfo);
  7175. if (isFncDecl && !exprNode->AsParseNodeFnc()->IsClassConstructor())
  7176. {
  7177. EmitComputedFunctionNameVar(nameNode, exprNode->AsParseNodeFnc(), byteCodeGenerator);
  7178. }
  7179. }
  7180. // Classes allocates a RegSlot as part of Instance Methods EmitClassInitializers,
  7181. // but if we don't have any members then we don't need to load the prototype.
  7182. Assert(isClassMember == (isObjectEmpty != nullptr));
  7183. if (isClassMember && *isObjectEmpty)
  7184. {
  7185. *isObjectEmpty = false;
  7186. int cacheId = funcInfo->FindOrAddInlineCacheId(parentNode->location, Js::PropertyIds::prototype, false, false);
  7187. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, objectLocation, parentNode->location, cacheId);
  7188. }
  7189. if (nameNode->nop == knopComputedName)
  7190. {
  7191. AssertOrFailFast(memberNode->nop == knopGetMember || memberNode->nop == knopSetMember || memberNode->nop == knopMember);
  7192. Js::OpCode setOp = memberNode->nop == knopGetMember ?
  7193. (isClassMember ? Js::OpCode::InitClassMemberGetComputedName : Js::OpCode::InitGetElemI) :
  7194. memberNode->nop == knopSetMember ?
  7195. (isClassMember ? Js::OpCode::InitClassMemberSetComputedName : Js::OpCode::InitSetElemI) :
  7196. (isClassMember ? Js::OpCode::InitClassMemberComputedName : Js::OpCode::InitComputedProperty);
  7197. byteCodeGenerator->Writer()->Element(setOp, exprNode->location, objectLocation, nameNode->location, true);
  7198. funcInfo->ReleaseLoc(exprNode);
  7199. funcInfo->ReleaseLoc(nameNode);
  7200. return;
  7201. }
  7202. Js::OpCode stFldOpCode = (Js::OpCode)0;
  7203. if (useStore)
  7204. {
  7205. stFldOpCode = ByteCodeGenerator::GetStFldOpCode(funcInfo, false, false, false, isClassMember);
  7206. }
  7207. Emit(exprNode, byteCodeGenerator, funcInfo, false);
  7208. Js::PropertyId propertyId = nameNode->AsParseNodeStr()->pid->GetPropertyId();
  7209. if (Js::PropertyIds::name == propertyId
  7210. && exprNode->nop == knopFncDecl
  7211. && exprNode->AsParseNodeFnc()->IsStaticMember()
  7212. && parentNode != nullptr && parentNode->nop == knopClassDecl
  7213. && parentNode->AsParseNodeClass()->pnodeConstructor != nullptr)
  7214. {
  7215. Js::ParseableFunctionInfo* nameFunc = parentNode->AsParseNodeClass()->pnodeConstructor->funcInfo->byteCodeFunction->GetParseableFunctionInfo();
  7216. nameFunc->SetIsStaticNameFunction(true);
  7217. }
  7218. if (memberNode->nop == knopMember || memberNode->nop == knopMemberShort)
  7219. {
  7220. // The internal prototype should be set only if the production is of the form PropertyDefinition : PropertyName : AssignmentExpression
  7221. if (propertyId == Js::PropertyIds::__proto__ && memberNode->nop != knopMemberShort && (exprNode->nop != knopFncDecl || !exprNode->AsParseNodeFnc()->IsMethod()))
  7222. {
  7223. byteCodeGenerator->Writer()->Property(Js::OpCode::InitProto, exprNode->location, objectLocation,
  7224. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  7225. }
  7226. else
  7227. {
  7228. uint cacheId = funcInfo->FindOrAddInlineCacheId(objectLocation, propertyId, false, true);
  7229. Js::OpCode patchablePropertyOpCode;
  7230. if (useStore)
  7231. {
  7232. patchablePropertyOpCode = stFldOpCode;
  7233. }
  7234. else if (isClassMember)
  7235. {
  7236. patchablePropertyOpCode = Js::OpCode::InitClassMember;
  7237. }
  7238. else
  7239. {
  7240. patchablePropertyOpCode = Js::OpCode::InitFld;
  7241. }
  7242. byteCodeGenerator->Writer()->PatchableProperty(patchablePropertyOpCode, exprNode->location, objectLocation, cacheId);
  7243. }
  7244. }
  7245. else
  7246. {
  7247. AssertOrFailFast(memberNode->nop == knopGetMember || memberNode->nop == knopSetMember);
  7248. Js::OpCode setOp = memberNode->nop == knopGetMember ?
  7249. (isClassMember ? Js::OpCode::InitClassMemberGet : Js::OpCode::InitGetFld) :
  7250. (isClassMember ? Js::OpCode::InitClassMemberSet : Js::OpCode::InitSetFld);
  7251. byteCodeGenerator->Writer()->Property(setOp, exprNode->location, objectLocation, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  7252. }
  7253. funcInfo->ReleaseLoc(exprNode);
  7254. if (propertyId == Js::PropertyIds::valueOf)
  7255. {
  7256. byteCodeGenerator->GetScriptContext()->optimizationOverrides.SetSideEffects(Js::SideEffects_ValueOf);
  7257. }
  7258. else if (propertyId == Js::PropertyIds::toString)
  7259. {
  7260. byteCodeGenerator->GetScriptContext()->optimizationOverrides.SetSideEffects(Js::SideEffects_ToString);
  7261. }
  7262. }
  7263. void EmitClassInitializers(ParseNode *memberList, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, ParseNode* parentNode, bool isObjectEmpty)
  7264. {
  7265. if (memberList != nullptr)
  7266. {
  7267. while (memberList->nop == knopList)
  7268. {
  7269. ParseNode *memberNode = memberList->AsParseNodeBin()->pnode1;
  7270. EmitMemberNode(memberNode, objectLocation, byteCodeGenerator, funcInfo, parentNode, /*useStore*/ false, &isObjectEmpty);
  7271. memberList = memberList->AsParseNodeBin()->pnode2;
  7272. }
  7273. EmitMemberNode(memberList, objectLocation, byteCodeGenerator, funcInfo, parentNode, /*useStore*/ false, &isObjectEmpty);
  7274. }
  7275. }
  7276. void EmitObjectInitializers(ParseNode *memberList, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7277. {
  7278. ParseNode *pmemberList = memberList;
  7279. unsigned int argCount = 0;
  7280. uint32 value;
  7281. Js::PropertyId propertyId;
  7282. //
  7283. // 1. Add all non-int property ids to a dictionary propertyIds with value true
  7284. // 2. Get the count of propertyIds
  7285. // 3. Create a propertyId array of size count
  7286. // 4. Put the propIds in the auxiliary area
  7287. // 5. Get the objectLiteralCacheId
  7288. // 6. Generate propId inits with values
  7289. //
  7290. // Handle propertyId collision
  7291. typedef JsUtil::BaseHashSet<Js::PropertyId, ArenaAllocator, PowerOf2SizePolicy> PropertyIdSet;
  7292. PropertyIdSet* propertyIds = Anew(byteCodeGenerator->GetAllocator(), PropertyIdSet, byteCodeGenerator->GetAllocator(), 17);
  7293. bool hasComputedName = false;
  7294. if (memberList != nullptr)
  7295. {
  7296. while (memberList->nop == knopList)
  7297. {
  7298. if (memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->nop == knopComputedName)
  7299. {
  7300. hasComputedName = true;
  7301. break;
  7302. }
  7303. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7304. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value))
  7305. {
  7306. propertyIds->Item(propertyId);
  7307. }
  7308. memberList = memberList->AsParseNodeBin()->pnode2;
  7309. }
  7310. if (memberList->AsParseNodeBin()->pnode1->nop != knopComputedName && !hasComputedName)
  7311. {
  7312. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7313. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value))
  7314. {
  7315. propertyIds->Item(propertyId);
  7316. }
  7317. }
  7318. }
  7319. argCount = propertyIds->Count();
  7320. memberList = pmemberList;
  7321. if ((memberList == nullptr) || (argCount == 0))
  7322. {
  7323. // Empty literal or numeric property only object literal
  7324. byteCodeGenerator->Writer()->Reg1(Js::OpCode::NewScObjectSimple, objectLocation);
  7325. }
  7326. else
  7327. {
  7328. uint32 allocSize = UInt32Math::Mul(argCount, sizeof(Js::PropertyId));
  7329. Js::PropertyIdArray *propIds = AnewPlus(byteCodeGenerator->GetAllocator(), allocSize, Js::PropertyIdArray, argCount, 0);
  7330. if (propertyIds->ContainsKey(Js::PropertyIds::__proto__))
  7331. {
  7332. // Always record whether the initializer contains __proto__ no matter if current environment has it enabled
  7333. // or not, in case the bytecode is later run with __proto__ enabled.
  7334. propIds->has__proto__ = true;
  7335. }
  7336. unsigned int argIndex = 0;
  7337. while (memberList->nop == knopList)
  7338. {
  7339. if (memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->nop == knopComputedName)
  7340. {
  7341. break;
  7342. }
  7343. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7344. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value) && propertyIds->Remove(propertyId))
  7345. {
  7346. propIds->elements[argIndex] = propertyId;
  7347. argIndex++;
  7348. }
  7349. memberList = memberList->AsParseNodeBin()->pnode2;
  7350. }
  7351. if (memberList->AsParseNodeBin()->pnode1->nop != knopComputedName && !hasComputedName)
  7352. {
  7353. propertyId = memberList->AsParseNodeBin()->pnode1->AsParseNodeStr()->pid->GetPropertyId();
  7354. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value) && propertyIds->Remove(propertyId))
  7355. {
  7356. propIds->elements[argIndex] = propertyId;
  7357. argIndex++;
  7358. }
  7359. }
  7360. uint32 literalObjectId = funcInfo->GetParsedFunctionBody()->NewObjectLiteral();
  7361. // Generate the opcode with propIds and cacheId
  7362. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::NewScObjectLiteral, objectLocation, propIds, UInt32Math::Add(sizeof(Js::PropertyIdArray), allocSize), literalObjectId);
  7363. Adelete(byteCodeGenerator->GetAllocator(), propertyIds);
  7364. AdeletePlus(byteCodeGenerator->GetAllocator(), allocSize, propIds);
  7365. }
  7366. memberList = pmemberList;
  7367. bool useStore = false;
  7368. // Generate the actual assignment to those properties
  7369. if (memberList != nullptr)
  7370. {
  7371. while (memberList->nop == knopList)
  7372. {
  7373. ParseNode *memberNode = memberList->AsParseNodeBin()->pnode1;
  7374. if (memberNode->AsParseNodeBin()->pnode1->nop == knopComputedName)
  7375. {
  7376. useStore = true;
  7377. }
  7378. byteCodeGenerator->StartSubexpression(memberNode);
  7379. EmitMemberNode(memberNode, objectLocation, byteCodeGenerator, funcInfo, nullptr, useStore);
  7380. byteCodeGenerator->EndSubexpression(memberNode);
  7381. memberList = memberList->AsParseNodeBin()->pnode2;
  7382. }
  7383. byteCodeGenerator->StartSubexpression(memberList);
  7384. EmitMemberNode(memberList, objectLocation, byteCodeGenerator, funcInfo, nullptr, useStore);
  7385. byteCodeGenerator->EndSubexpression(memberList);
  7386. }
  7387. }
  7388. void EmitStringTemplate(ParseNodeStrTemplate *pnodeStrTemplate, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7389. {
  7390. Assert(pnodeStrTemplate->pnodeStringLiterals);
  7391. // For a tagged string template, we will create the callsite constant object as part of the FunctionBody constants table.
  7392. // We only need to emit code for non-tagged string templates here.
  7393. if (!pnodeStrTemplate->isTaggedTemplate)
  7394. {
  7395. // If we have no substitutions and this is not a tagged template, we can emit just the single cooked string.
  7396. if (pnodeStrTemplate->pnodeSubstitutionExpressions == nullptr)
  7397. {
  7398. Assert(pnodeStrTemplate->pnodeStringLiterals->nop != knopList);
  7399. funcInfo->AcquireLoc(pnodeStrTemplate);
  7400. Emit(pnodeStrTemplate->pnodeStringLiterals, byteCodeGenerator, funcInfo, false);
  7401. Assert(pnodeStrTemplate->location != pnodeStrTemplate->pnodeStringLiterals->location);
  7402. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnodeStrTemplate->location, pnodeStrTemplate->pnodeStringLiterals->location);
  7403. funcInfo->ReleaseLoc(pnodeStrTemplate->pnodeStringLiterals);
  7404. }
  7405. else
  7406. {
  7407. // If we have substitutions but no tag function, we can skip the callSite object construction (and also ignore raw strings).
  7408. funcInfo->AcquireLoc(pnodeStrTemplate);
  7409. // First string must be a list node since we have substitutions.
  7410. AssertMsg(pnodeStrTemplate->pnodeStringLiterals->nop == knopList, "First string in the list must be a knopList node.");
  7411. ParseNode* stringNodeList = pnodeStrTemplate->pnodeStringLiterals;
  7412. // Emit the first string and load that into the pnode location.
  7413. Emit(stringNodeList->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  7414. Assert(pnodeStrTemplate->location != stringNodeList->AsParseNodeBin()->pnode1->location);
  7415. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnodeStrTemplate->location, stringNodeList->AsParseNodeBin()->pnode1->location);
  7416. funcInfo->ReleaseLoc(stringNodeList->AsParseNodeBin()->pnode1);
  7417. ParseNode* expressionNodeList = pnodeStrTemplate->pnodeSubstitutionExpressions;
  7418. ParseNode* stringNode;
  7419. ParseNode* expressionNode;
  7420. // Now append the substitution expressions and remaining string constants via normal add operator
  7421. // We will always have one more string constant than substitution expression
  7422. // `strcon1 ${expr1} strcon2 ${expr2} strcon3` = strcon1 + expr1 + strcon2 + expr2 + strcon3
  7423. //
  7424. // strcon1 --- step 1 (above)
  7425. // expr1 \__ step 2
  7426. // strcon2 /
  7427. // expr2 \__ step 3
  7428. // strcon3 /
  7429. while (stringNodeList->nop == knopList)
  7430. {
  7431. // If the current head of the expression list is a list, fetch the node and walk the list.
  7432. if (expressionNodeList->nop == knopList)
  7433. {
  7434. expressionNode = expressionNodeList->AsParseNodeBin()->pnode1;
  7435. expressionNodeList = expressionNodeList->AsParseNodeBin()->pnode2;
  7436. }
  7437. else
  7438. {
  7439. // This is the last element of the expression list.
  7440. expressionNode = expressionNodeList;
  7441. }
  7442. // Emit the expression and append it to the string we're building.
  7443. Emit(expressionNode, byteCodeGenerator, funcInfo, false);
  7444. Js::RegSlot toStringLocation = funcInfo->AcquireTmpRegister();
  7445. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Str, toStringLocation, expressionNode->location);
  7446. byteCodeGenerator->Writer()->Reg3(Js::OpCode::Add_A, pnodeStrTemplate->location, pnodeStrTemplate->location, toStringLocation);
  7447. funcInfo->ReleaseTmpRegister(toStringLocation);
  7448. funcInfo->ReleaseLoc(expressionNode);
  7449. // Move to the next string in the list - we already got ahead of the expressions in the first string literal above.
  7450. stringNodeList = stringNodeList->AsParseNodeBin()->pnode2;
  7451. // If the current head of the string literal list is also a list node, need to fetch the actual string literal node.
  7452. if (stringNodeList->nop == knopList)
  7453. {
  7454. stringNode = stringNodeList->AsParseNodeBin()->pnode1;
  7455. }
  7456. else
  7457. {
  7458. // This is the last element of the string literal list.
  7459. stringNode = stringNodeList;
  7460. }
  7461. // Emit the string node following the previous expression and append it to the string.
  7462. // This is either just some string in the list or it is the last string.
  7463. Emit(stringNode, byteCodeGenerator, funcInfo, false);
  7464. byteCodeGenerator->Writer()->Reg3(Js::OpCode::Add_A, pnodeStrTemplate->location, pnodeStrTemplate->location, stringNode->location);
  7465. funcInfo->ReleaseLoc(stringNode);
  7466. }
  7467. }
  7468. }
  7469. }
  7470. void SetNewArrayElements(ParseNode *pnode, Js::RegSlot arrayLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7471. {
  7472. ParseNode *args = pnode->AsParseNodeUni()->pnode1;
  7473. uint argCount = pnode->AsParseNodeArrLit()->count;
  7474. uint spreadCount = pnode->AsParseNodeArrLit()->spreadCount;
  7475. bool nativeArrays = CreateNativeArrays(byteCodeGenerator, funcInfo);
  7476. bool arrayIntOpt = nativeArrays && pnode->AsParseNodeArrLit()->arrayOfInts;
  7477. if (arrayIntOpt)
  7478. {
  7479. int extraAlloc = 0, auxSize = 0;
  7480. if (Int32Math::Mul(argCount, sizeof(int32), &extraAlloc)
  7481. || Int32Math::Add(sizeof(Js::AuxArray<int>), extraAlloc, &auxSize))
  7482. {
  7483. ::Math::DefaultOverflowPolicy();
  7484. }
  7485. Js::AuxArray<int> *ints = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<int32>, argCount);
  7486. EmitConstantArgsToIntArray(byteCodeGenerator, ints->elements, args, argCount);
  7487. Assert(!pnode->AsParseNodeArrLit()->hasMissingValues);
  7488. byteCodeGenerator->Writer()->Auxiliary(
  7489. Js::OpCode::NewScIntArray,
  7490. pnode->location,
  7491. ints,
  7492. auxSize,
  7493. argCount);
  7494. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, ints);
  7495. return;
  7496. }
  7497. bool arrayNumOpt = nativeArrays && pnode->AsParseNodeArrLit()->arrayOfNumbers;
  7498. if (arrayNumOpt)
  7499. {
  7500. int extraAlloc = 0, auxSize = 0;
  7501. if (Int32Math::Mul(argCount, sizeof(double), &extraAlloc)
  7502. || Int32Math::Add(sizeof(Js::AuxArray<double>), extraAlloc, &auxSize))
  7503. {
  7504. ::Math::DefaultOverflowPolicy();
  7505. }
  7506. Js::AuxArray<double> *doubles = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<double>, argCount);
  7507. EmitConstantArgsToFltArray(byteCodeGenerator, doubles->elements, args, argCount);
  7508. Assert(!pnode->AsParseNodeArrLit()->hasMissingValues);
  7509. byteCodeGenerator->Writer()->Auxiliary(
  7510. Js::OpCode::NewScFltArray,
  7511. pnode->location,
  7512. doubles,
  7513. auxSize,
  7514. argCount);
  7515. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, doubles);
  7516. return;
  7517. }
  7518. bool arrayLitOpt = pnode->AsParseNodeArrLit()->arrayOfTaggedInts && pnode->AsParseNodeArrLit()->count > 1;
  7519. Assert(!arrayLitOpt || !nativeArrays);
  7520. Js::RegSlot spreadArrLoc = arrayLocation;
  7521. Js::AuxArray<uint32> *spreadIndices = nullptr;
  7522. const uint extraAlloc = UInt32Math::Mul(spreadCount, sizeof(uint32));
  7523. if (pnode->AsParseNodeArrLit()->spreadCount > 0)
  7524. {
  7525. arrayLocation = funcInfo->AcquireTmpRegister();
  7526. spreadIndices = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<uint32>, spreadCount);
  7527. }
  7528. byteCodeGenerator->Writer()->Reg1Unsigned1(
  7529. pnode->AsParseNodeArrLit()->hasMissingValues ? Js::OpCode::NewScArrayWithMissingValues : Js::OpCode::NewScArray,
  7530. arrayLocation,
  7531. argCount);
  7532. if (args != nullptr)
  7533. {
  7534. Js::OpCode opcode;
  7535. Js::RegSlot arrLoc;
  7536. if (argCount == 1 && !byteCodeGenerator->Writer()->DoProfileNewScArrayOp(Js::OpCode::NewScArray))
  7537. {
  7538. opcode = Js::OpCode::StArrItemC_CI4;
  7539. arrLoc = arrayLocation;
  7540. }
  7541. else if (arrayLitOpt)
  7542. {
  7543. opcode = Js::OpCode::StArrSegItem_A;
  7544. arrLoc = funcInfo->AcquireTmpRegister();
  7545. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdArrHead, arrLoc, arrayLocation);
  7546. }
  7547. else if (Js::JavascriptArray::HasInlineHeadSegment(argCount))
  7548. {
  7549. // The head segment will be allocated inline as an interior pointer. To keep the array alive, the set operation
  7550. // should be done relative to the array header to keep it alive (instead of the array segment).
  7551. opcode = Js::OpCode::StArrInlineItem_CI4;
  7552. arrLoc = arrayLocation;
  7553. }
  7554. else if (argCount <= Js::JavascriptArray::MaxInitialDenseLength)
  7555. {
  7556. opcode = Js::OpCode::StArrSegItem_CI4;
  7557. arrLoc = funcInfo->AcquireTmpRegister();
  7558. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdArrHead, arrLoc, arrayLocation);
  7559. }
  7560. else
  7561. {
  7562. opcode = Js::OpCode::StArrItemI_CI4;
  7563. arrLoc = arrayLocation;
  7564. }
  7565. if (arrayLitOpt)
  7566. {
  7567. uint32 allocSize = UInt32Math::Mul(argCount, sizeof(Js::Var));
  7568. Js::VarArray *vars = AnewPlus(byteCodeGenerator->GetAllocator(), allocSize, Js::VarArray, argCount);
  7569. EmitConstantArgsToVarArray(byteCodeGenerator, vars->elements, args, argCount);
  7570. // Generate the opcode with vars
  7571. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::StArrSegItem_A, arrLoc, vars, UInt32Math::Add(sizeof(Js::VarArray), allocSize), argCount);
  7572. AdeletePlus(byteCodeGenerator->GetAllocator(), allocSize, vars);
  7573. }
  7574. else
  7575. {
  7576. uint i = 0;
  7577. unsigned spreadIndex = 0;
  7578. Js::RegSlot rhsLocation;
  7579. while (args->nop == knopList)
  7580. {
  7581. if (args->AsParseNodeBin()->pnode1->nop != knopEmpty)
  7582. {
  7583. Emit(args->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  7584. rhsLocation = args->AsParseNodeBin()->pnode1->location;
  7585. Js::RegSlot regVal = rhsLocation;
  7586. if (args->AsParseNodeBin()->pnode1->nop == knopEllipsis)
  7587. {
  7588. AnalysisAssert(spreadIndices);
  7589. regVal = funcInfo->AcquireTmpRegister();
  7590. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, rhsLocation);
  7591. spreadIndices->elements[spreadIndex++] = i;
  7592. }
  7593. byteCodeGenerator->Writer()->ElementUnsigned1(opcode, regVal, arrLoc, i);
  7594. if (args->AsParseNodeBin()->pnode1->nop == knopEllipsis)
  7595. {
  7596. funcInfo->ReleaseTmpRegister(regVal);
  7597. }
  7598. funcInfo->ReleaseLoc(args->AsParseNodeBin()->pnode1);
  7599. }
  7600. args = args->AsParseNodeBin()->pnode2;
  7601. i++;
  7602. }
  7603. if (args->nop != knopEmpty)
  7604. {
  7605. Emit(args, byteCodeGenerator, funcInfo, false);
  7606. rhsLocation = args->location;
  7607. Js::RegSlot regVal = rhsLocation;
  7608. if (args->nop == knopEllipsis)
  7609. {
  7610. regVal = funcInfo->AcquireTmpRegister();
  7611. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, rhsLocation);
  7612. AnalysisAssert(spreadIndices);
  7613. spreadIndices->elements[spreadIndex] = i;
  7614. }
  7615. byteCodeGenerator->Writer()->ElementUnsigned1(opcode, regVal, arrLoc, i);
  7616. if (args->nop == knopEllipsis)
  7617. {
  7618. funcInfo->ReleaseTmpRegister(regVal);
  7619. }
  7620. funcInfo->ReleaseLoc(args);
  7621. i++;
  7622. }
  7623. Assert(i <= argCount);
  7624. }
  7625. if (arrLoc != arrayLocation)
  7626. {
  7627. funcInfo->ReleaseTmpRegister(arrLoc);
  7628. }
  7629. }
  7630. if (pnode->AsParseNodeArrLit()->spreadCount > 0)
  7631. {
  7632. byteCodeGenerator->Writer()->Reg2Aux(Js::OpCode::SpreadArrayLiteral, spreadArrLoc, arrayLocation, spreadIndices, UInt32Math::Add(sizeof(Js::AuxArray<uint32>), extraAlloc), extraAlloc);
  7633. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, spreadIndices);
  7634. funcInfo->ReleaseTmpRegister(arrayLocation);
  7635. }
  7636. }
  7637. // FIX: TODO: mixed-mode expressions (arithmetic expressions mixed with boolean expressions); current solution
  7638. // will not short-circuit in some cases and is not complete (for example: var i=(x==y))
  7639. // This uses Aho and Ullman style double-branch generation (p. 494 ASU); we will need to peephole optimize or replace
  7640. // with special case for single-branch style.
  7641. void EmitBooleanExpression(
  7642. _In_ ParseNode* expr,
  7643. Js::ByteCodeLabel trueLabel,
  7644. Js::ByteCodeLabel falseLabel,
  7645. _In_ ByteCodeGenerator* byteCodeGenerator,
  7646. _In_ FuncInfo* funcInfo,
  7647. bool trueFallthrough,
  7648. bool falseFallthrough)
  7649. {
  7650. Assert(!trueFallthrough || !falseFallthrough);
  7651. byteCodeGenerator->StartStatement(expr);
  7652. switch (expr->nop)
  7653. {
  7654. case knopLogOr:
  7655. {
  7656. Js::ByteCodeLabel leftFalse = byteCodeGenerator->Writer()->DefineLabel();
  7657. EmitBooleanExpression(expr->AsParseNodeBin()->pnode1, trueLabel, leftFalse, byteCodeGenerator, funcInfo, false, true);
  7658. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7659. byteCodeGenerator->Writer()->MarkLabel(leftFalse);
  7660. EmitBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, falseLabel, byteCodeGenerator, funcInfo, trueFallthrough, falseFallthrough);
  7661. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7662. break;
  7663. }
  7664. case knopLogAnd:
  7665. {
  7666. Js::ByteCodeLabel leftTrue = byteCodeGenerator->Writer()->DefineLabel();
  7667. EmitBooleanExpression(expr->AsParseNodeBin()->pnode1, leftTrue, falseLabel, byteCodeGenerator, funcInfo, true, false);
  7668. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7669. byteCodeGenerator->Writer()->MarkLabel(leftTrue);
  7670. EmitBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, falseLabel, byteCodeGenerator, funcInfo, trueFallthrough, falseFallthrough);
  7671. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7672. break;
  7673. }
  7674. case knopLogNot:
  7675. EmitBooleanExpression(expr->AsParseNodeUni()->pnode1, falseLabel, trueLabel, byteCodeGenerator, funcInfo, falseFallthrough, trueFallthrough);
  7676. funcInfo->ReleaseLoc(expr->AsParseNodeUni()->pnode1);
  7677. break;
  7678. case knopEq:
  7679. case knopEqv:
  7680. case knopNEqv:
  7681. case knopNe:
  7682. case knopLt:
  7683. case knopLe:
  7684. case knopGe:
  7685. case knopGt:
  7686. EmitBinaryOpnds(expr->AsParseNodeBin()->pnode1, expr->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  7687. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7688. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7689. byteCodeGenerator->Writer()->BrReg2(nopToOp[expr->nop], trueLabel, expr->AsParseNodeBin()->pnode1->location,
  7690. expr->AsParseNodeBin()->pnode2->location);
  7691. if (!falseFallthrough)
  7692. {
  7693. byteCodeGenerator->Writer()->Br(falseLabel);
  7694. }
  7695. break;
  7696. case knopTrue:
  7697. if (!trueFallthrough)
  7698. {
  7699. byteCodeGenerator->Writer()->Br(trueLabel);
  7700. }
  7701. break;
  7702. case knopFalse:
  7703. if (!falseFallthrough)
  7704. {
  7705. byteCodeGenerator->Writer()->Br(falseLabel);
  7706. }
  7707. break;
  7708. default:
  7709. // Note: we usually release the temp assigned to a node after we Emit it.
  7710. // But in this case, EmitBooleanExpression is just a wrapper around a normal Emit call,
  7711. // and the caller of EmitBooleanExpression expects to be able to release this register.
  7712. Emit(expr, byteCodeGenerator, funcInfo, false);
  7713. if (trueFallthrough)
  7714. {
  7715. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  7716. }
  7717. else
  7718. {
  7719. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7720. if (!falseFallthrough)
  7721. {
  7722. byteCodeGenerator->Writer()->Br(falseLabel);
  7723. }
  7724. }
  7725. break;
  7726. }
  7727. byteCodeGenerator->EndStatement(expr);
  7728. }
  7729. void EmitGeneratingBooleanExpression(ParseNode *expr, Js::ByteCodeLabel trueLabel, bool truefallthrough, Js::ByteCodeLabel falseLabel, bool falsefallthrough, Js::RegSlot writeto,
  7730. ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7731. {
  7732. switch (expr->nop)
  7733. {
  7734. case knopLogOr:
  7735. {
  7736. byteCodeGenerator->StartStatement(expr);
  7737. Js::ByteCodeLabel leftFalse = byteCodeGenerator->Writer()->DefineLabel();
  7738. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode1, trueLabel, false, leftFalse, true, writeto, byteCodeGenerator, funcInfo);
  7739. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7740. byteCodeGenerator->Writer()->MarkLabel(leftFalse);
  7741. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, truefallthrough, falseLabel, falsefallthrough, writeto, byteCodeGenerator, funcInfo);
  7742. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7743. byteCodeGenerator->EndStatement(expr);
  7744. break;
  7745. }
  7746. case knopLogAnd:
  7747. {
  7748. byteCodeGenerator->StartStatement(expr);
  7749. Js::ByteCodeLabel leftTrue = byteCodeGenerator->Writer()->DefineLabel();
  7750. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode1, leftTrue, true, falseLabel, false, writeto, byteCodeGenerator, funcInfo);
  7751. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7752. byteCodeGenerator->Writer()->MarkLabel(leftTrue);
  7753. EmitGeneratingBooleanExpression(expr->AsParseNodeBin()->pnode2, trueLabel, truefallthrough, falseLabel, falsefallthrough, writeto, byteCodeGenerator, funcInfo);
  7754. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7755. byteCodeGenerator->EndStatement(expr);
  7756. break;
  7757. }
  7758. case knopLogNot:
  7759. {
  7760. byteCodeGenerator->StartStatement(expr);
  7761. // this time we want a boolean expression, since Logical Not is nice and only returns true or false
  7762. Js::ByteCodeLabel emitTrue = byteCodeGenerator->Writer()->DefineLabel();
  7763. Js::ByteCodeLabel emitFalse = byteCodeGenerator->Writer()->DefineLabel();
  7764. EmitBooleanExpression(expr->AsParseNodeUni()->pnode1, emitFalse, emitTrue, byteCodeGenerator, funcInfo, false, true);
  7765. byteCodeGenerator->Writer()->MarkLabel(emitTrue);
  7766. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, writeto);
  7767. byteCodeGenerator->Writer()->Br(trueLabel);
  7768. byteCodeGenerator->Writer()->MarkLabel(emitFalse);
  7769. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, writeto);
  7770. if (!falsefallthrough)
  7771. {
  7772. byteCodeGenerator->Writer()->Br(falseLabel);
  7773. }
  7774. funcInfo->ReleaseLoc(expr->AsParseNodeUni()->pnode1);
  7775. byteCodeGenerator->EndStatement(expr);
  7776. break;
  7777. }
  7778. case knopEq:
  7779. case knopEqv:
  7780. case knopNEqv:
  7781. case knopNe:
  7782. case knopLt:
  7783. case knopLe:
  7784. case knopGe:
  7785. case knopGt:
  7786. byteCodeGenerator->StartStatement(expr);
  7787. EmitBinaryOpnds(expr->AsParseNodeBin()->pnode1, expr->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  7788. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode2);
  7789. funcInfo->ReleaseLoc(expr->AsParseNodeBin()->pnode1);
  7790. funcInfo->AcquireLoc(expr);
  7791. byteCodeGenerator->Writer()->Reg3(nopToCMOp[expr->nop], expr->location, expr->AsParseNodeBin()->pnode1->location,
  7792. expr->AsParseNodeBin()->pnode2->location);
  7793. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, writeto, expr->location);
  7794. // The inliner likes small bytecode
  7795. if (!(truefallthrough || falsefallthrough))
  7796. {
  7797. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7798. byteCodeGenerator->Writer()->Br(falseLabel);
  7799. }
  7800. else if (truefallthrough && !falsefallthrough) {
  7801. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  7802. }
  7803. else if (falsefallthrough && !truefallthrough) {
  7804. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7805. }
  7806. byteCodeGenerator->EndStatement(expr);
  7807. break;
  7808. case knopTrue:
  7809. byteCodeGenerator->StartStatement(expr);
  7810. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, writeto);
  7811. if (!truefallthrough)
  7812. {
  7813. byteCodeGenerator->Writer()->Br(trueLabel);
  7814. }
  7815. byteCodeGenerator->EndStatement(expr);
  7816. break;
  7817. case knopFalse:
  7818. byteCodeGenerator->StartStatement(expr);
  7819. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, writeto);
  7820. if (!falsefallthrough)
  7821. {
  7822. byteCodeGenerator->Writer()->Br(falseLabel);
  7823. }
  7824. byteCodeGenerator->EndStatement(expr);
  7825. break;
  7826. default:
  7827. // Note: we usually release the temp assigned to a node after we Emit it.
  7828. // But in this case, EmitBooleanExpression is just a wrapper around a normal Emit call,
  7829. // and the caller of EmitBooleanExpression expects to be able to release this register.
  7830. // For diagnostics purposes, register the name and dot to the statement list.
  7831. if (expr->nop == knopName || expr->nop == knopDot)
  7832. {
  7833. byteCodeGenerator->StartStatement(expr);
  7834. Emit(expr, byteCodeGenerator, funcInfo, false);
  7835. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, writeto, expr->location);
  7836. // The inliner likes small bytecode
  7837. if (!(truefallthrough || falsefallthrough))
  7838. {
  7839. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7840. byteCodeGenerator->Writer()->Br(falseLabel);
  7841. }
  7842. else if (truefallthrough && !falsefallthrough) {
  7843. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  7844. }
  7845. else if (falsefallthrough && !truefallthrough) {
  7846. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7847. }
  7848. byteCodeGenerator->EndStatement(expr);
  7849. }
  7850. else
  7851. {
  7852. Emit(expr, byteCodeGenerator, funcInfo, false);
  7853. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, writeto, expr->location);
  7854. // The inliner likes small bytecode
  7855. if (!(truefallthrough || falsefallthrough))
  7856. {
  7857. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7858. byteCodeGenerator->Writer()->Br(falseLabel);
  7859. }
  7860. else if (truefallthrough && !falsefallthrough) {
  7861. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  7862. }
  7863. else if (falsefallthrough && !truefallthrough) {
  7864. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7865. }
  7866. }
  7867. break;
  7868. }
  7869. }
  7870. // used by while and for loops
  7871. void EmitLoop(
  7872. ParseNodeLoop *loopNode,
  7873. ParseNode *cond,
  7874. ParseNode *body,
  7875. ParseNode *incr,
  7876. ByteCodeGenerator *byteCodeGenerator,
  7877. FuncInfo *funcInfo,
  7878. BOOL fReturnValue,
  7879. BOOL doWhile = FALSE,
  7880. ParseNodeBlock *forLoopBlock = nullptr)
  7881. {
  7882. // Need to increment loop count whether we are going to profile or not for HasLoop()
  7883. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  7884. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  7885. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  7886. loopNode->loopId = loopId;
  7887. if (doWhile)
  7888. {
  7889. Emit(body, byteCodeGenerator, funcInfo, fReturnValue);
  7890. funcInfo->ReleaseLoc(body);
  7891. if (loopNode->emitLabels)
  7892. {
  7893. byteCodeGenerator->Writer()->MarkLabel(loopNode->continueLabel);
  7894. }
  7895. if (!ByteCodeGenerator::IsFalse(cond) ||
  7896. byteCodeGenerator->IsInDebugMode())
  7897. {
  7898. EmitBooleanExpression(cond, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, false, false);
  7899. }
  7900. funcInfo->ReleaseLoc(cond);
  7901. }
  7902. else
  7903. {
  7904. if (cond)
  7905. {
  7906. if (!(cond->nop == knopInt &&
  7907. cond->AsParseNodeInt()->lw != 0))
  7908. {
  7909. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  7910. EmitBooleanExpression(cond, trueLabel, continuePastLoop, byteCodeGenerator, funcInfo, true, false);
  7911. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  7912. }
  7913. funcInfo->ReleaseLoc(cond);
  7914. }
  7915. Emit(body, byteCodeGenerator, funcInfo, fReturnValue);
  7916. funcInfo->ReleaseLoc(body);
  7917. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled() &&
  7918. forLoopBlock != nullptr)
  7919. {
  7920. CloneEmitBlock(forLoopBlock, byteCodeGenerator, funcInfo);
  7921. }
  7922. if (loopNode->emitLabels)
  7923. {
  7924. byteCodeGenerator->Writer()->MarkLabel(loopNode->continueLabel);
  7925. }
  7926. if (incr != nullptr)
  7927. {
  7928. Emit(incr, byteCodeGenerator, funcInfo, false);
  7929. funcInfo->ReleaseLoc(incr);
  7930. }
  7931. byteCodeGenerator->Writer()->Br(loopEntrance);
  7932. }
  7933. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  7934. if (loopNode->emitLabels)
  7935. {
  7936. byteCodeGenerator->Writer()->MarkLabel(loopNode->breakLabel);
  7937. }
  7938. byteCodeGenerator->Writer()->ExitLoop(loopId);
  7939. }
  7940. void ByteCodeGenerator::EmitInvertedLoop(ParseNodeLoop* outerLoop, ParseNodeFor* invertedLoop, FuncInfo* funcInfo)
  7941. {
  7942. Js::ByteCodeLabel invertedLoopLabel = this->m_writer.DefineLabel();
  7943. Js::ByteCodeLabel afterInvertedLoop = this->m_writer.DefineLabel();
  7944. // emit branch around original
  7945. Emit(outerLoop->AsParseNodeFor()->pnodeInit, this, funcInfo, false);
  7946. funcInfo->ReleaseLoc(outerLoop->AsParseNodeFor()->pnodeInit);
  7947. this->m_writer.BrS(Js::OpCode::BrNotHasSideEffects, invertedLoopLabel, Js::SideEffects_Any);
  7948. // emit original
  7949. EmitLoop(outerLoop, outerLoop->AsParseNodeFor()->pnodeCond, outerLoop->AsParseNodeFor()->pnodeBody,
  7950. outerLoop->AsParseNodeFor()->pnodeIncr, this, funcInfo, false);
  7951. // clear temporary registers since inverted loop may share nodes with
  7952. // emitted original loop
  7953. VisitClearTmpRegs(outerLoop, this, funcInfo);
  7954. // emit branch around inverted
  7955. this->m_writer.Br(afterInvertedLoop);
  7956. this->m_writer.MarkLabel(invertedLoopLabel);
  7957. // Emit a zero trip test for the original outer-loop
  7958. Js::ByteCodeLabel zeroTrip = this->m_writer.DefineLabel();
  7959. ParseNode* testNode = this->GetParser()->CopyPnode(outerLoop->AsParseNodeFor()->pnodeCond);
  7960. EmitBooleanExpression(testNode, zeroTrip, afterInvertedLoop, this, funcInfo, true, false);
  7961. this->m_writer.MarkLabel(zeroTrip);
  7962. funcInfo->ReleaseLoc(testNode);
  7963. // emit inverted
  7964. Emit(invertedLoop->pnodeInit, this, funcInfo, false);
  7965. funcInfo->ReleaseLoc(invertedLoop->pnodeInit);
  7966. EmitLoop(invertedLoop, invertedLoop->pnodeCond, invertedLoop->pnodeBody,
  7967. invertedLoop->pnodeIncr, this, funcInfo, false);
  7968. this->m_writer.MarkLabel(afterInvertedLoop);
  7969. }
  7970. void EmitGetIterator(Js::RegSlot iteratorLocation, Js::RegSlot iterableLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  7971. {
  7972. // get iterator object from the iterable
  7973. EmitInvoke(iteratorLocation, iterableLocation, Js::PropertyIds::_symbolIterator, byteCodeGenerator, funcInfo);
  7974. // throw TypeError if the result is not an object
  7975. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  7976. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, skipThrow, iteratorLocation);
  7977. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_NeedObject));
  7978. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  7979. }
  7980. void EmitIteratorNext(Js::RegSlot itemLocation, Js::RegSlot iteratorLocation, Js::RegSlot nextInputLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  7981. {
  7982. // invoke next() on the iterator
  7983. if (nextInputLocation == Js::Constants::NoRegister)
  7984. {
  7985. EmitInvoke(itemLocation, iteratorLocation, Js::PropertyIds::next, byteCodeGenerator, funcInfo);
  7986. }
  7987. else
  7988. {
  7989. EmitInvoke(itemLocation, iteratorLocation, Js::PropertyIds::next, byteCodeGenerator, funcInfo, nextInputLocation);
  7990. }
  7991. // throw TypeError if the result is not an object
  7992. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  7993. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, skipThrow, itemLocation);
  7994. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_NeedObject));
  7995. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  7996. }
  7997. // Generating
  7998. // if (hasReturnFunction) {
  7999. // value = Call Retrun;
  8000. // if (value != Object)
  8001. // throw TypeError;
  8002. // }
  8003. void EmitIteratorClose(Js::RegSlot iteratorLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8004. {
  8005. Js::RegSlot returnLocation = funcInfo->AcquireTmpRegister();
  8006. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  8007. Js::ByteCodeLabel noReturn = byteCodeGenerator->Writer()->DefineLabel();
  8008. uint cacheId = funcInfo->FindOrAddInlineCacheId(iteratorLocation, Js::PropertyIds::return_, false, false);
  8009. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, returnLocation, iteratorLocation, cacheId);
  8010. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrEq_A, noReturn, returnLocation, funcInfo->undefinedConstantRegister);
  8011. EmitInvoke(returnLocation, iteratorLocation, Js::PropertyIds::return_, byteCodeGenerator, funcInfo);
  8012. // throw TypeError if the result is not an Object
  8013. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, skipThrow, returnLocation);
  8014. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_NeedObject));
  8015. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  8016. byteCodeGenerator->Writer()->MarkLabel(noReturn);
  8017. funcInfo->ReleaseTmpRegister(returnLocation);
  8018. }
  8019. void EmitIteratorComplete(Js::RegSlot doneLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8020. {
  8021. // get the iterator result's "done" property
  8022. uint cacheId = funcInfo->FindOrAddInlineCacheId(iteratorResultLocation, Js::PropertyIds::done, false, false);
  8023. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, doneLocation, iteratorResultLocation, cacheId);
  8024. // Do not need to do ToBoolean explicitly with current uses of EmitIteratorComplete since BrTrue_A does this.
  8025. // Add a ToBoolean controlled by template flag if needed for new uses later on.
  8026. }
  8027. void EmitIteratorValue(Js::RegSlot valueLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8028. {
  8029. // get the iterator result's "value" property
  8030. uint cacheId = funcInfo->FindOrAddInlineCacheId(iteratorResultLocation, Js::PropertyIds::value, false, false);
  8031. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, valueLocation, iteratorResultLocation, cacheId);
  8032. }
  8033. void EmitForInOfLoopBody(ParseNodeForInOrForOf *loopNode,
  8034. Js::ByteCodeLabel loopEntrance,
  8035. Js::ByteCodeLabel continuePastLoop,
  8036. ByteCodeGenerator *byteCodeGenerator,
  8037. FuncInfo *funcInfo,
  8038. BOOL fReturnValue)
  8039. {
  8040. if (loopNode->pnodeLval->nop != knopVarDecl &&
  8041. loopNode->pnodeLval->nop != knopLetDecl &&
  8042. loopNode->pnodeLval->nop != knopConstDecl)
  8043. {
  8044. EmitReference(loopNode->pnodeLval, byteCodeGenerator, funcInfo);
  8045. }
  8046. else
  8047. {
  8048. Symbol * sym = loopNode->pnodeLval->AsParseNodeVar()->sym;
  8049. sym->SetNeedDeclaration(false);
  8050. }
  8051. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8052. {
  8053. BeginEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8054. }
  8055. EmitAssignment(nullptr, loopNode->pnodeLval, loopNode->itemLocation, byteCodeGenerator, funcInfo);
  8056. // The StartStatement is already done in the caller of this function.
  8057. byteCodeGenerator->EndStatement(loopNode->pnodeLval);
  8058. funcInfo->ReleaseReference(loopNode->pnodeLval);
  8059. Emit(loopNode->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  8060. funcInfo->ReleaseLoc(loopNode->pnodeBody);
  8061. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8062. {
  8063. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8064. }
  8065. funcInfo->ReleaseTmpRegister(loopNode->itemLocation);
  8066. if (loopNode->emitLabels)
  8067. {
  8068. byteCodeGenerator->Writer()->MarkLabel(loopNode->continueLabel);
  8069. }
  8070. byteCodeGenerator->Writer()->Br(loopEntrance);
  8071. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  8072. if (loopNode->emitLabels)
  8073. {
  8074. byteCodeGenerator->Writer()->MarkLabel(loopNode->breakLabel);
  8075. }
  8076. }
  8077. void EmitForIn(ParseNodeForInOrForOf *loopNode,
  8078. Js::ByteCodeLabel loopEntrance,
  8079. Js::ByteCodeLabel continuePastLoop,
  8080. ByteCodeGenerator *byteCodeGenerator,
  8081. FuncInfo *funcInfo,
  8082. BOOL fReturnValue)
  8083. {
  8084. Assert(loopNode->nop == knopForIn);
  8085. Assert(loopNode->location == Js::Constants::NoRegister);
  8086. // Grab registers for the enumerator and for the current enumerated item.
  8087. // The enumerator register will be released after this call returns.
  8088. loopNode->itemLocation = funcInfo->AcquireTmpRegister();
  8089. uint forInLoopLevel = funcInfo->AcquireForInLoopLevel();
  8090. // get enumerator from the collection
  8091. byteCodeGenerator->Writer()->Reg1Unsigned1(Js::OpCode::InitForInEnumerator, loopNode->pnodeObj->location, forInLoopLevel);
  8092. // The StartStatement is already done in the caller of the current function, which is EmitForInOrForOf
  8093. byteCodeGenerator->EndStatement(loopNode);
  8094. // Need to increment loop count whether we are going into profile or not for HasLoop()
  8095. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8096. loopNode->loopId = loopId;
  8097. // The EndStatement will happen in the EmitForInOfLoopBody function
  8098. byteCodeGenerator->StartStatement(loopNode->pnodeLval);
  8099. // branch past loop when MoveAndGetNext returns nullptr
  8100. byteCodeGenerator->Writer()->BrReg1Unsigned1(Js::OpCode::BrOnEmpty, continuePastLoop, loopNode->itemLocation, forInLoopLevel);
  8101. EmitForInOfLoopBody(loopNode, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, fReturnValue);
  8102. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8103. funcInfo->ReleaseForInLoopLevel(forInLoopLevel);
  8104. if (!byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8105. {
  8106. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8107. }
  8108. }
  8109. void EmitForInOrForOf(ParseNodeForInOrForOf *loopNode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue)
  8110. {
  8111. bool isForIn = (loopNode->nop == knopForIn);
  8112. Assert(isForIn || loopNode->nop == knopForOf);
  8113. BeginEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8114. byteCodeGenerator->StartStatement(loopNode);
  8115. if (!isForIn)
  8116. {
  8117. funcInfo->AcquireLoc(loopNode);
  8118. }
  8119. // Record the branch bytecode offset.
  8120. // This is used for "ignore exception" and "set next stmt" scenarios. See ProbeContainer::GetNextUserStatementOffsetForAdvance:
  8121. // If there is a branch recorded between current offset and next stmt offset, we'll use offset of the branch recorded,
  8122. // otherwise use offset of next stmt.
  8123. // The idea here is that when we bail out after ignore exception, we need to bail out to the beginning of the ForIn,
  8124. // but currently ForIn stmt starts at the condition part, which is needed for correct handling of break point on ForIn
  8125. // (break every time on the loop back edge) and correct display of current statement under debugger.
  8126. // See WinBlue 231880 for details.
  8127. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_All);
  8128. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled() &&
  8129. loopNode->pnodeBlock->HasBlockScopedContent())
  8130. {
  8131. byteCodeGenerator->Writer()->RecordForInOrOfCollectionScope();
  8132. }
  8133. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  8134. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  8135. if (loopNode->pnodeLval->nop == knopVarDecl)
  8136. {
  8137. EmitReference(loopNode->pnodeLval, byteCodeGenerator, funcInfo);
  8138. }
  8139. Emit(loopNode->pnodeObj, byteCodeGenerator, funcInfo, false); // evaluate collection expression
  8140. funcInfo->ReleaseLoc(loopNode->pnodeObj);
  8141. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8142. {
  8143. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8144. if (loopNode->pnodeBlock->scope != nullptr)
  8145. {
  8146. loopNode->pnodeBlock->scope->ForEachSymbol([](Symbol *sym) {
  8147. sym->SetIsTrackedForDebugger(false);
  8148. });
  8149. }
  8150. }
  8151. if (isForIn)
  8152. {
  8153. EmitForIn(loopNode, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, fReturnValue);
  8154. if (!byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8155. {
  8156. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8157. }
  8158. return;
  8159. }
  8160. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  8161. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrNeq_A, skipThrow, loopNode->pnodeObj->location, funcInfo->undefinedConstantRegister);
  8162. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ObjectCoercible));
  8163. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  8164. Js::RegSlot regException = Js::Constants::NoRegister;
  8165. Js::RegSlot regOffset = Js::Constants::NoRegister;
  8166. // These two temp variables store the information of return function to be called or not.
  8167. // one variable is used for catch block and one is used for finally block. These variable will be set to true when we think that return function
  8168. // to be called on abrupt loop break.
  8169. // Why two variables? since these are temps and JIT does like not flow if single variable is used in multiple blocks.
  8170. Js::RegSlot shouldCallReturnFunctionLocation = funcInfo->AcquireTmpRegister();
  8171. Js::RegSlot shouldCallReturnFunctionLocationFinally = funcInfo->AcquireTmpRegister();
  8172. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  8173. if (isCoroutine)
  8174. {
  8175. regException = funcInfo->AcquireTmpRegister();
  8176. regOffset = funcInfo->AcquireTmpRegister();
  8177. }
  8178. // Grab registers for the enumerator and for the current enumerated item.
  8179. // The enumerator register will be released after this call returns.
  8180. loopNode->itemLocation = funcInfo->AcquireTmpRegister();
  8181. // We want call profile information on the @@iterator call, so instead of adding a GetForOfIterator bytecode op
  8182. // to do all the following work in a helper do it explicitly in bytecode so that the @@iterator call is exposed
  8183. // to the profiler and JIT.
  8184. byteCodeGenerator->SetHasFinally(true);
  8185. byteCodeGenerator->SetHasTry(true);
  8186. byteCodeGenerator->TopFuncInfo()->byteCodeFunction->SetDontInline(true);
  8187. // do a ToObject on the collection
  8188. Js::RegSlot tmpObj = funcInfo->AcquireTmpRegister();
  8189. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Obj, tmpObj, loopNode->pnodeObj->location);
  8190. EmitGetIterator(loopNode->location, tmpObj, byteCodeGenerator, funcInfo);
  8191. funcInfo->ReleaseTmpRegister(tmpObj);
  8192. // The whole loop is surrounded with try..catch..finally - in order to capture the abrupt completion.
  8193. Js::ByteCodeLabel finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  8194. Js::ByteCodeLabel catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  8195. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  8196. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  8197. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  8198. ByteCodeGenerator::TryScopeRecord tryRecForTryFinally(Js::OpCode::TryFinallyWithYield, finallyLabel);
  8199. if (isCoroutine)
  8200. {
  8201. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  8202. tryRecForTryFinally.reg1 = regException;
  8203. tryRecForTryFinally.reg2 = regOffset;
  8204. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTryFinally);
  8205. }
  8206. else
  8207. {
  8208. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  8209. }
  8210. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  8211. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryCatch, catchLabel);
  8212. if (isCoroutine)
  8213. {
  8214. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  8215. }
  8216. byteCodeGenerator->EndStatement(loopNode);
  8217. // Need to increment loop count whether we are going into profile or not for HasLoop()
  8218. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8219. loopNode->loopId = loopId;
  8220. byteCodeGenerator->StartStatement(loopNode->pnodeLval);
  8221. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  8222. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  8223. EmitIteratorNext(loopNode->itemLocation, loopNode->location, Js::Constants::NoRegister, byteCodeGenerator, funcInfo);
  8224. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  8225. EmitIteratorComplete(doneLocation, loopNode->itemLocation, byteCodeGenerator, funcInfo);
  8226. // branch past loop if the result's done property is truthy
  8227. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, continuePastLoop, doneLocation);
  8228. funcInfo->ReleaseTmpRegister(doneLocation);
  8229. // otherwise put result's value property in itemLocation
  8230. EmitIteratorValue(loopNode->itemLocation, loopNode->itemLocation, byteCodeGenerator, funcInfo);
  8231. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  8232. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  8233. EmitForInOfLoopBody(loopNode, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, fReturnValue);
  8234. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8235. EmitCatchAndFinallyBlocks(catchLabel,
  8236. finallyLabel,
  8237. loopNode->location,
  8238. shouldCallReturnFunctionLocation,
  8239. shouldCallReturnFunctionLocationFinally,
  8240. regException,
  8241. regOffset,
  8242. byteCodeGenerator,
  8243. funcInfo);
  8244. if (!byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8245. {
  8246. EndEmitBlock(loopNode->pnodeBlock, byteCodeGenerator, funcInfo);
  8247. }
  8248. }
  8249. void EmitArrayLiteral(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8250. {
  8251. funcInfo->AcquireLoc(pnode);
  8252. ParseNode *args = pnode->AsParseNodeUni()->pnode1;
  8253. if (args == nullptr)
  8254. {
  8255. byteCodeGenerator->Writer()->Reg1Unsigned1(
  8256. pnode->AsParseNodeArrLit()->hasMissingValues ? Js::OpCode::NewScArrayWithMissingValues : Js::OpCode::NewScArray,
  8257. pnode->location,
  8258. ByteCodeGenerator::DefaultArraySize);
  8259. }
  8260. else
  8261. {
  8262. SetNewArrayElements(pnode, pnode->location, byteCodeGenerator, funcInfo);
  8263. }
  8264. }
  8265. void EmitJumpCleanup(ParseNodeStmt *pnode, ParseNode *pnodeTarget, ByteCodeGenerator *byteCodeGenerator, FuncInfo * funcInfo)
  8266. {
  8267. for (; pnode != pnodeTarget; pnode = pnode->pnodeOuter)
  8268. {
  8269. switch (pnode->nop)
  8270. {
  8271. case knopTry:
  8272. case knopCatch:
  8273. case knopFinally:
  8274. // We insert OpCode::Leave when there is a 'return' inside try/catch/finally.
  8275. // This is for flow control and does not participate in identifying boundaries of try/catch blocks,
  8276. // thus we shouldn't call RecordCrossFrameEntryExitRecord() here.
  8277. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  8278. break;
  8279. case knopForOf:
  8280. #if ENABLE_PROFILE_INFO
  8281. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(funcInfo->GetParsedFunctionBody()))
  8282. {
  8283. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::ProfiledLoopEnd, pnode->AsParseNodeLoop()->loopId);
  8284. }
  8285. #endif
  8286. // The ForOf loop code is wrapped around try..catch..finally - Forcing couple Leave bytecode over here
  8287. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  8288. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  8289. break;
  8290. #if ENABLE_PROFILE_INFO
  8291. case knopWhile:
  8292. case knopDoWhile:
  8293. case knopFor:
  8294. case knopForIn:
  8295. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(funcInfo->GetParsedFunctionBody()))
  8296. {
  8297. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::ProfiledLoopEnd, pnode->AsParseNodeLoop()->loopId);
  8298. }
  8299. break;
  8300. #endif
  8301. }
  8302. }
  8303. }
  8304. void EmitBinaryOpnds(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8305. {
  8306. // If opnd2 can overwrite opnd1, make sure the value of opnd1 is stashed away.
  8307. if (MayHaveSideEffectOnNode(pnode1, pnode2))
  8308. {
  8309. SaveOpndValue(pnode1, funcInfo);
  8310. }
  8311. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  8312. if (pnode1->nop == knopComputedName && pnode2->nop == knopClassDecl &&
  8313. (pnode2->AsParseNodeClass()->pnodeConstructor == nullptr || pnode2->AsParseNodeClass()->pnodeConstructor->nop != knopVarDecl))
  8314. {
  8315. Emit(pnode2, byteCodeGenerator, funcInfo, false, false, pnode1);
  8316. }
  8317. else
  8318. {
  8319. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  8320. }
  8321. }
  8322. void EmitBinaryReference(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fLoadLhs)
  8323. {
  8324. // Make sure that the RHS of an assignment doesn't kill the opnd's of the expression on the LHS.
  8325. switch (pnode1->nop)
  8326. {
  8327. case knopName:
  8328. if (fLoadLhs && MayHaveSideEffectOnNode(pnode1, pnode2))
  8329. {
  8330. // Given x op y, y may kill x, so stash x.
  8331. // Note that this only matters if we're loading x prior to the op.
  8332. SaveOpndValue(pnode1, funcInfo);
  8333. }
  8334. break;
  8335. case knopDot:
  8336. if (fLoadLhs)
  8337. {
  8338. // We're loading the value of the LHS before the RHS, so make sure the LHS gets a register first.
  8339. funcInfo->AcquireLoc(pnode1);
  8340. }
  8341. if (MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode1, pnode2))
  8342. {
  8343. // Given x.y op z, z may kill x, so stash x away.
  8344. SaveOpndValue(pnode1->AsParseNodeBin()->pnode1, funcInfo);
  8345. }
  8346. break;
  8347. case knopIndex:
  8348. if (fLoadLhs)
  8349. {
  8350. // We're loading the value of the LHS before the RHS, so make sure the LHS gets a register first.
  8351. funcInfo->AcquireLoc(pnode1);
  8352. }
  8353. if (MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode1, pnode2) ||
  8354. MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode1, pnode1->AsParseNodeBin()->pnode2))
  8355. {
  8356. // Given x[y] op z, y or z may kill x, so stash x away.
  8357. SaveOpndValue(pnode1->AsParseNodeBin()->pnode1, funcInfo);
  8358. }
  8359. if (MayHaveSideEffectOnNode(pnode1->AsParseNodeBin()->pnode2, pnode2))
  8360. {
  8361. // Given x[y] op z, z may kill y, so stash y away.
  8362. // But make sure that x gets a register before y.
  8363. funcInfo->AcquireLoc(pnode1->AsParseNodeBin()->pnode1);
  8364. SaveOpndValue(pnode1->AsParseNodeBin()->pnode2, funcInfo);
  8365. }
  8366. break;
  8367. }
  8368. if (fLoadLhs)
  8369. {
  8370. // Emit code to load the value of the LHS.
  8371. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  8372. }
  8373. else
  8374. {
  8375. // Emit code to evaluate the LHS opnds, but don't load the LHS's value.
  8376. EmitReference(pnode1, byteCodeGenerator, funcInfo);
  8377. }
  8378. // Evaluate the RHS.
  8379. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  8380. }
  8381. void EmitUseBeforeDeclarationRuntimeError(ByteCodeGenerator * byteCodeGenerator, Js::RegSlot location)
  8382. {
  8383. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_UseBeforeDeclaration));
  8384. if (location != Js::Constants::NoRegister)
  8385. {
  8386. // Optionally load something into register in order to do not confuse IRBuilder. This value will never be used.
  8387. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, location);
  8388. }
  8389. }
  8390. void EmitUseBeforeDeclaration(Symbol *sym, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8391. {
  8392. // Don't emit static use-before-declaration error in a closure or dynamic scope case. We detect such cases with dynamic checks,
  8393. // if necessary.
  8394. if (sym != nullptr &&
  8395. !sym->GetIsModuleExportStorage() &&
  8396. sym->GetNeedDeclaration() &&
  8397. byteCodeGenerator->GetCurrentScope()->HasStaticPathToAncestor(sym->GetScope()) &&
  8398. sym->GetScope()->GetFunc() == funcInfo)
  8399. {
  8400. EmitUseBeforeDeclarationRuntimeError(byteCodeGenerator, Js::Constants::NoRegister);
  8401. }
  8402. }
  8403. void EmitBinary(Js::OpCode opcode, ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8404. {
  8405. byteCodeGenerator->StartStatement(pnode);
  8406. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  8407. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  8408. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  8409. funcInfo->AcquireLoc(pnode);
  8410. byteCodeGenerator->Writer()->Reg3(opcode,
  8411. pnode->location,
  8412. pnode->AsParseNodeBin()->pnode1->location,
  8413. pnode->AsParseNodeBin()->pnode2->location);
  8414. byteCodeGenerator->EndStatement(pnode);
  8415. }
  8416. bool CollectConcat(ParseNode *pnodeAdd, DListCounted<ParseNode *, ArenaAllocator>& concatOpnds, ArenaAllocator *arenaAllocator)
  8417. {
  8418. Assert(pnodeAdd->nop == knopAdd);
  8419. Assert(pnodeAdd->CanFlattenConcatExpr());
  8420. bool doConcatString = false;
  8421. DList<ParseNode*, ArenaAllocator> pnodeStack(arenaAllocator);
  8422. pnodeStack.Prepend(pnodeAdd->AsParseNodeBin()->pnode2);
  8423. ParseNode * pnode = pnodeAdd->AsParseNodeBin()->pnode1;
  8424. while (true)
  8425. {
  8426. if (!pnode->CanFlattenConcatExpr())
  8427. {
  8428. concatOpnds.Append(pnode);
  8429. }
  8430. else if (pnode->nop == knopStr)
  8431. {
  8432. concatOpnds.Append(pnode);
  8433. // Detect if there are any string larger then the append size limit.
  8434. // If there are, we can do concat; otherwise, still use add so we will not lose the AddLeftDead opportunities.
  8435. doConcatString = doConcatString || !Js::CompoundString::ShouldAppendChars(pnode->AsParseNodeStr()->pid->Cch());
  8436. }
  8437. else
  8438. {
  8439. Assert(pnode->nop == knopAdd);
  8440. pnodeStack.Prepend(pnode->AsParseNodeBin()->pnode2);
  8441. pnode = pnode->AsParseNodeBin()->pnode1;
  8442. continue;
  8443. }
  8444. if (pnodeStack.Empty())
  8445. {
  8446. break;
  8447. }
  8448. pnode = pnodeStack.Head();
  8449. pnodeStack.RemoveHead();
  8450. }
  8451. return doConcatString;
  8452. }
  8453. void EmitConcat3(ParseNode *pnode, ParseNode *pnode1, ParseNode *pnode2, ParseNode *pnode3, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8454. {
  8455. byteCodeGenerator->StartStatement(pnode);
  8456. if (MayHaveSideEffectOnNode(pnode1, pnode2) || MayHaveSideEffectOnNode(pnode1, pnode3))
  8457. {
  8458. SaveOpndValue(pnode1, funcInfo);
  8459. }
  8460. if (MayHaveSideEffectOnNode(pnode2, pnode3))
  8461. {
  8462. SaveOpndValue(pnode2, funcInfo);
  8463. }
  8464. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  8465. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  8466. Emit(pnode3, byteCodeGenerator, funcInfo, false);
  8467. funcInfo->ReleaseLoc(pnode3);
  8468. funcInfo->ReleaseLoc(pnode2);
  8469. funcInfo->ReleaseLoc(pnode1);
  8470. funcInfo->AcquireLoc(pnode);
  8471. byteCodeGenerator->Writer()->Reg4(Js::OpCode::Concat3,
  8472. pnode->location,
  8473. pnode1->location,
  8474. pnode2->location,
  8475. pnode3->location);
  8476. byteCodeGenerator->EndStatement(pnode);
  8477. }
  8478. void EmitNewConcatStrMulti(ParseNode *pnode, uint8 count, ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8479. {
  8480. EmitBinaryOpnds(pnode1, pnode2, byteCodeGenerator, funcInfo);
  8481. funcInfo->ReleaseLoc(pnode2);
  8482. funcInfo->ReleaseLoc(pnode1);
  8483. funcInfo->AcquireLoc(pnode);
  8484. byteCodeGenerator->Writer()->Reg3B1(Js::OpCode::NewConcatStrMulti,
  8485. pnode->location,
  8486. pnode1->location,
  8487. pnode2->location,
  8488. count);
  8489. }
  8490. void EmitAdd(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8491. {
  8492. Assert(pnode->nop == knopAdd);
  8493. if (pnode->CanFlattenConcatExpr())
  8494. {
  8495. // We should only have a string concat if the feature is on.
  8496. Assert(!PHASE_OFF1(Js::ByteCodeConcatExprOptPhase));
  8497. DListCounted<ParseNode*, ArenaAllocator> concatOpnds(byteCodeGenerator->GetAllocator());
  8498. bool doConcatString = CollectConcat(pnode, concatOpnds, byteCodeGenerator->GetAllocator());
  8499. if (doConcatString)
  8500. {
  8501. uint concatCount = concatOpnds.Count();
  8502. Assert(concatCount >= 2);
  8503. // Don't do concatN if the number is too high
  8504. // CONSIDER: although we could have done multiple ConcatNs
  8505. if (concatCount > 2 && concatCount <= UINT8_MAX)
  8506. {
  8507. #if DBG
  8508. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  8509. #endif
  8510. ParseNode * pnode1 = concatOpnds.Head();
  8511. concatOpnds.RemoveHead();
  8512. ParseNode * pnode2 = concatOpnds.Head();
  8513. concatOpnds.RemoveHead();
  8514. if (concatCount == 3)
  8515. {
  8516. OUTPUT_TRACE_DEBUGONLY(Js::ByteCodeConcatExprOptPhase, _u("%s(%s) offset:#%d : Concat3\n"),
  8517. funcInfo->GetParsedFunctionBody()->GetDisplayName(),
  8518. funcInfo->GetParsedFunctionBody()->GetDebugNumberSet(debugStringBuffer),
  8519. byteCodeGenerator->Writer()->ByteCodeDataSize());
  8520. EmitConcat3(pnode, pnode1, pnode2, concatOpnds.Head(), byteCodeGenerator, funcInfo);
  8521. return;
  8522. }
  8523. OUTPUT_TRACE_DEBUGONLY(Js::ByteCodeConcatExprOptPhase, _u("%s(%s) offset:#%d: ConcatMulti %d\n"),
  8524. funcInfo->GetParsedFunctionBody()->GetDisplayName(),
  8525. funcInfo->GetParsedFunctionBody()->GetDebugNumberSet(debugStringBuffer),
  8526. byteCodeGenerator->Writer()->ByteCodeDataSize(), concatCount);
  8527. byteCodeGenerator->StartStatement(pnode);
  8528. funcInfo->AcquireLoc(pnode);
  8529. // CONSIDER: this may cause the backend not able CSE repeating pattern within the concat.
  8530. EmitNewConcatStrMulti(pnode, (uint8)concatCount, pnode1, pnode2, byteCodeGenerator, funcInfo);
  8531. uint i = 2;
  8532. do
  8533. {
  8534. ParseNode * currNode = concatOpnds.Head();
  8535. concatOpnds.RemoveHead();
  8536. ParseNode * currNode2 = concatOpnds.Head();
  8537. concatOpnds.RemoveHead();
  8538. EmitBinaryOpnds(currNode, currNode2, byteCodeGenerator, funcInfo);
  8539. funcInfo->ReleaseLoc(currNode2);
  8540. funcInfo->ReleaseLoc(currNode);
  8541. byteCodeGenerator->Writer()->Reg3B1(
  8542. Js::OpCode::SetConcatStrMultiItem2, pnode->location, currNode->location, currNode2->location, (uint8)i);
  8543. i += 2;
  8544. } while (concatOpnds.Count() > 1);
  8545. if (!concatOpnds.Empty())
  8546. {
  8547. ParseNode * currNode = concatOpnds.Head();
  8548. Emit(currNode, byteCodeGenerator, funcInfo, false);
  8549. funcInfo->ReleaseLoc(currNode);
  8550. byteCodeGenerator->Writer()->Reg2B1(
  8551. Js::OpCode::SetConcatStrMultiItem, pnode->location, currNode->location, (uint8)i);
  8552. i++;
  8553. }
  8554. Assert(concatCount == i);
  8555. byteCodeGenerator->EndStatement(pnode);
  8556. return;
  8557. }
  8558. }
  8559. // Since we collected all the node already, let's just emit them instead of doing it recursively.
  8560. byteCodeGenerator->StartStatement(pnode);
  8561. ParseNode * currNode = concatOpnds.Head();
  8562. concatOpnds.RemoveHead();
  8563. ParseNode * currNode2 = concatOpnds.Head();
  8564. concatOpnds.RemoveHead();
  8565. EmitBinaryOpnds(currNode, currNode2, byteCodeGenerator, funcInfo);
  8566. funcInfo->ReleaseLoc(currNode2);
  8567. funcInfo->ReleaseLoc(currNode);
  8568. Js::RegSlot dstReg = funcInfo->AcquireLoc(pnode);
  8569. byteCodeGenerator->Writer()->Reg3(
  8570. Js::OpCode::Add_A, dstReg, currNode->location, currNode2->location);
  8571. while (!concatOpnds.Empty())
  8572. {
  8573. currNode = concatOpnds.Head();
  8574. concatOpnds.RemoveHead();
  8575. Emit(currNode, byteCodeGenerator, funcInfo, false);
  8576. funcInfo->ReleaseLoc(currNode);
  8577. byteCodeGenerator->Writer()->Reg3(
  8578. Js::OpCode::Add_A, dstReg, dstReg, currNode->location);
  8579. }
  8580. byteCodeGenerator->EndStatement(pnode);
  8581. }
  8582. else
  8583. {
  8584. EmitBinary(Js::OpCode::Add_A, pnode, byteCodeGenerator, funcInfo);
  8585. }
  8586. }
  8587. void ByteCodeGenerator::EmitLeaveOpCodesBeforeYield()
  8588. {
  8589. for (TryScopeRecord* node = this->tryScopeRecordsList.Tail(); node != nullptr; node = node->Previous())
  8590. {
  8591. switch (node->op)
  8592. {
  8593. case Js::OpCode::TryFinallyWithYield:
  8594. this->Writer()->Empty(Js::OpCode::LeaveNull);
  8595. break;
  8596. case Js::OpCode::TryCatch:
  8597. case Js::OpCode::ResumeFinally:
  8598. case Js::OpCode::ResumeCatch:
  8599. this->Writer()->Empty(Js::OpCode::Leave);
  8600. break;
  8601. default:
  8602. AssertMsg(false, "Unexpected OpCode before Yield in the Try-Catch-Finally cache for generator!");
  8603. break;
  8604. }
  8605. }
  8606. }
  8607. void ByteCodeGenerator::EmitTryBlockHeadersAfterYield()
  8608. {
  8609. for (TryScopeRecord* node = this->tryScopeRecordsList.Head(); node != nullptr; node = node->Next())
  8610. {
  8611. switch (node->op)
  8612. {
  8613. case Js::OpCode::TryCatch:
  8614. this->Writer()->Br(node->op, node->label);
  8615. break;
  8616. case Js::OpCode::TryFinallyWithYield:
  8617. case Js::OpCode::ResumeFinally:
  8618. this->Writer()->BrReg2(node->op, node->label, node->reg1, node->reg2);
  8619. break;
  8620. case Js::OpCode::ResumeCatch:
  8621. this->Writer()->Empty(node->op);
  8622. break;
  8623. default:
  8624. AssertMsg(false, "Unexpected OpCode after yield in the Try-Catch-Finally cache for generator!");
  8625. break;
  8626. }
  8627. }
  8628. }
  8629. void EmitYield(Js::RegSlot inputLocation, Js::RegSlot resultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot yieldStarIterator)
  8630. {
  8631. // If the bytecode emitted by this function is part of 'yield*', inputLocation is the object
  8632. // returned by the iterable's next/return/throw method. Otherwise, it is the yielded value.
  8633. if (yieldStarIterator == Js::Constants::NoRegister)
  8634. {
  8635. byteCodeGenerator->Writer()->Reg1(Js::OpCode::NewScObjectSimple, funcInfo->yieldRegister);
  8636. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->yieldRegister, Js::PropertyIds::value, false, true);
  8637. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::StFld, inputLocation, funcInfo->yieldRegister, cacheId);
  8638. cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->yieldRegister, Js::PropertyIds::done, false, true);
  8639. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::StFld, funcInfo->falseConstantRegister, funcInfo->yieldRegister, cacheId);
  8640. }
  8641. else
  8642. {
  8643. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, funcInfo->yieldRegister, inputLocation);
  8644. }
  8645. byteCodeGenerator->EmitLeaveOpCodesBeforeYield();
  8646. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Yield, funcInfo->yieldRegister, funcInfo->yieldRegister);
  8647. byteCodeGenerator->EmitTryBlockHeadersAfterYield();
  8648. if (yieldStarIterator == Js::Constants::NoRegister)
  8649. {
  8650. byteCodeGenerator->Writer()->Reg2(Js::OpCode::ResumeYield, resultLocation, funcInfo->yieldRegister);
  8651. }
  8652. else
  8653. {
  8654. byteCodeGenerator->Writer()->Reg3(Js::OpCode::ResumeYieldStar, resultLocation, funcInfo->yieldRegister, yieldStarIterator);
  8655. }
  8656. }
  8657. void EmitYieldStar(ParseNodeUni* yieldStarNode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8658. {
  8659. funcInfo->AcquireLoc(yieldStarNode);
  8660. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  8661. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  8662. Js::RegSlot iteratorLocation = funcInfo->AcquireTmpRegister();
  8663. // Evaluate operand
  8664. Emit(yieldStarNode->pnode1, byteCodeGenerator, funcInfo, false);
  8665. funcInfo->ReleaseLoc(yieldStarNode->pnode1);
  8666. EmitGetIterator(iteratorLocation, yieldStarNode->pnode1->location, byteCodeGenerator, funcInfo);
  8667. // Call the iterator's next()
  8668. EmitIteratorNext(yieldStarNode->location, iteratorLocation, funcInfo->undefinedConstantRegister, byteCodeGenerator, funcInfo);
  8669. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8670. // since a yield* doesn't have a user defined body, we cannot return from this loop
  8671. // which means we don't need to support EmitJumpCleanup() and there do not need to
  8672. // remember the loopId like the loop statements do.
  8673. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  8674. EmitIteratorComplete(doneLocation, yieldStarNode->location, byteCodeGenerator, funcInfo);
  8675. // branch past the loop if the done property is truthy
  8676. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, continuePastLoop, doneLocation);
  8677. funcInfo->ReleaseTmpRegister(doneLocation);
  8678. EmitYield(yieldStarNode->location, yieldStarNode->location, byteCodeGenerator, funcInfo, iteratorLocation);
  8679. funcInfo->ReleaseTmpRegister(iteratorLocation);
  8680. byteCodeGenerator->Writer()->Br(loopEntrance);
  8681. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  8682. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8683. // Put the iterator result's value in yieldStarNode->location.
  8684. // It will be used as the result value of the yield* operator expression.
  8685. EmitIteratorValue(yieldStarNode->location, yieldStarNode->location, byteCodeGenerator, funcInfo);
  8686. }
  8687. void TrackIntConstantsOnGlobalUserObject(ByteCodeGenerator *byteCodeGenerator, bool isSymGlobalAndSingleAssignment, Js::PropertyId propertyId)
  8688. {
  8689. if (isSymGlobalAndSingleAssignment)
  8690. {
  8691. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalUserObject(propertyId);
  8692. }
  8693. }
  8694. void TrackIntConstantsOnGlobalObject(ByteCodeGenerator *byteCodeGenerator, bool isSymGlobalAndSingleAssignment, Js::PropertyId propertyId)
  8695. {
  8696. if (isSymGlobalAndSingleAssignment)
  8697. {
  8698. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalObject(propertyId);
  8699. }
  8700. }
  8701. void TrackIntConstantsOnGlobalObject(ByteCodeGenerator *byteCodeGenerator, Symbol *sym)
  8702. {
  8703. if (sym && sym->GetIsGlobal() && sym->IsAssignedOnce())
  8704. {
  8705. Js::PropertyId propertyId = sym->EnsurePosition(byteCodeGenerator);
  8706. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalObject(propertyId);
  8707. }
  8708. }
  8709. void TrackMemberNodesInObjectForIntConstants(ByteCodeGenerator *byteCodeGenerator, ParseNodePtr objNode)
  8710. {
  8711. Assert(objNode->nop == knopObject);
  8712. ParseNodePtr memberList = objNode->AsParseNodeUni()->pnode1;
  8713. while (memberList != nullptr)
  8714. {
  8715. ParseNodePtr memberNode = memberList->nop == knopList ? memberList->AsParseNodeBin()->pnode1 : memberList;
  8716. ParseNodePtr memberNameNode = memberNode->AsParseNodeBin()->pnode1;
  8717. ParseNodePtr memberValNode = memberNode->AsParseNodeBin()->pnode2;
  8718. if (memberNameNode->nop != knopComputedName && memberValNode->nop == knopInt)
  8719. {
  8720. Js::PropertyId propertyId = memberNameNode->AsParseNodeStr()->pid->GetPropertyId();
  8721. TrackIntConstantsOnGlobalUserObject(byteCodeGenerator, true, propertyId);
  8722. }
  8723. memberList = memberList->nop == knopList ? memberList->AsParseNodeBin()->pnode2 : nullptr;
  8724. }
  8725. }
  8726. void TrackGlobalIntAssignmentsForknopDotProps(ParseNodePtr knopDotNode, ByteCodeGenerator * byteCodeGenerator)
  8727. {
  8728. Assert(knopDotNode->nop == knopDot);
  8729. ParseNodePtr objectNode = knopDotNode->AsParseNodeBin()->pnode1;
  8730. ParseNodeName * propertyNode = knopDotNode->AsParseNodeBin()->pnode2->AsParseNodeName();
  8731. bool isSymGlobalAndSingleAssignment = false;
  8732. if (objectNode->nop == knopName)
  8733. {
  8734. if (ByteCodeGenerator::IsThis(objectNode))
  8735. {
  8736. // Assume 'this' always refer to GlobalObject
  8737. // Cases like "this.a = "
  8738. isSymGlobalAndSingleAssignment = propertyNode->pid->IsSingleAssignment();
  8739. Js::PropertyId propertyId = propertyNode->PropertyIdFromNameNode();
  8740. TrackIntConstantsOnGlobalObject(byteCodeGenerator, isSymGlobalAndSingleAssignment, propertyId);
  8741. }
  8742. else
  8743. {
  8744. Symbol * sym = objectNode->AsParseNodeName()->sym;
  8745. isSymGlobalAndSingleAssignment = sym && sym->GetIsGlobal() && sym->IsAssignedOnce() && propertyNode->pid->IsSingleAssignment();
  8746. Js::PropertyId propertyId = propertyNode->PropertyIdFromNameNode();
  8747. TrackIntConstantsOnGlobalUserObject(byteCodeGenerator, isSymGlobalAndSingleAssignment, propertyId);
  8748. }
  8749. }
  8750. }
  8751. void TrackGlobalIntAssignments(ParseNodePtr pnode, ByteCodeGenerator * byteCodeGenerator)
  8752. {
  8753. // Track the Global Int Constant properties' assignments here.
  8754. uint nodeType = ParseNode::Grfnop(pnode->nop);
  8755. if (nodeType & fnopAsg)
  8756. {
  8757. if (nodeType & fnopBin)
  8758. {
  8759. ParseNodePtr lhs = pnode->AsParseNodeBin()->pnode1;
  8760. ParseNodePtr rhs = pnode->AsParseNodeBin()->pnode2;
  8761. Assert(lhs && rhs);
  8762. // Don't track other than integers and objects with member nodes.
  8763. if (rhs->nop == knopObject)
  8764. {
  8765. TrackMemberNodesInObjectForIntConstants(byteCodeGenerator, rhs);
  8766. }
  8767. else if (rhs->nop != knopInt &&
  8768. ((rhs->nop != knopLsh && rhs->nop != knopRsh) || (rhs->AsParseNodeBin()->pnode1->nop != knopInt || rhs->AsParseNodeBin()->pnode2->nop != knopInt)))
  8769. {
  8770. return;
  8771. }
  8772. if (lhs->nop == knopName)
  8773. {
  8774. // Handle "a = <Integer>" cases here
  8775. Symbol * sym = lhs->AsParseNodeName()->sym;
  8776. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  8777. }
  8778. else if (lhs->nop == knopDot && lhs->AsParseNodeBin()->pnode2->nop == knopName)
  8779. {
  8780. // Cases like "obj.a = <Integer>"
  8781. TrackGlobalIntAssignmentsForknopDotProps(lhs, byteCodeGenerator);
  8782. }
  8783. }
  8784. else if (nodeType & fnopUni)
  8785. {
  8786. ParseNodePtr lhs = pnode->AsParseNodeUni()->pnode1;
  8787. if (lhs->nop == knopName)
  8788. {
  8789. // Cases like "a++"
  8790. Symbol * sym = lhs->AsParseNodeName()->sym;
  8791. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  8792. }
  8793. else if (lhs->nop == knopDot && lhs->AsParseNodeBin()->pnode2->nop == knopName)
  8794. {
  8795. // Cases like "obj.a++"
  8796. TrackGlobalIntAssignmentsForknopDotProps(lhs, byteCodeGenerator);
  8797. }
  8798. }
  8799. }
  8800. }
  8801. void Emit(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue, bool isConstructorCall, ParseNode * bindPnode, bool isTopLevel)
  8802. {
  8803. if (pnode == nullptr)
  8804. {
  8805. return;
  8806. }
  8807. ThreadContext::ProbeCurrentStackNoDispose(Js::Constants::MinStackByteCodeVisitor, byteCodeGenerator->GetScriptContext());
  8808. TrackGlobalIntAssignments(pnode, byteCodeGenerator);
  8809. // printNop(pnode->nop);
  8810. switch (pnode->nop)
  8811. {
  8812. case knopList:
  8813. EmitList(pnode, byteCodeGenerator, funcInfo);
  8814. break;
  8815. case knopInt:
  8816. // currently, these are loaded at the top
  8817. break;
  8818. // PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  8819. case knopFlt:
  8820. // currently, these are loaded at the top
  8821. break;
  8822. // PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  8823. case knopStr:
  8824. // TODO: protocol for combining string constants
  8825. break;
  8826. // PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  8827. case knopRegExp:
  8828. funcInfo->GetParsedFunctionBody()->SetLiteralRegex(pnode->AsParseNodeRegExp()->regexPatternIndex, pnode->AsParseNodeRegExp()->regexPattern);
  8829. byteCodeGenerator->Writer()->Reg1Unsigned1(Js::OpCode::NewRegEx, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeRegExp()->regexPatternIndex);
  8830. break;
  8831. // PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  8832. case knopNull:
  8833. // enregistered
  8834. break;
  8835. // PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  8836. case knopFalse:
  8837. // enregistered
  8838. break;
  8839. // PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  8840. case knopTrue:
  8841. // enregistered
  8842. break;
  8843. // PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  8844. case knopEmpty:
  8845. break;
  8846. // Unary operators.
  8847. // PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  8848. case knopNot:
  8849. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8850. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  8851. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  8852. byteCodeGenerator->Writer()->Reg2(
  8853. Js::OpCode::Not_A, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeUni()->pnode1->location);
  8854. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8855. break;
  8856. // PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  8857. case knopNeg:
  8858. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8859. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  8860. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  8861. funcInfo->AcquireLoc(pnode);
  8862. byteCodeGenerator->Writer()->Reg2(
  8863. Js::OpCode::Neg_A, pnode->location, pnode->AsParseNodeUni()->pnode1->location);
  8864. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8865. break;
  8866. // PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  8867. case knopPos:
  8868. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8869. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  8870. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  8871. byteCodeGenerator->Writer()->Reg2(
  8872. Js::OpCode::Conv_Num, funcInfo->AcquireLoc(pnode), pnode->AsParseNodeUni()->pnode1->location);
  8873. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8874. break;
  8875. // PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  8876. case knopLogNot:
  8877. {
  8878. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8879. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  8880. // For boolean expressions that compute a result, we have to burn a register for the result
  8881. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  8882. // full-on renaming in the back end.
  8883. funcInfo->AcquireLoc(pnode);
  8884. if (pnode->AsParseNodeUni()->pnode1->nop == knopInt)
  8885. {
  8886. int32 value = pnode->AsParseNodeUni()->pnode1->AsParseNodeInt()->lw;
  8887. Js::OpCode op = value ? Js::OpCode::LdFalse : Js::OpCode::LdTrue;
  8888. byteCodeGenerator->Writer()->Reg1(op, pnode->location);
  8889. }
  8890. else
  8891. {
  8892. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  8893. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, pnode->location);
  8894. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, doneLabel, pnode->AsParseNodeUni()->pnode1->location);
  8895. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, pnode->location);
  8896. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  8897. }
  8898. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  8899. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8900. break;
  8901. }
  8902. // PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  8903. case knopEllipsis:
  8904. {
  8905. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  8906. // Transparently pass the location of the array.
  8907. pnode->location = pnode->AsParseNodeUni()->pnode1->location;
  8908. break;
  8909. }
  8910. // PTNODE(knopIncPost , "post++" ,Inc ,Uni ,fnopUni|fnopAsg)
  8911. case knopIncPost:
  8912. case knopDecPost:
  8913. // FALL THROUGH to the faster pre-inc/dec case if the result of the expression is not needed.
  8914. if (pnode->isUsed || fReturnValue)
  8915. {
  8916. byteCodeGenerator->StartStatement(pnode);
  8917. const Js::OpCode op = (pnode->nop == knopDecPost) ? Js::OpCode::Sub_A : Js::OpCode::Add_A;
  8918. ParseNode* pnode1 = pnode->AsParseNodeUni()->pnode1;
  8919. // Grab a register for the expression result.
  8920. funcInfo->AcquireLoc(pnode);
  8921. // Load the initial value, convert it (this is the expression result), and increment it.
  8922. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  8923. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Num, pnode->location, pnode1->location);
  8924. // Use temporary register if lhs cannot be assigned
  8925. Js::RegSlot incDecResult = pnode1->location;
  8926. if (funcInfo->RegIsConst(incDecResult) ||
  8927. (pnode1->nop == knopName && pnode1->AsParseNodeName()->sym && pnode1->AsParseNodeName()->sym->GetIsFuncExpr()))
  8928. {
  8929. incDecResult = funcInfo->AcquireTmpRegister();
  8930. }
  8931. Js::RegSlot oneReg = funcInfo->constantToRegister.LookupWithKey(1, Js::Constants::NoRegister);
  8932. Assert(oneReg != Js::Constants::NoRegister);
  8933. byteCodeGenerator->Writer()->Reg3(op, incDecResult, pnode->location, oneReg);
  8934. // Store the incremented value.
  8935. EmitAssignment(nullptr, pnode1, incDecResult, byteCodeGenerator, funcInfo);
  8936. // Release the incremented value and the l-value.
  8937. if (incDecResult != pnode1->location)
  8938. {
  8939. funcInfo->ReleaseTmpRegister(incDecResult);
  8940. }
  8941. funcInfo->ReleaseLoad(pnode1);
  8942. byteCodeGenerator->EndStatement(pnode);
  8943. break;
  8944. }
  8945. else
  8946. {
  8947. pnode->nop = (pnode->nop == knopIncPost) ? knopIncPre : knopDecPre;
  8948. }
  8949. // FALL THROUGH to the fast pre-inc/dec case if the result of the expression is not needed.
  8950. // PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  8951. case knopIncPre:
  8952. case knopDecPre:
  8953. {
  8954. byteCodeGenerator->StartStatement(pnode);
  8955. const Js::OpCode op = (pnode->nop == knopDecPre) ? Js::OpCode::Decr_A : Js::OpCode::Incr_A;
  8956. ParseNode* pnode1 = pnode->AsParseNodeUni()->pnode1;
  8957. // Assign a register for the result only if the result is used or the LHS can't be assigned to
  8958. // (i.e., is a constant).
  8959. const bool need_result_location =
  8960. pnode->isUsed
  8961. || fReturnValue
  8962. || funcInfo->RegIsConst(pnode1->location)
  8963. || (pnode1->nop == knopName && pnode1->AsParseNodeName()->sym && pnode1->AsParseNodeName()->sym->GetIsFuncExpr());
  8964. if (need_result_location)
  8965. {
  8966. const Js::RegSlot result_location = funcInfo->AcquireLoc(pnode);
  8967. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  8968. byteCodeGenerator->Writer()->Reg2(op, result_location, pnode1->location);
  8969. // Store the incremented value and release the l-value.
  8970. EmitAssignment(nullptr, pnode1, result_location, byteCodeGenerator, funcInfo);
  8971. }
  8972. else
  8973. {
  8974. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  8975. byteCodeGenerator->Writer()->Reg2(op, pnode1->location, pnode1->location);
  8976. // Store the incremented value and release the l-value.
  8977. EmitAssignment(nullptr, pnode1, pnode1->location, byteCodeGenerator, funcInfo);
  8978. }
  8979. funcInfo->ReleaseLoad(pnode1);
  8980. byteCodeGenerator->EndStatement(pnode);
  8981. break;
  8982. }
  8983. // PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  8984. case knopTypeof:
  8985. {
  8986. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  8987. ParseNode* pnodeOpnd = pnode->AsParseNodeUni()->pnode1;
  8988. switch (pnodeOpnd->nop)
  8989. {
  8990. case knopDot:
  8991. {
  8992. Emit(pnodeOpnd->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  8993. Js::PropertyId propertyId = pnodeOpnd->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  8994. Assert(pnodeOpnd->AsParseNodeBin()->pnode2->nop == knopName);
  8995. funcInfo->ReleaseLoc(pnodeOpnd->AsParseNodeBin()->pnode1);
  8996. funcInfo->AcquireLoc(pnode);
  8997. byteCodeGenerator->EmitTypeOfFld(funcInfo, propertyId, pnode->location, pnodeOpnd->AsParseNodeBin()->pnode1->location, Js::OpCode::LdFldForTypeOf);
  8998. break;
  8999. }
  9000. case knopIndex:
  9001. {
  9002. EmitBinaryOpnds(pnodeOpnd->AsParseNodeBin()->pnode1, pnodeOpnd->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9003. funcInfo->ReleaseLoc(pnodeOpnd->AsParseNodeBin()->pnode2);
  9004. funcInfo->ReleaseLoc(pnodeOpnd->AsParseNodeBin()->pnode1);
  9005. funcInfo->AcquireLoc(pnode);
  9006. byteCodeGenerator->Writer()->Element(Js::OpCode::TypeofElem, pnode->location, pnodeOpnd->AsParseNodeBin()->pnode1->location, pnodeOpnd->AsParseNodeBin()->pnode2->location);
  9007. break;
  9008. }
  9009. case knopName:
  9010. {
  9011. ParseNodeName * pnodeNameOpnd = pnodeOpnd->AsParseNodeName();
  9012. if (pnodeNameOpnd->IsUserIdentifier())
  9013. {
  9014. funcInfo->AcquireLoc(pnode);
  9015. byteCodeGenerator->EmitPropTypeof(pnode->location, pnodeNameOpnd->sym, pnodeNameOpnd->pid, funcInfo);
  9016. break;
  9017. }
  9018. // Special names should fallthrough to default case
  9019. }
  9020. default:
  9021. Emit(pnodeOpnd, byteCodeGenerator, funcInfo, false);
  9022. funcInfo->ReleaseLoc(pnodeOpnd);
  9023. byteCodeGenerator->Writer()->Reg2(
  9024. Js::OpCode::Typeof, funcInfo->AcquireLoc(pnode), pnodeOpnd->location);
  9025. break;
  9026. }
  9027. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9028. break;
  9029. }
  9030. // PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  9031. case knopVoid:
  9032. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9033. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  9034. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, funcInfo->AcquireLoc(pnode));
  9035. break;
  9036. // PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  9037. case knopArray:
  9038. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9039. EmitArrayLiteral(pnode, byteCodeGenerator, funcInfo);
  9040. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9041. break;
  9042. // PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  9043. case knopObject:
  9044. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9045. funcInfo->AcquireLoc(pnode);
  9046. EmitObjectInitializers(pnode->AsParseNodeUni()->pnode1, pnode->location, byteCodeGenerator, funcInfo);
  9047. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9048. break;
  9049. // PTNODE(knopComputedName, "[name]" ,None ,Uni ,fnopUni)
  9050. case knopComputedName:
  9051. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  9052. if (pnode->location == Js::Constants::NoRegister)
  9053. {
  9054. // The name is some expression with no home location. We can just re-use the register.
  9055. pnode->location = pnode->AsParseNodeUni()->pnode1->location;
  9056. }
  9057. else if (pnode->location != pnode->AsParseNodeUni()->pnode1->location)
  9058. {
  9059. // The name had to be protected from side-effects of the RHS.
  9060. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeUni()->pnode1->location);
  9061. }
  9062. break;
  9063. // Binary and Ternary Operators
  9064. case knopAdd:
  9065. EmitAdd(pnode, byteCodeGenerator, funcInfo);
  9066. break;
  9067. case knopSub:
  9068. case knopMul:
  9069. case knopExpo:
  9070. case knopDiv:
  9071. case knopMod:
  9072. case knopOr:
  9073. case knopXor:
  9074. case knopAnd:
  9075. case knopLsh:
  9076. case knopRsh:
  9077. case knopRs2:
  9078. case knopIn:
  9079. EmitBinary(nopToOp[pnode->nop], pnode, byteCodeGenerator, funcInfo);
  9080. break;
  9081. case knopInstOf:
  9082. {
  9083. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9084. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9085. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  9086. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  9087. funcInfo->AcquireLoc(pnode);
  9088. uint cacheId = funcInfo->NewIsInstInlineCache();
  9089. byteCodeGenerator->Writer()->Reg3C(nopToOp[pnode->nop], pnode->location, pnode->AsParseNodeBin()->pnode1->location,
  9090. pnode->AsParseNodeBin()->pnode2->location, cacheId);
  9091. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9092. }
  9093. break;
  9094. case knopEq:
  9095. case knopEqv:
  9096. case knopNEqv:
  9097. case knopNe:
  9098. case knopLt:
  9099. case knopLe:
  9100. case knopGe:
  9101. case knopGt:
  9102. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9103. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9104. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  9105. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  9106. funcInfo->AcquireLoc(pnode);
  9107. byteCodeGenerator->Writer()->Reg3(nopToCMOp[pnode->nop], pnode->location, pnode->AsParseNodeBin()->pnode1->location,
  9108. pnode->AsParseNodeBin()->pnode2->location);
  9109. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9110. break;
  9111. case knopNew:
  9112. {
  9113. EmitNew(pnode, byteCodeGenerator, funcInfo);
  9114. byteCodeGenerator->EndStatement(pnode);
  9115. break;
  9116. }
  9117. case knopDelete:
  9118. {
  9119. ParseNode *pexpr = pnode->AsParseNodeUni()->pnode1;
  9120. byteCodeGenerator->StartStatement(pnode);
  9121. switch (pexpr->nop)
  9122. {
  9123. case knopName:
  9124. {
  9125. ParseNodeName * pnodeName = pexpr->AsParseNodeName();
  9126. if (pnodeName->IsSpecialName())
  9127. {
  9128. funcInfo->AcquireLoc(pnode);
  9129. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, pnode->location);
  9130. }
  9131. else
  9132. {
  9133. funcInfo->AcquireLoc(pnode);
  9134. byteCodeGenerator->EmitPropDelete(pnode->location, pnodeName->sym, pnodeName->pid, funcInfo);
  9135. }
  9136. break;
  9137. }
  9138. case knopDot:
  9139. {
  9140. if (ByteCodeGenerator::IsSuper(pexpr->AsParseNodeBin()->pnode1))
  9141. {
  9142. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_DeletePropertyWithSuper));
  9143. funcInfo->AcquireLoc(pnode);
  9144. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, pnode->location);
  9145. }
  9146. else
  9147. {
  9148. Emit(pexpr->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  9149. funcInfo->ReleaseLoc(pexpr->AsParseNodeBin()->pnode1);
  9150. Js::PropertyId propertyId = pexpr->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  9151. funcInfo->AcquireLoc(pnode);
  9152. byteCodeGenerator->Writer()->Property(Js::OpCode::DeleteFld, pnode->location, pexpr->AsParseNodeBin()->pnode1->location,
  9153. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  9154. }
  9155. break;
  9156. }
  9157. case knopIndex:
  9158. {
  9159. EmitBinaryOpnds(pexpr->AsParseNodeBin()->pnode1, pexpr->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9160. funcInfo->ReleaseLoc(pexpr->AsParseNodeBin()->pnode2);
  9161. funcInfo->ReleaseLoc(pexpr->AsParseNodeBin()->pnode1);
  9162. funcInfo->AcquireLoc(pnode);
  9163. byteCodeGenerator->Writer()->Element(Js::OpCode::DeleteElemI_A, pnode->location, pexpr->AsParseNodeBin()->pnode1->location, pexpr->AsParseNodeBin()->pnode2->location);
  9164. break;
  9165. }
  9166. default:
  9167. {
  9168. Emit(pexpr, byteCodeGenerator, funcInfo, false);
  9169. funcInfo->ReleaseLoc(pexpr);
  9170. byteCodeGenerator->Writer()->Reg2(
  9171. Js::OpCode::Delete_A, funcInfo->AcquireLoc(pnode), pexpr->location);
  9172. break;
  9173. }
  9174. }
  9175. byteCodeGenerator->EndStatement(pnode);
  9176. break;
  9177. }
  9178. case knopCall:
  9179. {
  9180. ParseNodeCall * pnodeCall = pnode->AsParseNodeCall();
  9181. byteCodeGenerator->StartStatement(pnodeCall);
  9182. if (pnodeCall->isSuperCall)
  9183. {
  9184. byteCodeGenerator->EmitSuperCall(funcInfo, pnodeCall->AsParseNodeSuperCall(), fReturnValue);
  9185. }
  9186. else if (pnodeCall->pnodeTarget->nop == knopImport)
  9187. {
  9188. ParseNodePtr args = pnodeCall->pnodeArgs;
  9189. Assert(CountArguments(args) == 2); // import() takes one argument
  9190. Emit(args, byteCodeGenerator, funcInfo, false);
  9191. funcInfo->ReleaseLoc(args);
  9192. funcInfo->AcquireLoc(pnodeCall);
  9193. byteCodeGenerator->Writer()->Reg2(Js::OpCode::ImportCall, pnodeCall->location, args->location);
  9194. }
  9195. else
  9196. {
  9197. if (pnodeCall->isApplyCall && funcInfo->GetApplyEnclosesArgs())
  9198. {
  9199. // TODO[ianhall]: Can we remove the ApplyCall bytecode gen time optimization?
  9200. EmitApplyCall(pnodeCall, byteCodeGenerator, funcInfo, fReturnValue);
  9201. }
  9202. else
  9203. {
  9204. EmitCall(pnodeCall, byteCodeGenerator, funcInfo, fReturnValue, /*fEvaluateComponents*/ true);
  9205. }
  9206. }
  9207. byteCodeGenerator->EndStatement(pnode);
  9208. break;
  9209. }
  9210. case knopIndex:
  9211. {
  9212. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9213. EmitBinaryOpnds(pnode->AsParseNodeBin()->pnode1, pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo);
  9214. Js::RegSlot callObjLocation = pnode->AsParseNodeBin()->pnode1->location;
  9215. Js::RegSlot protoLocation = callObjLocation;
  9216. if (ByteCodeGenerator::IsSuper(pnode->AsParseNodeBin()->pnode1))
  9217. {
  9218. Emit(pnode->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  9219. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, callObjLocation, funcInfo);
  9220. funcInfo->ReleaseLoc(pnode->AsParseNodeSuperReference()->pnodeThis);
  9221. }
  9222. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  9223. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  9224. funcInfo->AcquireLoc(pnode);
  9225. byteCodeGenerator->Writer()->Element(
  9226. Js::OpCode::LdElemI_A, pnode->location, protoLocation, pnode->AsParseNodeBin()->pnode2->location);
  9227. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9228. break;
  9229. }
  9230. // this is MemberExpression as rvalue
  9231. case knopDot:
  9232. {
  9233. Emit(pnode->AsParseNodeBin()->pnode1, byteCodeGenerator, funcInfo, false);
  9234. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode1);
  9235. funcInfo->AcquireLoc(pnode);
  9236. Js::PropertyId propertyId = pnode->AsParseNodeBin()->pnode2->AsParseNodeName()->PropertyIdFromNameNode();
  9237. Js::RegSlot callObjLocation = pnode->AsParseNodeBin()->pnode1->location;
  9238. Js::RegSlot protoLocation = callObjLocation;
  9239. if (propertyId == Js::PropertyIds::length)
  9240. {
  9241. uint cacheId = funcInfo->FindOrAddInlineCacheId(protoLocation, propertyId, false, false);
  9242. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdLen_A, pnode->location, protoLocation, cacheId);
  9243. }
  9244. else if (pnode->IsCallApplyTargetLoad())
  9245. {
  9246. if (ByteCodeGenerator::IsSuper(pnode->AsParseNodeBin()->pnode1))
  9247. {
  9248. Emit(pnode->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  9249. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, callObjLocation, funcInfo);
  9250. funcInfo->ReleaseLoc(pnode->AsParseNodeSuperReference()->pnodeThis);
  9251. }
  9252. uint cacheId = funcInfo->FindOrAddInlineCacheId(protoLocation, propertyId, false, false);
  9253. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFldForCallApplyTarget, pnode->location, protoLocation, cacheId);
  9254. }
  9255. else
  9256. {
  9257. if (ByteCodeGenerator::IsSuper(pnode->AsParseNodeBin()->pnode1))
  9258. {
  9259. Emit(pnode->AsParseNodeSuperReference()->pnodeThis, byteCodeGenerator, funcInfo, false);
  9260. protoLocation = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, callObjLocation, funcInfo);
  9261. funcInfo->ReleaseLoc(pnode->AsParseNodeSuperReference()->pnodeThis);
  9262. uint cacheId = funcInfo->FindOrAddInlineCacheId(protoLocation, propertyId, false, false);
  9263. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(Js::OpCode::LdSuperFld, pnode->location, protoLocation, pnode->AsParseNodeSuperReference()->pnodeThis->location, cacheId, isConstructorCall);
  9264. }
  9265. else
  9266. {
  9267. uint cacheId = funcInfo->FindOrAddInlineCacheId(callObjLocation, propertyId, false, false);
  9268. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, pnode->location, callObjLocation, cacheId, isConstructorCall);
  9269. }
  9270. }
  9271. break;
  9272. }
  9273. // PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  9274. case knopAsg:
  9275. {
  9276. ParseNode *lhs = pnode->AsParseNodeBin()->pnode1;
  9277. ParseNode *rhs = pnode->AsParseNodeBin()->pnode2;
  9278. byteCodeGenerator->StartStatement(pnode);
  9279. if (pnode->isUsed || fReturnValue)
  9280. {
  9281. // If the assignment result is used, grab a register to hold it and pass it to EmitAssignment,
  9282. // which will copy the assigned value there.
  9283. funcInfo->AcquireLoc(pnode);
  9284. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, false);
  9285. EmitAssignment(pnode, lhs, rhs->location, byteCodeGenerator, funcInfo);
  9286. }
  9287. else
  9288. {
  9289. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, false);
  9290. EmitAssignment(nullptr, lhs, rhs->location, byteCodeGenerator, funcInfo);
  9291. }
  9292. funcInfo->ReleaseLoc(rhs);
  9293. if (!(byteCodeGenerator->IsES6DestructuringEnabled() && (lhs->IsPattern())))
  9294. {
  9295. funcInfo->ReleaseReference(lhs);
  9296. }
  9297. byteCodeGenerator->EndStatement(pnode);
  9298. break;
  9299. }
  9300. case knopName:
  9301. funcInfo->AcquireLoc(pnode);
  9302. if (ByteCodeGenerator::IsThis(pnode))
  9303. {
  9304. byteCodeGenerator->EmitPropLoadThis(pnode->location, pnode->AsParseNodeSpecialName(), funcInfo, true);
  9305. }
  9306. else
  9307. {
  9308. byteCodeGenerator->EmitPropLoad(pnode->location, pnode->AsParseNodeName()->sym, pnode->AsParseNodeName()->pid, funcInfo);
  9309. }
  9310. break;
  9311. case knopComma:
  9312. {
  9313. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9314. // The parser marks binary opnd pnodes as used, but value of the first opnd of a comma is not used.
  9315. // Easier to correct this here than to check every binary op in the parser.
  9316. ParseNode *pnode1 = pnode->AsParseNodeBin()->pnode1;
  9317. pnode1->isUsed = false;
  9318. if (pnode1->nop == knopComma)
  9319. {
  9320. // Spot fix for giant comma expressions that send us into OOS if we use a simple recursive
  9321. // algorithm. Instead of recursing on comma LHS's, iterate over them, pushing the RHS's onto
  9322. // a stack. (This suggests a model for removing recursion from Emit altogether...)
  9323. ArenaAllocator *alloc = byteCodeGenerator->GetAllocator();
  9324. SList<ParseNode *> rhsStack(alloc);
  9325. do
  9326. {
  9327. rhsStack.Push(pnode1->AsParseNodeBin()->pnode2);
  9328. pnode1 = pnode1->AsParseNodeBin()->pnode1;
  9329. pnode1->isUsed = false;
  9330. } while (pnode1->nop == knopComma);
  9331. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  9332. if (funcInfo->IsTmpReg(pnode1->location))
  9333. {
  9334. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Unused, pnode1->location);
  9335. }
  9336. while (!rhsStack.Empty())
  9337. {
  9338. ParseNode *pnodeRhs = rhsStack.Pop();
  9339. pnodeRhs->isUsed = false;
  9340. Emit(pnodeRhs, byteCodeGenerator, funcInfo, false);
  9341. if (funcInfo->IsTmpReg(pnodeRhs->location))
  9342. {
  9343. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Unused, pnodeRhs->location);
  9344. }
  9345. funcInfo->ReleaseLoc(pnodeRhs);
  9346. }
  9347. }
  9348. else
  9349. {
  9350. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  9351. if (funcInfo->IsTmpReg(pnode1->location))
  9352. {
  9353. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Unused, pnode1->location);
  9354. }
  9355. }
  9356. funcInfo->ReleaseLoc(pnode1);
  9357. pnode->AsParseNodeBin()->pnode2->isUsed = pnode->isUsed || fReturnValue;
  9358. Emit(pnode->AsParseNodeBin()->pnode2, byteCodeGenerator, funcInfo, false);
  9359. funcInfo->ReleaseLoc(pnode->AsParseNodeBin()->pnode2);
  9360. funcInfo->AcquireLoc(pnode);
  9361. if (pnode->AsParseNodeBin()->pnode2->isUsed && pnode->location != pnode->AsParseNodeBin()->pnode2->location)
  9362. {
  9363. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeBin()->pnode2->location);
  9364. }
  9365. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9366. }
  9367. break;
  9368. // The binary logical ops && and || resolve to the value of the left-hand expression if its
  9369. // boolean value short-circuits the operation, and to the value of the right-hand expression
  9370. // otherwise. (In other words, the "truth" of the right-hand expression is never tested.)
  9371. // PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  9372. case knopLogOr:
  9373. {
  9374. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9375. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  9376. // We use a single dest here for the whole generating boolean expr, because we were poorly
  9377. // optimizing the previous version where we had a dest for each level
  9378. funcInfo->AcquireLoc(pnode);
  9379. EmitGeneratingBooleanExpression(pnode, doneLabel, true, doneLabel, true, pnode->location, byteCodeGenerator, funcInfo);
  9380. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  9381. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9382. break;
  9383. }
  9384. // PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  9385. case knopLogAnd:
  9386. {
  9387. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9388. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  9389. // We use a single dest here for the whole generating boolean expr, because we were poorly
  9390. // optimizing the previous version where we had a dest for each level
  9391. funcInfo->AcquireLoc(pnode);
  9392. EmitGeneratingBooleanExpression(pnode, doneLabel, true, doneLabel, true, pnode->location, byteCodeGenerator, funcInfo);
  9393. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  9394. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9395. break;
  9396. }
  9397. // PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  9398. case knopQmark:
  9399. {
  9400. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  9401. Js::ByteCodeLabel falseLabel = byteCodeGenerator->Writer()->DefineLabel();
  9402. Js::ByteCodeLabel skipLabel = byteCodeGenerator->Writer()->DefineLabel();
  9403. EmitBooleanExpression(pnode->AsParseNodeTri()->pnode1, trueLabel, falseLabel, byteCodeGenerator, funcInfo, true, false);
  9404. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  9405. funcInfo->ReleaseLoc(pnode->AsParseNodeTri()->pnode1);
  9406. // For boolean expressions that compute a result, we have to burn a register for the result
  9407. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  9408. // full-on renaming in the back end.
  9409. funcInfo->AcquireLoc(pnode);
  9410. Emit(pnode->AsParseNodeTri()->pnode2, byteCodeGenerator, funcInfo, false);
  9411. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeTri()->pnode2->location);
  9412. funcInfo->ReleaseLoc(pnode->AsParseNodeTri()->pnode2);
  9413. // Record the branch bytecode offset
  9414. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_FromCurrentToNext);
  9415. byteCodeGenerator->Writer()->Br(skipLabel);
  9416. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  9417. Emit(pnode->AsParseNodeTri()->pnode3, byteCodeGenerator, funcInfo, false);
  9418. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeTri()->pnode3->location);
  9419. funcInfo->ReleaseLoc(pnode->AsParseNodeTri()->pnode3);
  9420. byteCodeGenerator->Writer()->MarkLabel(skipLabel);
  9421. break;
  9422. }
  9423. case knopAsgAdd:
  9424. case knopAsgSub:
  9425. case knopAsgMul:
  9426. case knopAsgDiv:
  9427. case knopAsgExpo:
  9428. case knopAsgMod:
  9429. case knopAsgAnd:
  9430. case knopAsgXor:
  9431. case knopAsgOr:
  9432. case knopAsgLsh:
  9433. case knopAsgRsh:
  9434. case knopAsgRs2:
  9435. {
  9436. byteCodeGenerator->StartStatement(pnode);
  9437. ParseNode *lhs = pnode->AsParseNodeBin()->pnode1;
  9438. ParseNode *rhs = pnode->AsParseNodeBin()->pnode2;
  9439. // Assign a register for the result only if the result is used or the LHS can't be assigned to
  9440. // (i.e., is a constant).
  9441. const bool need_result_location =
  9442. pnode->isUsed
  9443. || fReturnValue
  9444. || funcInfo->RegIsConst(lhs->location)
  9445. || (lhs->nop == knopName && lhs->AsParseNodeName()->sym && lhs->AsParseNodeName()->sym->GetIsFuncExpr());
  9446. if (need_result_location)
  9447. {
  9448. const Js::RegSlot result_location = funcInfo->AcquireLoc(pnode);
  9449. // Grab a register for the initial value and load it.
  9450. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, true);
  9451. funcInfo->ReleaseLoc(rhs);
  9452. // Do the arithmetic, store the result, and release the l-value.
  9453. byteCodeGenerator->Writer()->Reg3(nopToOp[pnode->nop], result_location, lhs->location, rhs->location);
  9454. EmitAssignment(pnode, lhs, result_location, byteCodeGenerator, funcInfo);
  9455. }
  9456. else
  9457. {
  9458. // Grab a register for the initial value and load it. Might modify lhs->location.
  9459. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, true);
  9460. funcInfo->ReleaseLoc(rhs);
  9461. // Do the arithmetic, store the result, and release the l-value.
  9462. byteCodeGenerator->Writer()->Reg3(nopToOp[pnode->nop], lhs->location, lhs->location, rhs->location);
  9463. EmitAssignment(nullptr, lhs, lhs->location, byteCodeGenerator, funcInfo);
  9464. }
  9465. funcInfo->ReleaseLoad(lhs);
  9466. byteCodeGenerator->EndStatement(pnode);
  9467. break;
  9468. }
  9469. // General nodes.
  9470. // PTNODE(knopTempRef , "temp ref" ,None ,Uni ,fnopUni)
  9471. case knopTempRef:
  9472. // TODO: check whether mov is necessary
  9473. funcInfo->AcquireLoc(pnode);
  9474. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeUni()->pnode1->location);
  9475. break;
  9476. // PTNODE(knopTemp , "temp" ,None ,None ,fnopLeaf)
  9477. case knopTemp:
  9478. // Emit initialization code
  9479. if (pnode->AsParseNodeVar()->pnodeInit != nullptr)
  9480. {
  9481. byteCodeGenerator->StartStatement(pnode);
  9482. Emit(pnode->AsParseNodeVar()->pnodeInit, byteCodeGenerator, funcInfo, false);
  9483. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->AsParseNodeVar()->pnodeInit->location);
  9484. funcInfo->ReleaseLoc(pnode->AsParseNodeVar()->pnodeInit);
  9485. byteCodeGenerator->EndStatement(pnode);
  9486. }
  9487. break;
  9488. // PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  9489. case knopVarDecl:
  9490. case knopConstDecl:
  9491. case knopLetDecl:
  9492. {
  9493. // Emit initialization code
  9494. ParseNodePtr initNode = pnode->AsParseNodeVar()->pnodeInit;
  9495. AssertMsg(pnode->nop != knopConstDecl || initNode != nullptr, "knopConstDecl expected to have an initializer");
  9496. if (initNode != nullptr || pnode->nop == knopLetDecl)
  9497. {
  9498. Symbol *sym = pnode->AsParseNodeVar()->sym;
  9499. Js::RegSlot rhsLocation;
  9500. byteCodeGenerator->StartStatement(pnode);
  9501. if (initNode != nullptr)
  9502. {
  9503. Emit(initNode, byteCodeGenerator, funcInfo, false);
  9504. rhsLocation = initNode->location;
  9505. if (initNode->nop == knopObject)
  9506. {
  9507. TrackMemberNodesInObjectForIntConstants(byteCodeGenerator, initNode);
  9508. }
  9509. else if (initNode->nop == knopInt)
  9510. {
  9511. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  9512. }
  9513. }
  9514. else
  9515. {
  9516. Assert(pnode->nop == knopLetDecl);
  9517. rhsLocation = funcInfo->AcquireTmpRegister();
  9518. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, rhsLocation);
  9519. }
  9520. if (pnode->nop != knopVarDecl)
  9521. {
  9522. Assert(sym->GetDecl() == pnode || (sym->IsArguments() && !funcInfo->GetHasArguments()));
  9523. sym->SetNeedDeclaration(false);
  9524. }
  9525. EmitAssignment(nullptr, pnode, rhsLocation, byteCodeGenerator, funcInfo);
  9526. funcInfo->ReleaseTmpRegister(rhsLocation);
  9527. byteCodeGenerator->EndStatement(pnode);
  9528. }
  9529. break;
  9530. }
  9531. // PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  9532. case knopFncDecl:
  9533. // The "function declarations" were emitted in DefineFunctions()
  9534. if (!pnode->AsParseNodeFnc()->IsDeclaration())
  9535. {
  9536. byteCodeGenerator->DefineOneFunction(pnode->AsParseNodeFnc(), funcInfo, false);
  9537. }
  9538. break;
  9539. // PTNODE(knopClassDecl, "class" ,None ,None ,fnopLeaf)
  9540. case knopClassDecl:
  9541. {
  9542. ParseNodeClass * pnodeClass = pnode->AsParseNodeClass();
  9543. funcInfo->AcquireLoc(pnodeClass);
  9544. Assert(pnodeClass->pnodeConstructor);
  9545. pnodeClass->pnodeConstructor->location = pnodeClass->location;
  9546. BeginEmitBlock(pnodeClass->pnodeBlock, byteCodeGenerator, funcInfo);
  9547. // Extends
  9548. if (pnodeClass->pnodeExtends)
  9549. {
  9550. // We can't do StartStatement/EndStatement for pnodeExtends here because the load locations may differ between
  9551. // defer and nondefer parse modes.
  9552. Emit(pnodeClass->pnodeExtends, byteCodeGenerator, funcInfo, false);
  9553. }
  9554. // Constructor
  9555. Emit(pnodeClass->pnodeConstructor, byteCodeGenerator, funcInfo, false);
  9556. EmitComputedFunctionNameVar(bindPnode, pnodeClass->pnodeConstructor, byteCodeGenerator);
  9557. if (pnodeClass->pnodeExtends)
  9558. {
  9559. byteCodeGenerator->StartStatement(pnodeClass->pnodeExtends);
  9560. byteCodeGenerator->Writer()->InitClass(pnodeClass->location, pnodeClass->pnodeExtends->location);
  9561. byteCodeGenerator->EndStatement(pnodeClass->pnodeExtends);
  9562. }
  9563. else
  9564. {
  9565. byteCodeGenerator->Writer()->InitClass(pnodeClass->location);
  9566. }
  9567. Js::RegSlot protoLoc = funcInfo->AcquireTmpRegister(); //register set if we have Instance Methods
  9568. int cacheId = funcInfo->FindOrAddInlineCacheId(pnodeClass->location, Js::PropertyIds::prototype, false, false);
  9569. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, protoLoc, pnodeClass->location, cacheId);
  9570. // Static Methods
  9571. EmitClassInitializers(pnodeClass->pnodeStaticMembers, pnodeClass->location, byteCodeGenerator, funcInfo, pnode, /*isObjectEmpty*/ false);
  9572. // Instance Methods
  9573. EmitClassInitializers(pnodeClass->pnodeMembers, protoLoc, byteCodeGenerator, funcInfo, pnode, /*isObjectEmpty*/ true);
  9574. funcInfo->ReleaseTmpRegister(protoLoc);
  9575. // Emit name binding.
  9576. if (pnodeClass->pnodeName)
  9577. {
  9578. Symbol * sym = pnodeClass->pnodeName->sym;
  9579. sym->SetNeedDeclaration(false);
  9580. byteCodeGenerator->EmitPropStore(pnodeClass->location, sym, nullptr, funcInfo, false, true);
  9581. }
  9582. EndEmitBlock(pnodeClass->pnodeBlock, byteCodeGenerator, funcInfo);
  9583. if (pnodeClass->pnodeExtends)
  9584. {
  9585. funcInfo->ReleaseLoc(pnodeClass->pnodeExtends);
  9586. }
  9587. if (pnodeClass->pnodeDeclName)
  9588. {
  9589. Symbol * sym = pnodeClass->pnodeDeclName->sym;
  9590. sym->SetNeedDeclaration(false);
  9591. byteCodeGenerator->EmitPropStore(pnodeClass->location, sym, nullptr, funcInfo, true, false);
  9592. }
  9593. if (pnodeClass->IsDefaultModuleExport())
  9594. {
  9595. byteCodeGenerator->EmitAssignmentToDefaultModuleExport(pnodeClass, funcInfo);
  9596. }
  9597. break;
  9598. }
  9599. case knopStrTemplate:
  9600. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9601. EmitStringTemplate(pnode->AsParseNodeStrTemplate(), byteCodeGenerator, funcInfo);
  9602. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9603. break;
  9604. case knopEndCode:
  9605. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_All);
  9606. // load undefined for the fallthrough case:
  9607. if (!funcInfo->IsGlobalFunction())
  9608. {
  9609. if (funcInfo->IsClassConstructor())
  9610. {
  9611. // For class constructors, we need to explicitly load 'this' into the return register.
  9612. byteCodeGenerator->EmitClassConstructorEndCode(funcInfo);
  9613. }
  9614. else
  9615. {
  9616. // In the global function, implicit return values are copied to the return register, and if
  9617. // necessary the return register is initialized at the top. Don't clobber the value here.
  9618. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, ByteCodeGenerator::ReturnRegister);
  9619. }
  9620. }
  9621. // Label for non-fall-through return
  9622. byteCodeGenerator->Writer()->MarkLabel(funcInfo->singleExit);
  9623. if (funcInfo->GetHasCachedScope())
  9624. {
  9625. byteCodeGenerator->Writer()->Empty(Js::OpCode::CommitScope);
  9626. }
  9627. byteCodeGenerator->StartStatement(pnode);
  9628. byteCodeGenerator->Writer()->Empty(Js::OpCode::Ret);
  9629. byteCodeGenerator->EndStatement(pnode);
  9630. break;
  9631. // PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  9632. case knopDebugger:
  9633. byteCodeGenerator->StartStatement(pnode);
  9634. byteCodeGenerator->Writer()->Empty(Js::OpCode::Break);
  9635. byteCodeGenerator->EndStatement(pnode);
  9636. break;
  9637. // PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  9638. case knopFor:
  9639. {
  9640. ParseNodeFor * pnodeFor = pnode->AsParseNodeFor();
  9641. if (pnodeFor->pnodeInverted != nullptr)
  9642. {
  9643. byteCodeGenerator->EmitInvertedLoop(pnodeFor, pnodeFor->pnodeInverted, funcInfo);
  9644. }
  9645. else
  9646. {
  9647. BeginEmitBlock(pnodeFor->pnodeBlock, byteCodeGenerator, funcInfo);
  9648. Emit(pnodeFor->pnodeInit, byteCodeGenerator, funcInfo, false);
  9649. funcInfo->ReleaseLoc(pnodeFor->pnodeInit);
  9650. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  9651. {
  9652. CloneEmitBlock(pnodeFor->pnodeBlock, byteCodeGenerator, funcInfo);
  9653. }
  9654. EmitLoop(pnodeFor,
  9655. pnodeFor->pnodeCond,
  9656. pnodeFor->pnodeBody,
  9657. pnodeFor->pnodeIncr,
  9658. byteCodeGenerator,
  9659. funcInfo,
  9660. fReturnValue,
  9661. FALSE,
  9662. pnodeFor->pnodeBlock);
  9663. EndEmitBlock(pnodeFor->pnodeBlock, byteCodeGenerator, funcInfo);
  9664. }
  9665. break;
  9666. }
  9667. // PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  9668. case knopIf:
  9669. {
  9670. ParseNodeIf * pnodeIf = pnode->AsParseNodeIf();
  9671. byteCodeGenerator->StartStatement(pnodeIf);
  9672. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  9673. Js::ByteCodeLabel falseLabel = byteCodeGenerator->Writer()->DefineLabel();
  9674. EmitBooleanExpression(pnodeIf->pnodeCond, trueLabel, falseLabel, byteCodeGenerator, funcInfo, true, false);
  9675. funcInfo->ReleaseLoc(pnodeIf->pnodeCond);
  9676. byteCodeGenerator->EndStatement(pnodeIf);
  9677. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  9678. Emit(pnodeIf->pnodeTrue, byteCodeGenerator, funcInfo, fReturnValue);
  9679. funcInfo->ReleaseLoc(pnodeIf->pnodeTrue);
  9680. if (pnodeIf->pnodeFalse != nullptr)
  9681. {
  9682. // has else clause
  9683. Js::ByteCodeLabel skipLabel = byteCodeGenerator->Writer()->DefineLabel();
  9684. // Record the branch bytecode offset
  9685. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_FromCurrentToNext);
  9686. // then clause skips else clause
  9687. byteCodeGenerator->Writer()->Br(skipLabel);
  9688. // generate code for else clause
  9689. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  9690. Emit(pnodeIf->pnodeFalse, byteCodeGenerator, funcInfo, fReturnValue);
  9691. funcInfo->ReleaseLoc(pnodeIf->pnodeFalse);
  9692. byteCodeGenerator->Writer()->MarkLabel(skipLabel);
  9693. }
  9694. else
  9695. {
  9696. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  9697. }
  9698. if (pnodeIf->emitLabels)
  9699. {
  9700. byteCodeGenerator->Writer()->MarkLabel(pnodeIf->breakLabel);
  9701. }
  9702. break;
  9703. }
  9704. case knopWhile:
  9705. {
  9706. ParseNodeWhile * pnodeWhile = pnode->AsParseNodeWhile();
  9707. EmitLoop(pnodeWhile,
  9708. pnodeWhile->pnodeCond,
  9709. pnodeWhile->pnodeBody,
  9710. nullptr,
  9711. byteCodeGenerator,
  9712. funcInfo,
  9713. fReturnValue);
  9714. break;
  9715. }
  9716. // PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  9717. case knopDoWhile:
  9718. {
  9719. ParseNodeWhile * pnodeWhile = pnode->AsParseNodeWhile();
  9720. EmitLoop(pnodeWhile,
  9721. pnodeWhile->pnodeCond,
  9722. pnodeWhile->pnodeBody,
  9723. nullptr,
  9724. byteCodeGenerator,
  9725. funcInfo,
  9726. fReturnValue,
  9727. true);
  9728. break;
  9729. }
  9730. // PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  9731. case knopForIn:
  9732. EmitForInOrForOf(pnode->AsParseNodeForInOrForOf(), byteCodeGenerator, funcInfo, fReturnValue);
  9733. break;
  9734. case knopForOf:
  9735. EmitForInOrForOf(pnode->AsParseNodeForInOrForOf(), byteCodeGenerator, funcInfo, fReturnValue);
  9736. break;
  9737. // PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  9738. case knopReturn:
  9739. {
  9740. ParseNodeReturn * pnodeReturn = pnode->AsParseNodeReturn();
  9741. byteCodeGenerator->StartStatement(pnodeReturn);
  9742. if (pnodeReturn->pnodeExpr != nullptr)
  9743. {
  9744. if (pnodeReturn->pnodeExpr->location == Js::Constants::NoRegister)
  9745. {
  9746. // No need to burn a register for the return value. If we need a temp, use R0 directly.
  9747. pnodeReturn->pnodeExpr->location = ByteCodeGenerator::ReturnRegister;
  9748. }
  9749. Emit(pnodeReturn->pnodeExpr, byteCodeGenerator, funcInfo, fReturnValue);
  9750. if (pnodeReturn->pnodeExpr->location != ByteCodeGenerator::ReturnRegister)
  9751. {
  9752. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, pnodeReturn->pnodeExpr->location);
  9753. }
  9754. funcInfo->GetParsedFunctionBody()->SetHasNoExplicitReturnValue(false);
  9755. }
  9756. else
  9757. {
  9758. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, ByteCodeGenerator::ReturnRegister);
  9759. }
  9760. if (funcInfo->IsClassConstructor())
  9761. {
  9762. // return expr; // becomes like below:
  9763. //
  9764. // if (IsObject(expr)) {
  9765. // return expr;
  9766. // } else if (IsBaseClassConstructor) {
  9767. // return this;
  9768. // } else if (!IsUndefined(expr)) {
  9769. // throw TypeError;
  9770. // }
  9771. Js::ByteCodeLabel returnExprLabel = byteCodeGenerator->Writer()->DefineLabel();
  9772. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, returnExprLabel, ByteCodeGenerator::ReturnRegister);
  9773. if (funcInfo->IsBaseClassConstructor())
  9774. {
  9775. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, funcInfo->GetThisSymbol()->GetLocation());
  9776. }
  9777. else
  9778. {
  9779. Js::ByteCodeLabel returnThisLabel = byteCodeGenerator->Writer()->DefineLabel();
  9780. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, returnThisLabel, ByteCodeGenerator::ReturnRegister, funcInfo->undefinedConstantRegister);
  9781. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ClassDerivedConstructorInvalidReturnType));
  9782. byteCodeGenerator->Writer()->MarkLabel(returnThisLabel);
  9783. byteCodeGenerator->EmitClassConstructorEndCode(funcInfo);
  9784. }
  9785. byteCodeGenerator->Writer()->MarkLabel(returnExprLabel);
  9786. }
  9787. if (pnodeReturn->grfnop & fnopCleanup)
  9788. {
  9789. EmitJumpCleanup(pnodeReturn, nullptr, byteCodeGenerator, funcInfo);
  9790. }
  9791. byteCodeGenerator->Writer()->Br(funcInfo->singleExit);
  9792. byteCodeGenerator->EndStatement(pnodeReturn);
  9793. break;
  9794. }
  9795. // PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  9796. case knopBlock:
  9797. {
  9798. ParseNodeBlock * pnodeBlock = pnode->AsParseNodeBlock();
  9799. if (pnodeBlock->pnodeStmt != nullptr)
  9800. {
  9801. EmitBlock(pnodeBlock, byteCodeGenerator, funcInfo, fReturnValue);
  9802. if (pnodeBlock->emitLabels)
  9803. {
  9804. byteCodeGenerator->Writer()->MarkLabel(pnodeBlock->breakLabel);
  9805. }
  9806. }
  9807. break;
  9808. }
  9809. // PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  9810. case knopWith:
  9811. {
  9812. ParseNodeWith * pnodeWith = pnode->AsParseNodeWith();
  9813. Assert(pnodeWith->pnodeObj != nullptr);
  9814. byteCodeGenerator->StartStatement(pnodeWith);
  9815. // Copy the with object to a temp register (the location assigned to pnode) so that if the with object
  9816. // is overwritten in the body, the lookups are not affected.
  9817. funcInfo->AcquireLoc(pnodeWith);
  9818. Emit(pnodeWith->pnodeObj, byteCodeGenerator, funcInfo, false);
  9819. Js::RegSlot regVal = (byteCodeGenerator->GetScriptContext()->GetConfig()->IsES6UnscopablesEnabled()) ? funcInfo->AcquireTmpRegister() : pnodeWith->location;
  9820. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Obj, regVal, pnodeWith->pnodeObj->location);
  9821. if (byteCodeGenerator->GetScriptContext()->GetConfig()->IsES6UnscopablesEnabled())
  9822. {
  9823. byteCodeGenerator->Writer()->Reg2(Js::OpCode::NewUnscopablesWrapperObject, pnodeWith->location, regVal);
  9824. }
  9825. byteCodeGenerator->EndStatement(pnodeWith);
  9826. #ifdef PERF_HINT
  9827. if (PHASE_TRACE1(Js::PerfHintPhase))
  9828. {
  9829. WritePerfHint(PerfHints::HasWithBlock, funcInfo->byteCodeFunction->GetFunctionBody(), byteCodeGenerator->Writer()->GetCurrentOffset() - 1);
  9830. }
  9831. #endif
  9832. if (pnodeWith->pnodeBody != nullptr)
  9833. {
  9834. Scope *scope = pnodeWith->scope;
  9835. scope->SetLocation(pnodeWith->location);
  9836. byteCodeGenerator->PushScope(scope);
  9837. Js::DebuggerScope *debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeWith, Js::DiagExtraScopesType::DiagWithScope, regVal);
  9838. if (byteCodeGenerator->ShouldTrackDebuggerMetadata())
  9839. {
  9840. byteCodeGenerator->Writer()->AddPropertyToDebuggerScope(debuggerScope, regVal, Js::Constants::NoProperty, /*shouldConsumeRegister*/ true, Js::DebuggerScopePropertyFlags_WithObject);
  9841. }
  9842. Emit(pnodeWith->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  9843. funcInfo->ReleaseLoc(pnodeWith->pnodeBody);
  9844. byteCodeGenerator->PopScope();
  9845. byteCodeGenerator->RecordEndScopeObject(pnodeWith);
  9846. }
  9847. if (pnodeWith->emitLabels)
  9848. {
  9849. byteCodeGenerator->Writer()->MarkLabel(pnodeWith->breakLabel);
  9850. }
  9851. if (byteCodeGenerator->GetScriptContext()->GetConfig()->IsES6UnscopablesEnabled())
  9852. {
  9853. funcInfo->ReleaseTmpRegister(regVal);
  9854. }
  9855. funcInfo->ReleaseLoc(pnodeWith->pnodeObj);
  9856. break;
  9857. }
  9858. // PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  9859. case knopBreak:
  9860. {
  9861. ParseNodeJump * pnodeJump = pnode->AsParseNodeJump();
  9862. Assert(pnodeJump->pnodeTarget->emitLabels);
  9863. byteCodeGenerator->StartStatement(pnodeJump);
  9864. if (pnodeJump->grfnop & fnopCleanup)
  9865. {
  9866. EmitJumpCleanup(pnodeJump, pnodeJump->pnodeTarget, byteCodeGenerator, funcInfo);
  9867. }
  9868. byteCodeGenerator->Writer()->Br(pnodeJump->pnodeTarget->breakLabel);
  9869. if (pnodeJump->emitLabels)
  9870. {
  9871. byteCodeGenerator->Writer()->MarkLabel(pnodeJump->breakLabel);
  9872. }
  9873. byteCodeGenerator->EndStatement(pnodeJump);
  9874. break;
  9875. }
  9876. case knopContinue:
  9877. {
  9878. ParseNodeJump * pnodeJump = pnode->AsParseNodeJump();
  9879. Assert(pnodeJump->pnodeTarget->emitLabels);
  9880. byteCodeGenerator->StartStatement(pnodeJump);
  9881. if (pnodeJump->grfnop & fnopCleanup)
  9882. {
  9883. EmitJumpCleanup(pnodeJump, pnodeJump->pnodeTarget, byteCodeGenerator, funcInfo);
  9884. }
  9885. byteCodeGenerator->Writer()->Br(pnodeJump->pnodeTarget->continueLabel);
  9886. byteCodeGenerator->EndStatement(pnodeJump);
  9887. break;
  9888. }
  9889. // PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  9890. case knopSwitch:
  9891. {
  9892. ParseNodeSwitch * pnodeSwitch = pnode->AsParseNodeSwitch();
  9893. BOOL fHasDefault = false;
  9894. Assert(pnodeSwitch->pnodeVal != nullptr);
  9895. byteCodeGenerator->StartStatement(pnodeSwitch);
  9896. Emit(pnodeSwitch->pnodeVal, byteCodeGenerator, funcInfo, false);
  9897. Js::RegSlot regVal = funcInfo->AcquireTmpRegister();
  9898. byteCodeGenerator->Writer()->Reg2(Js::OpCode::BeginSwitch, regVal, pnodeSwitch->pnodeVal->location);
  9899. BeginEmitBlock(pnodeSwitch->pnodeBlock, byteCodeGenerator, funcInfo);
  9900. byteCodeGenerator->EndStatement(pnodeSwitch);
  9901. // TODO: if all cases are compile-time constants, emit a switch statement in the byte
  9902. // code so the BE can optimize it.
  9903. ParseNodeCase *pnodeCase;
  9904. for (pnodeCase = pnodeSwitch->pnodeCases; pnodeCase; pnodeCase = pnodeCase->pnodeNext)
  9905. {
  9906. // Jump to the first case body if this one doesn't match. Make sure any side-effects of the case
  9907. // expression take place regardless.
  9908. pnodeCase->labelCase = byteCodeGenerator->Writer()->DefineLabel();
  9909. if (pnodeCase == pnodeSwitch->pnodeDefault)
  9910. {
  9911. fHasDefault = true;
  9912. continue;
  9913. }
  9914. Emit(pnodeCase->pnodeExpr, byteCodeGenerator, funcInfo, false);
  9915. byteCodeGenerator->Writer()->BrReg2(
  9916. Js::OpCode::Case, pnodeCase->labelCase, regVal, pnodeCase->pnodeExpr->location);
  9917. funcInfo->ReleaseLoc(pnodeCase->pnodeExpr);
  9918. }
  9919. // No explicit case value matches. Jump to the default arm (if any) or break out altogether.
  9920. if (fHasDefault)
  9921. {
  9922. byteCodeGenerator->Writer()->Br(Js::OpCode::EndSwitch, pnodeSwitch->pnodeDefault->labelCase);
  9923. }
  9924. else
  9925. {
  9926. if (!pnodeSwitch->emitLabels)
  9927. {
  9928. pnodeSwitch->breakLabel = byteCodeGenerator->Writer()->DefineLabel();
  9929. }
  9930. byteCodeGenerator->Writer()->Br(Js::OpCode::EndSwitch, pnodeSwitch->breakLabel);
  9931. }
  9932. // Now emit the case arms to which we jump on matching a case value.
  9933. for (pnodeCase = pnodeSwitch->pnodeCases; pnodeCase; pnodeCase = pnodeCase->pnodeNext)
  9934. {
  9935. byteCodeGenerator->Writer()->MarkLabel(pnodeCase->labelCase);
  9936. Emit(pnodeCase->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  9937. funcInfo->ReleaseLoc(pnodeCase->pnodeBody);
  9938. }
  9939. EndEmitBlock(pnodeSwitch->pnodeBlock, byteCodeGenerator, funcInfo);
  9940. funcInfo->ReleaseTmpRegister(regVal);
  9941. funcInfo->ReleaseLoc(pnodeSwitch->pnodeVal);
  9942. if (!fHasDefault || pnodeSwitch->emitLabels)
  9943. {
  9944. byteCodeGenerator->Writer()->MarkLabel(pnodeSwitch->breakLabel);
  9945. }
  9946. break;
  9947. }
  9948. case knopTryCatch:
  9949. {
  9950. Js::ByteCodeLabel catchLabel = (Js::ByteCodeLabel) - 1;
  9951. ParseNodeTryCatch * pnodeTryCatch = pnode->AsParseNodeTryCatch();
  9952. ParseNodeTry *pnodeTry = pnodeTryCatch->pnodeTry;
  9953. Assert(pnodeTry);
  9954. ParseNodeCatch *pnodeCatch = pnodeTryCatch->pnodeCatch;
  9955. Assert(pnodeCatch);
  9956. catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  9957. // Note: try uses OpCode::Leave which causes a return to parent interpreter thunk,
  9958. // same for catch block. Thus record cross interpreter frame entry/exit records for them.
  9959. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  9960. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  9961. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryCatch, catchLabel);
  9962. if (funcInfo->byteCodeFunction->IsCoroutine())
  9963. {
  9964. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  9965. }
  9966. Emit(pnodeTry->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  9967. funcInfo->ReleaseLoc(pnodeTry->pnodeBody);
  9968. if (funcInfo->byteCodeFunction->IsCoroutine())
  9969. {
  9970. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  9971. }
  9972. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  9973. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  9974. byteCodeGenerator->Writer()->Br(pnodeTryCatch->breakLabel);
  9975. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  9976. ParseNode *pnodeObj = pnodeCatch->GetParam();
  9977. Assert(pnodeObj);
  9978. Js::RegSlot location;
  9979. bool acquiredTempLocation = false;
  9980. Js::DebuggerScope *debuggerScope = nullptr;
  9981. Js::DebuggerScopePropertyFlags debuggerPropertyFlags = Js::DebuggerScopePropertyFlags_CatchObject;
  9982. bool isPattern = pnodeObj->nop == knopParamPattern;
  9983. if (isPattern)
  9984. {
  9985. location = pnodeObj->AsParseNodeParamPattern()->location;
  9986. }
  9987. else
  9988. {
  9989. location = pnodeObj->AsParseNodeName()->sym->GetLocation();
  9990. }
  9991. if (location == Js::Constants::NoRegister)
  9992. {
  9993. location = funcInfo->AcquireLoc(pnodeObj);
  9994. acquiredTempLocation = true;
  9995. }
  9996. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, location);
  9997. Scope *scope = pnodeCatch->scope;
  9998. byteCodeGenerator->PushScope(scope);
  9999. if (scope->GetMustInstantiate())
  10000. {
  10001. Assert(scope->GetLocation() == Js::Constants::NoRegister);
  10002. if (scope->GetIsObject())
  10003. {
  10004. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeTryCatch, Js::DiagCatchScopeInObject, funcInfo->InnerScopeToRegSlot(scope));
  10005. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::NewPseudoScope, scope->GetInnerScopeIndex());
  10006. }
  10007. else
  10008. {
  10009. int index = Js::DebuggerScope::InvalidScopeIndex;
  10010. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeTryCatch, Js::DiagCatchScopeInSlot, funcInfo->InnerScopeToRegSlot(scope), &index);
  10011. byteCodeGenerator->Writer()->Num3(Js::OpCode::NewInnerScopeSlots, scope->GetInnerScopeIndex(), scope->GetScopeSlotCount() + Js::ScopeSlots::FirstSlotIndex, index);
  10012. }
  10013. }
  10014. else
  10015. {
  10016. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeTryCatch, Js::DiagCatchScopeDirect, location);
  10017. }
  10018. auto ParamTrackAndInitialization = [&](Symbol *sym, bool initializeParam, Js::RegSlot location)
  10019. {
  10020. if (sym->IsInSlot(byteCodeGenerator, funcInfo))
  10021. {
  10022. Assert(scope->GetMustInstantiate());
  10023. if (scope->GetIsObject())
  10024. {
  10025. Js::OpCode op = (sym->GetDecl()->nop == knopLetDecl) ? Js::OpCode::InitUndeclLetFld :
  10026. byteCodeGenerator->GetInitFldOp(scope, scope->GetLocation(), funcInfo, false);
  10027. Js::PropertyId propertyId = sym->EnsurePosition(byteCodeGenerator);
  10028. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
  10029. byteCodeGenerator->Writer()->ElementPIndexed(op, location, scope->GetInnerScopeIndex(), cacheId);
  10030. byteCodeGenerator->TrackActivationObjectPropertyForDebugger(debuggerScope, sym, debuggerPropertyFlags);
  10031. }
  10032. else
  10033. {
  10034. byteCodeGenerator->TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(byteCodeGenerator), debuggerPropertyFlags);
  10035. if (initializeParam)
  10036. {
  10037. byteCodeGenerator->EmitLocalPropInit(location, sym, funcInfo);
  10038. }
  10039. else
  10040. {
  10041. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  10042. byteCodeGenerator->Writer()->Reg1(Js::OpCode::InitUndecl, tmpReg);
  10043. byteCodeGenerator->EmitLocalPropInit(tmpReg, sym, funcInfo);
  10044. funcInfo->ReleaseTmpRegister(tmpReg);
  10045. }
  10046. }
  10047. }
  10048. else
  10049. {
  10050. byteCodeGenerator->TrackRegisterPropertyForDebugger(debuggerScope, sym, funcInfo, debuggerPropertyFlags);
  10051. if (initializeParam)
  10052. {
  10053. byteCodeGenerator->EmitLocalPropInit(location, sym, funcInfo);
  10054. }
  10055. else
  10056. {
  10057. byteCodeGenerator->Writer()->Reg1(Js::OpCode::InitUndecl, location);
  10058. }
  10059. }
  10060. };
  10061. ByteCodeGenerator::TryScopeRecord tryRecForCatch(Js::OpCode::ResumeCatch, catchLabel);
  10062. if (isPattern)
  10063. {
  10064. Parser::MapBindIdentifier(pnodeObj->AsParseNodeParamPattern()->pnode1, [&](ParseNodePtr item)
  10065. {
  10066. Js::RegSlot itemLocation = item->AsParseNodeVar()->sym->GetLocation();
  10067. if (itemLocation == Js::Constants::NoRegister)
  10068. {
  10069. // The var has no assigned register, meaning it's captured, so we have no reg to write to.
  10070. // Emit the designated return reg in the byte code to avoid asserting on bad register.
  10071. itemLocation = ByteCodeGenerator::ReturnRegister;
  10072. }
  10073. ParamTrackAndInitialization(item->AsParseNodeVar()->sym, false /*initializeParam*/, itemLocation);
  10074. });
  10075. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10076. // Now emitting bytecode for destructuring pattern
  10077. byteCodeGenerator->StartStatement(pnodeCatch);
  10078. ParseNodePtr pnode1 = pnodeObj->AsParseNodeParamPattern()->pnode1;
  10079. Assert(pnode1->IsPattern());
  10080. if (funcInfo->byteCodeFunction->IsCoroutine())
  10081. {
  10082. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForCatch);
  10083. }
  10084. EmitAssignment(nullptr, pnode1, location, byteCodeGenerator, funcInfo);
  10085. byteCodeGenerator->EndStatement(pnodeCatch);
  10086. }
  10087. else
  10088. {
  10089. ParamTrackAndInitialization(pnodeObj->AsParseNodeName()->sym, true /*initializeParam*/, location);
  10090. if (scope->GetMustInstantiate())
  10091. {
  10092. pnodeObj->AsParseNodeName()->sym->SetIsGlobalCatch(true);
  10093. }
  10094. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10095. // Allow a debugger to stop on the 'catch (e)'
  10096. byteCodeGenerator->StartStatement(pnodeCatch);
  10097. byteCodeGenerator->Writer()->Empty(Js::OpCode::Nop);
  10098. byteCodeGenerator->EndStatement(pnodeCatch);
  10099. if (funcInfo->byteCodeFunction->IsCoroutine())
  10100. {
  10101. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForCatch);
  10102. }
  10103. }
  10104. Emit(pnodeCatch->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10105. if (funcInfo->byteCodeFunction->IsCoroutine())
  10106. {
  10107. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  10108. }
  10109. byteCodeGenerator->PopScope();
  10110. byteCodeGenerator->RecordEndScopeObject(pnodeTryCatch);
  10111. funcInfo->ReleaseLoc(pnodeCatch->pnodeBody);
  10112. if (acquiredTempLocation)
  10113. {
  10114. funcInfo->ReleaseLoc(pnodeObj);
  10115. }
  10116. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  10117. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  10118. byteCodeGenerator->Writer()->MarkLabel(pnodeTryCatch->breakLabel);
  10119. break;
  10120. }
  10121. case knopTryFinally:
  10122. {
  10123. Js::ByteCodeLabel finallyLabel = (Js::ByteCodeLabel) - 1;
  10124. ParseNodeTryFinally * pnodeTryFinally = pnode->AsParseNodeTryFinally();
  10125. ParseNodeTry *pnodeTry = pnodeTryFinally->pnodeTry;
  10126. Assert(pnodeTry);
  10127. ParseNodeFinally *pnodeFinally = pnodeTryFinally->pnodeFinally;
  10128. Assert(pnodeFinally);
  10129. // If we yield from the finally block after an exception, we have to store the exception object for the future next call.
  10130. // When we yield from the Try-Finally the offset to the end of the Try block is needed for the branch instruction.
  10131. Js::RegSlot regException = Js::Constants::NoRegister;
  10132. Js::RegSlot regOffset = Js::Constants::NoRegister;
  10133. finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  10134. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10135. // [CONSIDER][aneeshd] Ideally the TryFinallyWithYield opcode needs to be used only if there is a yield expression.
  10136. // For now, if the function is generator we are using the TryFinallyWithYield.
  10137. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryFinallyWithYield, finallyLabel);
  10138. if (funcInfo->byteCodeFunction->IsCoroutine())
  10139. {
  10140. regException = funcInfo->AcquireTmpRegister();
  10141. regOffset = funcInfo->AcquireTmpRegister();
  10142. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  10143. tryRecForTry.reg1 = regException;
  10144. tryRecForTry.reg2 = regOffset;
  10145. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  10146. }
  10147. else
  10148. {
  10149. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  10150. }
  10151. // Increasing the stack as we will be storing the additional values when we enter try..finally.
  10152. funcInfo->StartRecordingOutArgs(1);
  10153. Emit(pnodeTry->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10154. funcInfo->ReleaseLoc(pnodeTry->pnodeBody);
  10155. if (funcInfo->byteCodeFunction->IsCoroutine())
  10156. {
  10157. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  10158. }
  10159. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  10160. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  10161. // Note: although we don't use OpCode::Leave for finally block,
  10162. // OpCode::LeaveNull causes a return to parent interpreter thunk.
  10163. // This has to be on offset prior to offset of 1st statement of finally.
  10164. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10165. byteCodeGenerator->Writer()->Br(pnodeTryFinally->breakLabel);
  10166. byteCodeGenerator->Writer()->MarkLabel(finallyLabel);
  10167. byteCodeGenerator->Writer()->Empty(Js::OpCode::Finally);
  10168. ByteCodeGenerator::TryScopeRecord tryRecForFinally(Js::OpCode::ResumeFinally, finallyLabel, regException, regOffset);
  10169. if (funcInfo->byteCodeFunction->IsCoroutine())
  10170. {
  10171. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForFinally);
  10172. }
  10173. Emit(pnodeFinally->pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10174. funcInfo->ReleaseLoc(pnodeFinally->pnodeBody);
  10175. if (funcInfo->byteCodeFunction->IsCoroutine())
  10176. {
  10177. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  10178. funcInfo->ReleaseTmpRegister(regOffset);
  10179. funcInfo->ReleaseTmpRegister(regException);
  10180. }
  10181. funcInfo->EndRecordingOutArgs(1);
  10182. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  10183. byteCodeGenerator->Writer()->Empty(Js::OpCode::LeaveNull);
  10184. byteCodeGenerator->Writer()->MarkLabel(pnodeTryFinally->breakLabel);
  10185. break;
  10186. }
  10187. case knopThrow:
  10188. byteCodeGenerator->StartStatement(pnode);
  10189. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  10190. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Throw, pnode->AsParseNodeUni()->pnode1->location);
  10191. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  10192. byteCodeGenerator->EndStatement(pnode);
  10193. break;
  10194. case knopYieldLeaf:
  10195. byteCodeGenerator->StartStatement(pnode);
  10196. funcInfo->AcquireLoc(pnode);
  10197. EmitYield(funcInfo->undefinedConstantRegister, pnode->location, byteCodeGenerator, funcInfo);
  10198. byteCodeGenerator->EndStatement(pnode);
  10199. break;
  10200. case knopAwait:
  10201. case knopYield:
  10202. byteCodeGenerator->StartStatement(pnode);
  10203. funcInfo->AcquireLoc(pnode);
  10204. Emit(pnode->AsParseNodeUni()->pnode1, byteCodeGenerator, funcInfo, false);
  10205. EmitYield(pnode->AsParseNodeUni()->pnode1->location, pnode->location, byteCodeGenerator, funcInfo);
  10206. funcInfo->ReleaseLoc(pnode->AsParseNodeUni()->pnode1);
  10207. byteCodeGenerator->EndStatement(pnode);
  10208. break;
  10209. case knopYieldStar:
  10210. byteCodeGenerator->StartStatement(pnode);
  10211. EmitYieldStar(pnode->AsParseNodeUni(), byteCodeGenerator, funcInfo);
  10212. byteCodeGenerator->EndStatement(pnode);
  10213. break;
  10214. case knopExportDefault:
  10215. Emit(pnode->AsParseNodeExportDefault()->pnodeExpr, byteCodeGenerator, funcInfo, false);
  10216. byteCodeGenerator->EmitAssignmentToDefaultModuleExport(pnode->AsParseNodeExportDefault()->pnodeExpr, funcInfo);
  10217. funcInfo->ReleaseLoc(pnode->AsParseNodeExportDefault()->pnodeExpr);
  10218. pnode = pnode->AsParseNodeExportDefault()->pnodeExpr;
  10219. break;
  10220. default:
  10221. AssertMsg(0, "emit unhandled pnode op");
  10222. break;
  10223. }
  10224. if (fReturnValue && IsExpressionStatement(pnode, byteCodeGenerator->GetScriptContext()) && !pnode->IsPatternDeclaration())
  10225. {
  10226. // If this statement may produce the global function's return value, copy its result to the return register.
  10227. // fReturnValue implies global function, which implies that "return" is a parse error.
  10228. Assert(funcInfo->IsGlobalFunction());
  10229. Assert(pnode->nop != knopReturn);
  10230. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, pnode->location);
  10231. }
  10232. }