ByteCodeEmitter.cpp 460 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "RuntimeByteCodePch.h"
  6. #include "FormalsUtil.h"
  7. #include "Language/AsmJs.h"
  8. void EmitReference(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  9. void EmitAssignment(ParseNode *asgnNode, ParseNode *lhs, Js::RegSlot rhsLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  10. void EmitLoad(ParseNode *rhs, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  11. void EmitCall(ParseNode* pnode, Js::RegSlot rhsLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue, BOOL fEvaluateComponents, BOOL fHasNewTarget, Js::RegSlot overrideThisLocation = Js::Constants::NoRegister);
  12. void EmitSuperFieldPatch(FuncInfo* funcInfo, ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator);
  13. void EmitUseBeforeDeclaration(Symbol *sym, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  14. void EmitUseBeforeDeclarationRuntimeError(ByteCodeGenerator *byteCodeGenerator, Js::RegSlot location);
  15. void VisitClearTmpRegs(ParseNode * pnode, ByteCodeGenerator * byteCodeGenerator, FuncInfo * funcInfo);
  16. bool CallTargetIsArray(ParseNode *pnode)
  17. {
  18. return pnode->nop == knopName && pnode->sxPid.PropertyIdFromNameNode() == Js::PropertyIds::Array;
  19. }
  20. #define STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode) \
  21. if ((isTopLevel)) \
  22. { \
  23. byteCodeGenerator->StartStatement(pnode); \
  24. }
  25. #define ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode) \
  26. if ((isTopLevel)) \
  27. { \
  28. byteCodeGenerator->EndStatement(pnode); \
  29. }
  30. BOOL MayHaveSideEffectOnNode(ParseNode *pnode, ParseNode *pnodeSE)
  31. {
  32. // Try to determine whether pnodeSE may kill the named var represented by pnode.
  33. if (pnode->nop == knopComputedName)
  34. {
  35. pnode = pnode->sxUni.pnode1;
  36. }
  37. if (pnode->nop != knopName)
  38. {
  39. // Only investigating named vars here.
  40. return false;
  41. }
  42. uint fnop = ParseNode::Grfnop(pnodeSE->nop);
  43. if (fnop & fnopLeaf)
  44. {
  45. // pnodeSE is a leaf and can't kill anything.
  46. return false;
  47. }
  48. if (fnop & fnopAsg)
  49. {
  50. // pnodeSE is an assignment (=, ++, +=, etc.)
  51. // Trying to examine the LHS of pnodeSE caused small perf regressions,
  52. // maybe because of code layout or some other subtle effect.
  53. return true;
  54. }
  55. if (fnop & fnopUni)
  56. {
  57. // pnodeSE is a unary op, so recurse to the source (if present - e.g., [] may have no opnd).
  58. if (pnodeSE->nop == knopTempRef)
  59. {
  60. return false;
  61. }
  62. else
  63. {
  64. return pnodeSE->sxUni.pnode1 && MayHaveSideEffectOnNode(pnode, pnodeSE->sxUni.pnode1);
  65. }
  66. }
  67. else if (fnop & fnopBin)
  68. {
  69. // pnodeSE is a binary (or ternary) op, so recurse to the sources (if present).
  70. if (pnodeSE->nop == knopQmark)
  71. {
  72. return MayHaveSideEffectOnNode(pnode, pnodeSE->sxTri.pnode1) ||
  73. MayHaveSideEffectOnNode(pnode, pnodeSE->sxTri.pnode2) ||
  74. MayHaveSideEffectOnNode(pnode, pnodeSE->sxTri.pnode3);
  75. }
  76. else if (pnodeSE->nop == knopCall || pnodeSE->nop == knopNew)
  77. {
  78. return MayHaveSideEffectOnNode(pnode, pnodeSE->sxCall.pnodeTarget) ||
  79. (pnodeSE->sxCall.pnodeArgs && MayHaveSideEffectOnNode(pnode, pnodeSE->sxCall.pnodeArgs));
  80. }
  81. else
  82. {
  83. return MayHaveSideEffectOnNode(pnode, pnodeSE->sxBin.pnode1) ||
  84. (pnodeSE->sxBin.pnode2 && MayHaveSideEffectOnNode(pnode, pnodeSE->sxBin.pnode2));
  85. }
  86. }
  87. else if (pnodeSE->nop == knopList)
  88. {
  89. return true;
  90. }
  91. return false;
  92. }
  93. bool IsCallOfConstants(ParseNode *pnode);
  94. bool BlockHasOwnScope(ParseNode* pnodeBlock, ByteCodeGenerator *byteCodeGenerator);
  95. bool CreateNativeArrays(ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  96. bool IsArguments(ParseNode *pnode)
  97. {
  98. for (;;)
  99. {
  100. switch (pnode->nop)
  101. {
  102. case knopName:
  103. return pnode->sxPid.sym && pnode->sxPid.sym->GetIsArguments();
  104. case knopCall:
  105. case knopNew:
  106. if (IsArguments(pnode->sxCall.pnodeTarget))
  107. {
  108. return true;
  109. }
  110. if (pnode->sxCall.pnodeArgs)
  111. {
  112. ParseNode *pnodeArg = pnode->sxCall.pnodeArgs;
  113. while (pnodeArg->nop == knopList)
  114. {
  115. if (IsArguments(pnodeArg->sxBin.pnode1))
  116. return true;
  117. pnodeArg = pnodeArg->sxBin.pnode2;
  118. }
  119. pnode = pnodeArg;
  120. break;
  121. }
  122. return false;
  123. case knopArray:
  124. if (pnode->sxArrLit.arrayOfNumbers || pnode->sxArrLit.count == 0)
  125. {
  126. return false;
  127. }
  128. pnode = pnode->sxUni.pnode1;
  129. break;
  130. case knopQmark:
  131. if (IsArguments(pnode->sxTri.pnode1) || IsArguments(pnode->sxTri.pnode2))
  132. {
  133. return true;
  134. }
  135. pnode = pnode->sxTri.pnode3;
  136. break;
  137. //
  138. // Cases where we don't check for "arguments" yet.
  139. // Assume that they might have it. Disable the optimization is such scenarios
  140. //
  141. case knopList:
  142. case knopObject:
  143. case knopVarDecl:
  144. case knopConstDecl:
  145. case knopLetDecl:
  146. case knopFncDecl:
  147. case knopClassDecl:
  148. case knopFor:
  149. case knopIf:
  150. case knopDoWhile:
  151. case knopWhile:
  152. case knopForIn:
  153. case knopForOf:
  154. case knopReturn:
  155. case knopBlock:
  156. case knopBreak:
  157. case knopContinue:
  158. case knopLabel:
  159. case knopTypeof:
  160. case knopThrow:
  161. case knopWith:
  162. case knopFinally:
  163. case knopTry:
  164. case knopTryCatch:
  165. case knopTryFinally:
  166. case knopArrayPattern:
  167. case knopObjectPattern:
  168. case knopParamPattern:
  169. return true;
  170. default:
  171. {
  172. uint flags = ParseNode::Grfnop(pnode->nop);
  173. if (flags&fnopUni)
  174. {
  175. Assert(pnode->sxUni.pnode1);
  176. pnode = pnode->sxUni.pnode1;
  177. break;
  178. }
  179. else if (flags&fnopBin)
  180. {
  181. Assert(pnode->sxBin.pnode1 && pnode->sxBin.pnode2);
  182. if (IsArguments(pnode->sxBin.pnode1))
  183. {
  184. return true;
  185. }
  186. pnode = pnode->sxBin.pnode2;
  187. break;
  188. }
  189. return false;
  190. }
  191. }
  192. }
  193. }
  194. bool ApplyEnclosesArgs(ParseNode* fncDecl, ByteCodeGenerator* byteCodeGenerator);
  195. void Emit(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue, bool isConstructorCall = false, ParseNode *bindPnode = nullptr, bool isTopLevel = false);
  196. void EmitComputedFunctionNameVar(ParseNode *nameNode, ParseNode *exprNode, ByteCodeGenerator *byteCodeGenerator);
  197. void EmitBinaryOpnds(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  198. bool IsExpressionStatement(ParseNode* stmt, const Js::ScriptContext *const scriptContext);
  199. void EmitInvoke(Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  200. void EmitInvoke(Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, Js::RegSlot arg1Location);
  201. static const Js::OpCode nopToOp[knopLim] =
  202. {
  203. #define OP(x) Br##x##_A
  204. #define PTNODE(nop,sn,pc,nk,grfnop,json) Js::OpCode::pc,
  205. #include "ptlist.h"
  206. };
  207. static const Js::OpCode nopToCMOp[knopLim] =
  208. {
  209. #define OP(x) Cm##x##_A
  210. #define PTNODE(nop,sn,pc,nk,grfnop,json) Js::OpCode::pc,
  211. #include "ptlist.h"
  212. };
  213. Js::OpCode ByteCodeGenerator::ToChkUndeclOp(Js::OpCode op) const
  214. {
  215. switch (op)
  216. {
  217. case Js::OpCode::StLocalSlot:
  218. return Js::OpCode::StLocalSlotChkUndecl;
  219. case Js::OpCode::StInnerSlot:
  220. return Js::OpCode::StInnerSlotChkUndecl;
  221. case Js::OpCode::StEnvSlot:
  222. return Js::OpCode::StEnvSlotChkUndecl;
  223. case Js::OpCode::StObjSlot:
  224. return Js::OpCode::StObjSlotChkUndecl;
  225. case Js::OpCode::StLocalObjSlot:
  226. return Js::OpCode::StLocalObjSlotChkUndecl;
  227. case Js::OpCode::StInnerObjSlot:
  228. return Js::OpCode::StInnerObjSlotChkUndecl;
  229. case Js::OpCode::StEnvObjSlot:
  230. return Js::OpCode::StEnvObjSlotChkUndecl;
  231. default:
  232. AssertMsg(false, "Unknown opcode for chk undecl mapping");
  233. return Js::OpCode::InvalidOpCode;
  234. }
  235. }
  236. // Tracks a register slot let/const property for the passed in debugger block/catch scope.
  237. // debuggerScope - The scope to add the variable to.
  238. // symbol - The symbol that represents the register property.
  239. // funcInfo - The function info used to store the property into the tracked debugger register slot list.
  240. // flags - The flags to assign to the property.
  241. // isFunctionDeclaration - Whether or not the register is a function declaration, which requires that its byte code offset be updated immediately.
  242. void ByteCodeGenerator::TrackRegisterPropertyForDebugger(
  243. Js::DebuggerScope *debuggerScope,
  244. Symbol *symbol,
  245. FuncInfo *funcInfo,
  246. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  247. bool isFunctionDeclaration /*= false*/)
  248. {
  249. Assert(debuggerScope);
  250. Assert(symbol);
  251. Assert(funcInfo);
  252. Js::RegSlot location = symbol->GetLocation();
  253. Js::DebuggerScope *correctDebuggerScope = debuggerScope;
  254. if (debuggerScope->scopeType != Js::DiagExtraScopesType::DiagBlockScopeDirect && debuggerScope->scopeType != Js::DiagExtraScopesType::DiagCatchScopeDirect)
  255. {
  256. // We have to get the appropriate scope and add property over there.
  257. // Make sure the scope is created whether we're in debug mode or not, because we
  258. // need the empty scopes present during reparsing for debug mode.
  259. correctDebuggerScope = debuggerScope->GetSiblingScope(location, Writer()->GetFunctionWrite());
  260. }
  261. if (this->ShouldTrackDebuggerMetadata() && !symbol->GetIsTrackedForDebugger())
  262. {
  263. // Only track the property if we're in debug mode since it's only needed by the debugger.
  264. Js::PropertyId propertyId = symbol->EnsurePosition(this);
  265. this->Writer()->AddPropertyToDebuggerScope(
  266. correctDebuggerScope,
  267. location,
  268. propertyId,
  269. /*shouldConsumeRegister*/ true,
  270. flags,
  271. isFunctionDeclaration);
  272. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  273. byteCodeFunction->InsertSymbolToRegSlotList(location, propertyId, funcInfo->varRegsCount);
  274. symbol->SetIsTrackedForDebugger(true);
  275. }
  276. }
  277. void ByteCodeGenerator::TrackActivationObjectPropertyForDebugger(
  278. Js::DebuggerScope *debuggerScope,
  279. Symbol *symbol,
  280. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  281. bool isFunctionDeclaration /*= false*/)
  282. {
  283. Assert(debuggerScope);
  284. Assert(symbol);
  285. // Only need to track activation object properties in debug mode.
  286. if (ShouldTrackDebuggerMetadata() && !symbol->GetIsTrackedForDebugger())
  287. {
  288. Js::RegSlot location = symbol->GetLocation();
  289. Js::PropertyId propertyId = symbol->EnsurePosition(this);
  290. this->Writer()->AddPropertyToDebuggerScope(
  291. debuggerScope,
  292. location,
  293. propertyId,
  294. /*shouldConsumeRegister*/ false,
  295. flags,
  296. isFunctionDeclaration);
  297. symbol->SetIsTrackedForDebugger(true);
  298. }
  299. }
  300. void ByteCodeGenerator::TrackSlotArrayPropertyForDebugger(
  301. Js::DebuggerScope *debuggerScope,
  302. Symbol* symbol,
  303. Js::PropertyId propertyId,
  304. Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
  305. bool isFunctionDeclaration /*= false*/)
  306. {
  307. // Note: Slot array properties are tracked even in non-debug mode in order to support slot array serialization
  308. // of let/const variables between non-debug and debug mode (for example, when a slot array var escapes and is retrieved
  309. // after a debugger attach or for WWA apps). They are also needed for heap enumeration.
  310. Assert(debuggerScope);
  311. Assert(symbol);
  312. if (!symbol->GetIsTrackedForDebugger())
  313. {
  314. Js::RegSlot location = symbol->GetScopeSlot();
  315. Assert(location != Js::Constants::NoRegister);
  316. Assert(propertyId != Js::Constants::NoProperty);
  317. this->Writer()->AddPropertyToDebuggerScope(
  318. debuggerScope,
  319. location,
  320. propertyId,
  321. /*shouldConsumeRegister*/ false,
  322. flags,
  323. isFunctionDeclaration);
  324. symbol->SetIsTrackedForDebugger(true);
  325. }
  326. }
  327. // Tracks a function declaration inside a block scope for the debugger metadata's current scope (let binding).
  328. void ByteCodeGenerator::TrackFunctionDeclarationPropertyForDebugger(Symbol *functionDeclarationSymbol, FuncInfo *funcInfoParent)
  329. {
  330. Assert(functionDeclarationSymbol);
  331. Assert(funcInfoParent);
  332. AssertMsg(functionDeclarationSymbol->GetIsBlockVar(), "We should only track inner function let bindings for the debugger.");
  333. // Note: we don't have to check symbol->GetIsTrackedForDebugger, as we are not doing actual work here,
  334. // which is done in other Track* functions that we call.
  335. if (functionDeclarationSymbol->IsInSlot(funcInfoParent))
  336. {
  337. if (functionDeclarationSymbol->GetScope()->GetIsObject())
  338. {
  339. this->TrackActivationObjectPropertyForDebugger(
  340. this->Writer()->GetCurrentDebuggerScope(),
  341. functionDeclarationSymbol,
  342. Js::DebuggerScopePropertyFlags_None,
  343. true /*isFunctionDeclaration*/);
  344. }
  345. else
  346. {
  347. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  348. // Note that slot array inner function bindings are tracked even in non-debug mode in order
  349. // to keep the lifetime of the closure binding that could escape around for heap enumeration.
  350. functionDeclarationSymbol->EnsureScopeSlot(funcInfoParent);
  351. functionDeclarationSymbol->EnsurePosition(this);
  352. this->TrackSlotArrayPropertyForDebugger(
  353. this->Writer()->GetCurrentDebuggerScope(),
  354. functionDeclarationSymbol,
  355. functionDeclarationSymbol->GetPosition(),
  356. Js::DebuggerScopePropertyFlags_None,
  357. true /*isFunctionDeclaration*/);
  358. }
  359. }
  360. else
  361. {
  362. this->TrackRegisterPropertyForDebugger(
  363. this->Writer()->GetCurrentDebuggerScope(),
  364. functionDeclarationSymbol,
  365. funcInfoParent,
  366. Js::DebuggerScopePropertyFlags_None,
  367. true /*isFunctionDeclaration*/);
  368. }
  369. }
  370. // Updates the byte code offset of the property with the passed in location and ID.
  371. // Used to track let/const variables that are in the dead zone debugger side.
  372. // location - The activation object, scope slot index, or register location for the property.
  373. // propertyId - The ID of the property to update.
  374. // shouldConsumeRegister - Whether or not the a register should be consumed (used for reg slot locations).
  375. void ByteCodeGenerator::UpdateDebuggerPropertyInitializationOffset(Js::RegSlot location, Js::PropertyId propertyId, bool shouldConsumeRegister)
  376. {
  377. Assert(this->Writer());
  378. Js::DebuggerScope* currentDebuggerScope = this->Writer()->GetCurrentDebuggerScope();
  379. Assert(currentDebuggerScope);
  380. if (currentDebuggerScope != nullptr)
  381. {
  382. this->Writer()->UpdateDebuggerPropertyInitializationOffset(
  383. currentDebuggerScope,
  384. location,
  385. propertyId,
  386. shouldConsumeRegister);
  387. }
  388. }
  389. void ByteCodeGenerator::LoadHeapArguments(FuncInfo *funcInfo)
  390. {
  391. if (funcInfo->GetHasCachedScope())
  392. {
  393. this->LoadCachedHeapArguments(funcInfo);
  394. }
  395. else
  396. {
  397. this->LoadUncachedHeapArguments(funcInfo);
  398. }
  399. }
  400. void GetFormalArgsArray(ByteCodeGenerator *byteCodeGenerator, FuncInfo * funcInfo, Js::PropertyIdArray *propIds)
  401. {
  402. Assert(funcInfo);
  403. Assert(propIds);
  404. Assert(byteCodeGenerator);
  405. bool hadDuplicates = false;
  406. Js::ArgSlot i = 0;
  407. auto processArg = [&](ParseNode *pnode)
  408. {
  409. if (pnode->IsVarLetOrConst())
  410. {
  411. Assert(i < propIds->count);
  412. Symbol *sym = pnode->sxVar.sym;
  413. Assert(sym);
  414. Js::PropertyId symPos = sym->EnsurePosition(byteCodeGenerator);
  415. //
  416. // Check if the function has any same name parameters
  417. // For the same name param, only the last one will be passed the correct propertyid
  418. // For remaining dup param names, pass Constants::NoProperty
  419. //
  420. for (Js::ArgSlot j = 0; j < i; j++)
  421. {
  422. if (propIds->elements[j] == symPos)
  423. {
  424. // Found a dup parameter name
  425. propIds->elements[j] = Js::Constants::NoProperty;
  426. hadDuplicates = true;
  427. break;
  428. }
  429. }
  430. propIds->elements[i] = symPos;
  431. }
  432. else
  433. {
  434. propIds->elements[i] = Js::Constants::NoProperty;
  435. }
  436. ++i;
  437. };
  438. MapFormals(funcInfo->root, processArg);
  439. propIds->hadDuplicates = hadDuplicates;
  440. }
  441. void ByteCodeGenerator::LoadUncachedHeapArguments(FuncInfo *funcInfo)
  442. {
  443. Assert(funcInfo->GetHasHeapArguments());
  444. Scope *scope = funcInfo->GetBodyScope();
  445. Assert(scope);
  446. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  447. Assert(argSym && argSym->GetIsArguments());
  448. Js::RegSlot argumentsLoc = argSym->GetLocation();
  449. Js::OpCode opcode = !funcInfo->root->sxFnc.HasNonSimpleParameterList() ? Js::OpCode::LdHeapArguments : Js::OpCode::LdLetHeapArguments;
  450. bool hasRest = funcInfo->root->sxFnc.pnodeRest != nullptr;
  451. uint count = funcInfo->inArgsCount + (hasRest ? 1 : 0) - 1;
  452. if (count == 0)
  453. {
  454. // If no formals to function (only "this"), then no need to create the scope object.
  455. // Leave both the arguments location and the propertyIds location as null.
  456. Assert(funcInfo->root->sxFnc.pnodeParams == nullptr && !hasRest);
  457. }
  458. else if (!NeedScopeObjectForArguments(funcInfo, funcInfo->root))
  459. {
  460. // We may not need a scope object for arguments, e.g. strict mode with no eval.
  461. }
  462. else if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  463. {
  464. // Pass the frame object and ID array to the runtime, and put the resulting Arguments object
  465. // at the expected location.
  466. Js::PropertyIdArray *propIds = funcInfo->GetParsedFunctionBody()->AllocatePropertyIdArrayForFormals(count * sizeof(Js::PropertyId), count, 0);
  467. GetFormalArgsArray(this, funcInfo, propIds);
  468. }
  469. this->m_writer.Reg1(opcode, argumentsLoc);
  470. EmitLocalPropInit(argSym->GetLocation(), argSym, funcInfo);
  471. }
  472. void ByteCodeGenerator::LoadCachedHeapArguments(FuncInfo *funcInfo)
  473. {
  474. Assert(funcInfo->GetHasHeapArguments());
  475. Scope *scope = funcInfo->GetBodyScope();
  476. Assert(scope);
  477. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  478. Assert(argSym && argSym->GetIsArguments());
  479. Js::RegSlot argumentsLoc = argSym->GetLocation();
  480. Js::OpCode op = !funcInfo->root->sxFnc.HasNonSimpleParameterList() ? Js::OpCode::LdHeapArgsCached : Js::OpCode::LdLetHeapArgsCached;
  481. this->m_writer.Reg1(op, argumentsLoc);
  482. EmitLocalPropInit(argumentsLoc, argSym, funcInfo);
  483. }
  484. Js::JavascriptArray* ByteCodeGenerator::BuildArrayFromStringList(ParseNode* stringNodeList, uint arrayLength, Js::ScriptContext* scriptContext)
  485. {
  486. Assert(stringNodeList);
  487. uint index = 0;
  488. Js::Var str;
  489. IdentPtr pid;
  490. Js::JavascriptArray* pArr = scriptContext->GetLibrary()->CreateArray(arrayLength);
  491. while (stringNodeList->nop == knopList)
  492. {
  493. Assert(stringNodeList->sxBin.pnode1->nop == knopStr);
  494. pid = stringNodeList->sxBin.pnode1->sxPid.pid;
  495. str = Js::JavascriptString::NewCopyBuffer(pid->Psz(), pid->Cch(), scriptContext);
  496. pArr->SetItemWithAttributes(index, str, PropertyEnumerable);
  497. stringNodeList = stringNodeList->sxBin.pnode2;
  498. index++;
  499. }
  500. Assert(stringNodeList->nop == knopStr);
  501. pid = stringNodeList->sxPid.pid;
  502. str = Js::JavascriptString::NewCopyBuffer(pid->Psz(), pid->Cch(), scriptContext);
  503. pArr->SetItemWithAttributes(index, str, PropertyEnumerable);
  504. return pArr;
  505. }
  506. // For now, this just assigns field ids for the current script.
  507. // Later, we will combine this information with the global field id map.
  508. // This temporary code will not work if a global member is accessed both with and without a LHS.
  509. void ByteCodeGenerator::AssignPropertyIds(Js::ParseableFunctionInfo* functionInfo)
  510. {
  511. globalScope->ForEachSymbol([this, functionInfo](Symbol * sym)
  512. {
  513. this->AssignPropertyId(sym, functionInfo);
  514. });
  515. }
  516. void ByteCodeGenerator::InitBlockScopedContent(ParseNode *pnodeBlock, Js::DebuggerScope* debuggerScope, FuncInfo *funcInfo)
  517. {
  518. Assert(pnodeBlock->nop == knopBlock);
  519. auto genBlockInit = [this, debuggerScope, funcInfo](ParseNode *pnode)
  520. {
  521. // Only check if the scope is valid when let/const vars are in the scope. If there are no let/const vars,
  522. // the debugger scope will not be created.
  523. AssertMsg(debuggerScope, "Missing a case of scope tracking in BeginEmitBlock.");
  524. FuncInfo *funcInfo = this->TopFuncInfo();
  525. Symbol *sym = pnode->sxVar.sym;
  526. Scope *scope = sym->GetScope();
  527. if (sym->GetIsGlobal())
  528. {
  529. Js::PropertyId propertyId = sym->EnsurePosition(this);
  530. if (this->flags & fscrEval)
  531. {
  532. AssertMsg(this->IsConsoleScopeEval(), "Let/Consts cannot be in global scope outside of console eval");
  533. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ? Js::OpCode::InitUndeclConsoleConstFld : Js::OpCode::InitUndeclConsoleLetFld;
  534. this->m_writer.ElementScopedU(op, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  535. }
  536. else
  537. {
  538. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  539. Js::OpCode::InitUndeclRootConstFld : Js::OpCode::InitUndeclRootLetFld;
  540. this->m_writer.ElementRootU(op, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  541. }
  542. }
  543. else if (sym->IsInSlot(funcInfo) || (scope->GetIsObject() && sym->NeedsSlotAlloc(funcInfo)))
  544. {
  545. if (scope->GetIsObject())
  546. {
  547. Js::RegSlot scopeLocation = scope->GetLocation();
  548. Js::PropertyId propertyId = sym->EnsurePosition(this);
  549. if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  550. {
  551. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  552. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  553. Js::OpCode::InitUndeclLocalConstFld : Js::OpCode::InitUndeclLocalLetFld;
  554. this->m_writer.ElementP(op, ByteCodeGenerator::ReturnRegister, cacheId);
  555. }
  556. else
  557. {
  558. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
  559. Js::OpCode op = (sym->GetDecl()->nop == knopConstDecl) ?
  560. Js::OpCode::InitUndeclConstFld : Js::OpCode::InitUndeclLetFld;
  561. this->m_writer.ElementPIndexed(op, ByteCodeGenerator::ReturnRegister, scope->GetInnerScopeIndex(), cacheId);
  562. }
  563. TrackActivationObjectPropertyForDebugger(debuggerScope, sym, pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  564. }
  565. else
  566. {
  567. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  568. this->m_writer.Reg1(Js::OpCode::InitUndecl, tmpReg);
  569. this->EmitLocalPropInit(tmpReg, sym, funcInfo);
  570. funcInfo->ReleaseTmpRegister(tmpReg);
  571. // Slot array properties are tracked in non-debug mode as well because they need to stay
  572. // around for heap enumeration and escaping during attach/detach.
  573. TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(this), pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  574. }
  575. }
  576. else if (!sym->GetIsModuleExportStorage())
  577. {
  578. if (sym->GetDecl()->sxVar.isSwitchStmtDecl)
  579. {
  580. // let/const declared in a switch is the only case of a variable that must be checked for
  581. // use-before-declaration dynamically within its own function.
  582. this->m_writer.Reg1(Js::OpCode::InitUndecl, sym->GetLocation());
  583. }
  584. // Syms that begin in register may be delay-captured. In debugger mode, such syms
  585. // will live only in slots, so tell the debugger to find them there.
  586. if (sym->NeedsSlotAlloc(funcInfo))
  587. {
  588. TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(this), pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  589. }
  590. else
  591. {
  592. TrackRegisterPropertyForDebugger(debuggerScope, sym, funcInfo, pnode->nop == knopConstDecl ? Js::DebuggerScopePropertyFlags_Const : Js::DebuggerScopePropertyFlags_None);
  593. }
  594. }
  595. };
  596. IterateBlockScopedVariables(pnodeBlock, genBlockInit);
  597. }
  598. // Records the start of a debugger scope if the passed in node has any let/const variables (or is not a block node).
  599. // If it has no let/const variables, nullptr will be returned as no scope will be created.
  600. Js::DebuggerScope* ByteCodeGenerator::RecordStartScopeObject(ParseNode *pnodeBlock, Js::DiagExtraScopesType scopeType, Js::RegSlot scopeLocation /*= Js::Constants::NoRegister*/, int* index /*= nullptr*/)
  601. {
  602. Assert(pnodeBlock);
  603. if (pnodeBlock->nop == knopBlock && !pnodeBlock->sxBlock.HasBlockScopedContent())
  604. {
  605. // In order to reduce allocations now that we track debugger scopes in non-debug mode,
  606. // don't add a block to the chain if it has no let/const variables at all.
  607. return nullptr;
  608. }
  609. return this->Writer()->RecordStartScopeObject(scopeType, scopeLocation, index);
  610. }
  611. // Records the end of the current scope, but only if the current block has block scoped content.
  612. // Otherwise, a scope would not have been added (see ByteCodeGenerator::RecordStartScopeObject()).
  613. void ByteCodeGenerator::RecordEndScopeObject(ParseNode *pnodeBlock)
  614. {
  615. Assert(pnodeBlock);
  616. if (pnodeBlock->nop == knopBlock && !pnodeBlock->sxBlock.HasBlockScopedContent())
  617. {
  618. return;
  619. }
  620. this->Writer()->RecordEndScopeObject();
  621. }
  622. void BeginEmitBlock(ParseNode *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  623. {
  624. Js::DebuggerScope* debuggerScope = nullptr;
  625. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  626. {
  627. Scope *scope = pnodeBlock->sxBlock.scope;
  628. byteCodeGenerator->PushScope(scope);
  629. Js::RegSlot scopeLocation = scope->GetLocation();
  630. if (scope->GetMustInstantiate())
  631. {
  632. Assert(scopeLocation == Js::Constants::NoRegister);
  633. scopeLocation = funcInfo->FirstInnerScopeReg() + scope->GetInnerScopeIndex();
  634. if (scope->GetIsObject())
  635. {
  636. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInObject, scopeLocation);
  637. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::NewBlockScope, scope->GetInnerScopeIndex());
  638. }
  639. else
  640. {
  641. int scopeIndex = Js::DebuggerScope::InvalidScopeIndex;
  642. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInSlot, scopeLocation, &scopeIndex);
  643. // TODO: Handle heap enumeration
  644. int scopeSlotCount = scope->GetScopeSlotCount();
  645. byteCodeGenerator->Writer()->Num3(Js::OpCode::NewInnerScopeSlots, scope->GetInnerScopeIndex(), scopeSlotCount + Js::ScopeSlots::FirstSlotIndex, scopeIndex);
  646. }
  647. }
  648. else
  649. {
  650. // In the direct register access case, there is no block scope emitted but we can still track
  651. // the start and end offset of the block. The location registers for let/const variables will still be
  652. // captured along with this range in InitBlockScopedContent().
  653. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeDirect);
  654. }
  655. bool const isGlobalEvalBlockScope = scope->IsGlobalEvalBlockScope();
  656. Js::RegSlot frameDisplayLoc = Js::Constants::NoRegister;
  657. Js::RegSlot tmpInnerEnvReg = Js::Constants::NoRegister;
  658. ParseNodePtr pnodeScope;
  659. for (pnodeScope = pnodeBlock->sxBlock.pnodeScopes; pnodeScope;)
  660. {
  661. switch (pnodeScope->nop)
  662. {
  663. case knopFncDecl:
  664. if (pnodeScope->sxFnc.IsDeclaration())
  665. {
  666. // The frameDisplayLoc register's lifetime has to be controlled by this function. We can't let
  667. // it be released by DefineOneFunction, because further iterations of this loop can allocate
  668. // temps, and we can't let frameDisplayLoc be re-purposed until this loop completes.
  669. // So we'll supply a temp that we allocate and release here.
  670. if (frameDisplayLoc == Js::Constants::NoRegister)
  671. {
  672. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  673. {
  674. frameDisplayLoc = funcInfo->frameDisplayRegister;
  675. }
  676. else
  677. {
  678. frameDisplayLoc = funcInfo->GetEnvRegister();
  679. }
  680. tmpInnerEnvReg = funcInfo->AcquireTmpRegister();
  681. frameDisplayLoc = byteCodeGenerator->PrependLocalScopes(frameDisplayLoc, tmpInnerEnvReg, funcInfo);
  682. }
  683. byteCodeGenerator->DefineOneFunction(pnodeScope, funcInfo, true, frameDisplayLoc);
  684. }
  685. // If this is the global eval block scope, the function is actually assigned to the global
  686. // so we don't need to keep the registers.
  687. if (isGlobalEvalBlockScope)
  688. {
  689. funcInfo->ReleaseLoc(pnodeScope);
  690. pnodeScope->location = Js::Constants::NoRegister;
  691. }
  692. pnodeScope = pnodeScope->sxFnc.pnodeNext;
  693. break;
  694. case knopBlock:
  695. pnodeScope = pnodeScope->sxBlock.pnodeNext;
  696. break;
  697. case knopCatch:
  698. pnodeScope = pnodeScope->sxCatch.pnodeNext;
  699. break;
  700. case knopWith:
  701. pnodeScope = pnodeScope->sxWith.pnodeNext;
  702. break;
  703. }
  704. }
  705. if (tmpInnerEnvReg != Js::Constants::NoRegister)
  706. {
  707. funcInfo->ReleaseTmpRegister(tmpInnerEnvReg);
  708. }
  709. if (pnodeBlock->sxBlock.scope->IsGlobalEvalBlockScope() && funcInfo->thisScopeSlot != Js::Constants::NoRegister)
  710. {
  711. Scope* globalEvalBlockScope = funcInfo->GetGlobalEvalBlockScope();
  712. byteCodeGenerator->EmitInitCapturedThis(funcInfo, globalEvalBlockScope);
  713. }
  714. }
  715. else
  716. {
  717. Scope *scope = pnodeBlock->sxBlock.scope;
  718. if (scope)
  719. {
  720. if (scope->GetMustInstantiate())
  721. {
  722. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInObject);
  723. }
  724. else
  725. {
  726. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeDirect);
  727. }
  728. }
  729. else
  730. {
  731. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnodeBlock, Js::DiagExtraScopesType::DiagBlockScopeInSlot);
  732. }
  733. }
  734. byteCodeGenerator->InitBlockScopedContent(pnodeBlock, debuggerScope, funcInfo);
  735. }
  736. void EndEmitBlock(ParseNode *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  737. {
  738. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  739. {
  740. Scope *scope = pnodeBlock->sxBlock.scope;
  741. Assert(scope);
  742. Assert(scope == byteCodeGenerator->GetCurrentScope());
  743. byteCodeGenerator->PopScope();
  744. }
  745. byteCodeGenerator->RecordEndScopeObject(pnodeBlock);
  746. }
  747. void CloneEmitBlock(ParseNode *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  748. {
  749. if (BlockHasOwnScope(pnodeBlock, byteCodeGenerator))
  750. {
  751. // Only let variables have observable behavior when there are per iteration
  752. // bindings. const variables do not since they are immutable. Therefore,
  753. // (and the spec agrees), only create new scope clones if the loop variable
  754. // is a let declaration.
  755. bool isConst = false;
  756. pnodeBlock->sxBlock.scope->ForEachSymbolUntil([&isConst](Symbol * const sym) {
  757. // Exploit the fact that a for loop sxBlock can only have let and const
  758. // declarations, and can only have one or the other, regardless of how
  759. // many syms there might be. Thus only check the first sym.
  760. isConst = sym->GetDecl()->nop == knopConstDecl;
  761. return true;
  762. });
  763. if (!isConst)
  764. {
  765. Scope *scope = pnodeBlock->sxBlock.scope;
  766. Assert(scope == byteCodeGenerator->GetCurrentScope());
  767. if (scope->GetMustInstantiate())
  768. {
  769. Js::OpCode op = scope->GetIsObject() ? Js::OpCode::CloneBlockScope : Js::OpCode::CloneInnerScopeSlots;
  770. byteCodeGenerator->Writer()->Unsigned1(op, scope->GetInnerScopeIndex());
  771. }
  772. }
  773. }
  774. }
  775. void EmitBlock(ParseNode *pnodeBlock, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue)
  776. {
  777. Assert(pnodeBlock->nop == knopBlock);
  778. ParseNode *pnode = pnodeBlock->sxBlock.pnodeStmt;
  779. if (pnode == nullptr)
  780. {
  781. return;
  782. }
  783. BeginEmitBlock(pnodeBlock, byteCodeGenerator, funcInfo);
  784. ParseNode *pnodeLastValStmt = pnodeBlock->sxBlock.pnodeLastValStmt;
  785. while (pnode->nop == knopList)
  786. {
  787. ParseNode* stmt = pnode->sxBin.pnode1;
  788. if (stmt == pnodeLastValStmt)
  789. {
  790. // This is the last guaranteed return value, so any potential return values have to be
  791. // copied to the return register from this point forward.
  792. pnodeLastValStmt = nullptr;
  793. }
  794. byteCodeGenerator->EmitTopLevelStatement(stmt, funcInfo, fReturnValue && (pnodeLastValStmt == nullptr));
  795. pnode = pnode->sxBin.pnode2;
  796. }
  797. if (pnode == pnodeLastValStmt)
  798. {
  799. pnodeLastValStmt = nullptr;
  800. }
  801. byteCodeGenerator->EmitTopLevelStatement(pnode, funcInfo, fReturnValue && (pnodeLastValStmt == nullptr));
  802. EndEmitBlock(pnodeBlock, byteCodeGenerator, funcInfo);
  803. }
  804. void ClearTmpRegs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* emitFunc)
  805. {
  806. if (emitFunc->IsTmpReg(pnode->location))
  807. {
  808. pnode->location = Js::Constants::NoRegister;
  809. }
  810. }
  811. void ByteCodeGenerator::EmitTopLevelStatement(ParseNode *stmt, FuncInfo *funcInfo, BOOL fReturnValue)
  812. {
  813. if (stmt->nop == knopFncDecl && stmt->sxFnc.IsDeclaration())
  814. {
  815. // Function declarations (not function-declaration RHS's) are already fully processed.
  816. // Skip them here so the temp registers don't get messed up.
  817. return;
  818. }
  819. if (stmt->nop == knopName || stmt->nop == knopDot)
  820. {
  821. // Generating span for top level names are mostly useful in debugging mode, because user can debug it even though no side-effect expected.
  822. // But the name can have runtime error, e.g., foo.bar; // where foo is not defined.
  823. // At this time we need to throw proper line number and offset. so recording on all modes will be useful.
  824. StartStatement(stmt);
  825. Writer()->Empty(Js::OpCode::Nop);
  826. EndStatement(stmt);
  827. }
  828. Emit(stmt, this, funcInfo, fReturnValue, false/*isConstructorCall*/, nullptr/*bindPnode*/, true/*isTopLevel*/);
  829. if (funcInfo->IsTmpReg(stmt->location))
  830. {
  831. if (!stmt->isUsed && !fReturnValue)
  832. {
  833. m_writer.Reg1(Js::OpCode::Unused, stmt->location);
  834. }
  835. funcInfo->ReleaseLoc(stmt);
  836. }
  837. }
  838. // ByteCodeGenerator::DefineFunctions
  839. //
  840. // Emit byte code for scope-wide function definitions before any calls in the scope, regardless of lexical
  841. // order. Note that stores to the closure array are not emitted until we see the knopFncDecl in the tree
  842. // to make sure that sources of the stores have been defined.
  843. void ByteCodeGenerator::DefineFunctions(FuncInfo *funcInfoParent)
  844. {
  845. // DefineCachedFunctions doesn't depend on whether the user vars are declared or not, so
  846. // we'll just overload this variable to mean that the functions getting called again and we don't need to do anything
  847. if (funcInfoParent->GetHasCachedScope())
  848. {
  849. this->DefineCachedFunctions(funcInfoParent);
  850. }
  851. else
  852. {
  853. this->DefineUncachedFunctions(funcInfoParent);
  854. }
  855. }
  856. // Iterate over all child functions in a function's parameter and body scopes.
  857. template<typename Fn>
  858. void MapContainerScopeFunctions(ParseNode* pnodeScope, Fn fn)
  859. {
  860. auto mapFncDeclsInScopeList = [&](ParseNode *pnodeHead)
  861. {
  862. for (ParseNode *pnode = pnodeHead; pnode != nullptr;)
  863. {
  864. switch (pnode->nop)
  865. {
  866. case knopFncDecl:
  867. fn(pnode);
  868. pnode = pnode->sxFnc.pnodeNext;
  869. break;
  870. case knopBlock:
  871. pnode = pnode->sxBlock.pnodeNext;
  872. break;
  873. case knopCatch:
  874. pnode = pnode->sxCatch.pnodeNext;
  875. break;
  876. case knopWith:
  877. pnode = pnode->sxWith.pnodeNext;
  878. break;
  879. default:
  880. AssertMsg(false, "Unexpected opcode in tree of scopes");
  881. return;
  882. }
  883. }
  884. };
  885. pnodeScope->sxFnc.MapContainerScopes(mapFncDeclsInScopeList);
  886. }
  887. void ByteCodeGenerator::DefineCachedFunctions(FuncInfo *funcInfoParent)
  888. {
  889. ParseNode *pnodeParent = funcInfoParent->root;
  890. uint slotCount = 0;
  891. auto countFncSlots = [&](ParseNode *pnodeFnc)
  892. {
  893. if (pnodeFnc->sxFnc.GetFuncSymbol() != nullptr && pnodeFnc->sxFnc.IsDeclaration())
  894. {
  895. slotCount++;
  896. }
  897. };
  898. MapContainerScopeFunctions(pnodeParent, countFncSlots);
  899. if (slotCount == 0)
  900. {
  901. return;
  902. }
  903. size_t extraBytesActual = AllocSizeMath::Mul(slotCount, sizeof(Js::FuncInfoEntry));
  904. // Reg2Aux takes int for byteCount so we need to convert to int. OOM if we can't because it would truncate data.
  905. if (extraBytesActual > INT_MAX)
  906. {
  907. Js::Throw::OutOfMemory();
  908. }
  909. int extraBytes = (int)extraBytesActual;
  910. Js::FuncInfoArray *info = AnewPlus(alloc, extraBytes, Js::FuncInfoArray, slotCount);
  911. slotCount = 0;
  912. auto fillEntries = [&](ParseNode *pnodeFnc)
  913. {
  914. Symbol *sym = pnodeFnc->sxFnc.GetFuncSymbol();
  915. if (sym != nullptr && (pnodeFnc->sxFnc.IsDeclaration()))
  916. {
  917. AssertMsg(!pnodeFnc->sxFnc.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->sxFnc.nestedIndex;
  920. entry->scopeSlot = sym->GetScopeSlot();
  921. slotCount++;
  922. }
  923. };
  924. MapContainerScopeFunctions(pnodeParent, fillEntries);
  925. m_writer.AuxNoReg(Js::OpCode::InitCachedFuncs,
  926. info,
  927. sizeof(Js::FuncInfoArray) + extraBytes,
  928. sizeof(Js::FuncInfoArray) + extraBytes);
  929. slotCount = 0;
  930. auto defineOrGetCachedFunc = [&](ParseNode *pnodeFnc)
  931. {
  932. Symbol *sym = pnodeFnc->sxFnc.GetFuncSymbol();
  933. if (pnodeFnc->sxFnc.IsDeclaration())
  934. {
  935. // Do we need to define the function here (i.e., is it not one of our cached locals)?
  936. // Only happens if the sym is null (e.g., function x.y(){}).
  937. if (sym == nullptr)
  938. {
  939. this->DefineOneFunction(pnodeFnc, funcInfoParent);
  940. }
  941. else if (!sym->IsInSlot(funcInfoParent) && sym->GetLocation() != Js::Constants::NoRegister)
  942. {
  943. // If it was defined by InitCachedFuncs, do we need to put it in a register rather than a slot?
  944. m_writer.Reg1Unsigned1(Js::OpCode::GetCachedFunc, sym->GetLocation(), slotCount);
  945. }
  946. // The "x = function() {...}" case is being generated on the fly, during emission,
  947. // so the caller expects to be able to release this register.
  948. funcInfoParent->ReleaseLoc(pnodeFnc);
  949. pnodeFnc->location = Js::Constants::NoRegister;
  950. slotCount++;
  951. }
  952. };
  953. MapContainerScopeFunctions(pnodeParent, defineOrGetCachedFunc);
  954. AdeletePlus(alloc, extraBytes, info);
  955. }
  956. void ByteCodeGenerator::DefineUncachedFunctions(FuncInfo *funcInfoParent)
  957. {
  958. ParseNode *pnodeParent = funcInfoParent->root;
  959. auto defineCheck = [&](ParseNode *pnodeFnc)
  960. {
  961. Assert(pnodeFnc->nop == knopFncDecl);
  962. //
  963. // Don't define the function upfront in following cases
  964. // 1. x = function() {...};
  965. // Don't define the function for all modes.
  966. // Such a function can only be accessed via the LHS, so we define it at the assignment point
  967. // rather than the scope entry to save a register (and possibly save the whole definition).
  968. //
  969. // 2. x = function f() {...};
  970. // f is not visible in the enclosing scope.
  971. // Such function expressions should be emitted only at the assignment point, as can be used only
  972. // after the assignment. Might save register.
  973. //
  974. if (pnodeFnc->sxFnc.IsDeclaration())
  975. {
  976. this->DefineOneFunction(pnodeFnc, funcInfoParent);
  977. // The "x = function() {...}" case is being generated on the fly, during emission,
  978. // so the caller expects to be able to release this register.
  979. funcInfoParent->ReleaseLoc(pnodeFnc);
  980. pnodeFnc->location = Js::Constants::NoRegister;
  981. }
  982. };
  983. MapContainerScopeFunctions(pnodeParent, defineCheck);
  984. }
  985. void EmitAssignmentToFuncName(ParseNode *pnodeFnc, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfoParent)
  986. {
  987. // Assign the location holding the func object reference to the given name.
  988. Symbol *sym = pnodeFnc->sxFnc.pnodeName->sxVar.sym;
  989. if (sym != nullptr && !sym->GetIsFuncExpr())
  990. {
  991. if (sym->GetIsModuleExportStorage())
  992. {
  993. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  994. }
  995. else if (sym->GetIsGlobal())
  996. {
  997. Js::PropertyId propertyId = sym->GetPosition();
  998. byteCodeGenerator->EmitGlobalFncDeclInit(pnodeFnc->location, propertyId, funcInfoParent);
  999. if (byteCodeGenerator->GetFlags() & fscrEval && !funcInfoParent->GetIsStrictMode())
  1000. {
  1001. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  1002. }
  1003. }
  1004. else
  1005. {
  1006. if (sym->NeedsSlotAlloc(funcInfoParent))
  1007. {
  1008. if (!sym->GetHasNonCommittedReference() ||
  1009. (funcInfoParent->GetParsedFunctionBody()->DoStackNestedFunc()))
  1010. {
  1011. // No point in trying to optimize if there are no references before we have to commit to slot.
  1012. // And not safe to delay putting a stack function in the slot, since we may miss boxing.
  1013. sym->SetIsCommittedToSlot();
  1014. }
  1015. }
  1016. if (sym->GetScope()->GetFunc() != byteCodeGenerator->TopFuncInfo())
  1017. {
  1018. byteCodeGenerator->EmitPropStore(pnodeFnc->location, sym, nullptr, funcInfoParent);
  1019. }
  1020. else if (!sym->GetIsBlockVar() || sym->HasRealBlockVarRef() || sym->GetScope()->GetIsObject())
  1021. {
  1022. byteCodeGenerator->EmitLocalPropInit(pnodeFnc->location, sym, funcInfoParent);
  1023. }
  1024. Symbol * fncScopeSym = sym->GetFuncScopeVarSym();
  1025. if (fncScopeSym)
  1026. {
  1027. if (fncScopeSym->GetIsGlobal() && byteCodeGenerator->GetFlags() & fscrEval)
  1028. {
  1029. Js::PropertyId propertyId = fncScopeSym->GetPosition();
  1030. byteCodeGenerator->EmitGlobalFncDeclInit(pnodeFnc->location, propertyId, funcInfoParent);
  1031. }
  1032. else
  1033. {
  1034. byteCodeGenerator->EmitPropStore(pnodeFnc->location, fncScopeSym, nullptr, funcInfoParent, false, false, /* isFncDeclVar */true);
  1035. }
  1036. }
  1037. }
  1038. }
  1039. }
  1040. Js::RegSlot ByteCodeGenerator::DefineOneFunction(ParseNode *pnodeFnc, FuncInfo *funcInfoParent, bool generateAssignment, Js::RegSlot regEnv, Js::RegSlot frameDisplayTemp)
  1041. {
  1042. Assert(pnodeFnc->nop == knopFncDecl);
  1043. funcInfoParent->AcquireLoc(pnodeFnc);
  1044. if (regEnv == Js::Constants::NoRegister)
  1045. {
  1046. // If the child needs a closure, find a heap-allocated frame to pass to it.
  1047. if (frameDisplayTemp != Js::Constants::NoRegister)
  1048. {
  1049. // We allocated a temp to hold a local frame display value. Use that.
  1050. // It's likely that the FD is on the stack, and we used the temp to load it back.
  1051. regEnv = frameDisplayTemp;
  1052. }
  1053. else if (funcInfoParent->frameDisplayRegister != Js::Constants::NoRegister)
  1054. {
  1055. // This function has built a frame display, so pass it down.
  1056. regEnv = funcInfoParent->frameDisplayRegister;
  1057. }
  1058. else
  1059. {
  1060. // This function has no captured locals but inherits a closure environment, so pass it down.
  1061. regEnv = funcInfoParent->GetEnvRegister();
  1062. }
  1063. regEnv = this->PrependLocalScopes(regEnv, Js::Constants::NoRegister, funcInfoParent);
  1064. }
  1065. // AssertMsg(funcInfo->nonLocalSymbols == 0 || regEnv != funcInfoParent->nullConstantRegister,
  1066. // "We need a closure for the nested function");
  1067. // 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
  1068. if (regEnv == funcInfoParent->frameDisplayRegister || regEnv == funcInfoParent->GetEnvRegister())
  1069. {
  1070. m_writer.NewFunction(pnodeFnc->location, pnodeFnc->sxFnc.nestedIndex, pnodeFnc->sxFnc.IsCoroutine());
  1071. }
  1072. else
  1073. {
  1074. m_writer.NewInnerFunction(pnodeFnc->location, pnodeFnc->sxFnc.nestedIndex, regEnv, pnodeFnc->sxFnc.IsCoroutine());
  1075. }
  1076. if (funcInfoParent->IsGlobalFunction() && (this->flags & fscrEval))
  1077. {
  1078. // A function declared at global scope in eval is untrackable,
  1079. // so make sure the caller's cached scope is invalidated.
  1080. this->funcEscapes = true;
  1081. }
  1082. else
  1083. {
  1084. if (pnodeFnc->sxFnc.IsDeclaration())
  1085. {
  1086. Symbol * funcSymbol = pnodeFnc->sxFnc.GetFuncSymbol();
  1087. if (funcSymbol)
  1088. {
  1089. // In the case where a let/const declaration is the same symbol name
  1090. // as the function declaration (shadowing case), the let/const var and
  1091. // the function declaration symbol are the same and share the same flags
  1092. // (particularly, sym->GetIsBlockVar() for this code path).
  1093. //
  1094. // For example:
  1095. // let a = 0; // <-- sym->GetIsBlockVar() = true
  1096. // function b(){} // <-- sym2->GetIsBlockVar() = false
  1097. //
  1098. // let x = 0; // <-- sym3->GetIsBlockVar() = true
  1099. // function x(){} // <-- sym3->GetIsBlockVar() = true
  1100. //
  1101. // In order to tell if the function is actually part
  1102. // of a block scope, we compare against the function scope here.
  1103. // Note that having a function with the same name as a let/const declaration
  1104. // is a redeclaration error, but we're pushing the fix for this out since it's
  1105. // a bit involved.
  1106. Assert(funcInfoParent->GetBodyScope() != nullptr && funcSymbol->GetScope() != nullptr);
  1107. bool isFunctionDeclarationInBlock = funcSymbol->GetIsBlockVar();
  1108. // Track all vars/lets/consts register slot function declarations.
  1109. if (ShouldTrackDebuggerMetadata()
  1110. // If this is a let binding function declaration at global level, we want to
  1111. // be sure to track the register location as well.
  1112. && !(funcInfoParent->IsGlobalFunction() && !isFunctionDeclarationInBlock))
  1113. {
  1114. if (!funcSymbol->IsInSlot(funcInfoParent))
  1115. {
  1116. funcInfoParent->byteCodeFunction->GetFunctionBody()->InsertSymbolToRegSlotList(funcSymbol->GetName(), pnodeFnc->location, funcInfoParent->varRegsCount);
  1117. }
  1118. }
  1119. if (isFunctionDeclarationInBlock)
  1120. {
  1121. // We only track inner let bindings for the debugger side.
  1122. this->TrackFunctionDeclarationPropertyForDebugger(funcSymbol, funcInfoParent);
  1123. }
  1124. }
  1125. }
  1126. }
  1127. if (pnodeFnc->sxFnc.IsDefaultModuleExport())
  1128. {
  1129. this->EmitAssignmentToDefaultModuleExport(pnodeFnc, funcInfoParent);
  1130. }
  1131. if (pnodeFnc->sxFnc.pnodeName == nullptr || !generateAssignment)
  1132. {
  1133. return regEnv;
  1134. }
  1135. EmitAssignmentToFuncName(pnodeFnc, this, funcInfoParent);
  1136. return regEnv;
  1137. }
  1138. void ByteCodeGenerator::DefineUserVars(FuncInfo *funcInfo)
  1139. {
  1140. // Initialize scope-wide variables on entry to the scope. TODO: optimize by detecting uses that are always reached
  1141. // by an existing initialization.
  1142. BOOL fGlobal = funcInfo->IsGlobalFunction();
  1143. ParseNode *pnode;
  1144. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1145. // Global declarations need a temp register to hold the init value, but the node shouldn't get a register.
  1146. // Just assign one on the fly and re-use it for all initializations.
  1147. Js::RegSlot tmpReg = fGlobal ? funcInfo->AcquireTmpRegister() : Js::Constants::NoRegister;
  1148. for (pnode = funcInfo->root->sxFnc.pnodeVars; pnode; pnode = pnode->sxVar.pnodeNext)
  1149. {
  1150. Symbol* sym = pnode->sxVar.sym;
  1151. if (sym != nullptr && !(pnode->sxVar.isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  1152. {
  1153. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  1154. {
  1155. // The init node was bound to the catch object, because it's inside a catch and has the
  1156. // same name as the catch object. But we want to define a user var at function scope,
  1157. // so find the right symbol. (We'll still assign the RHS value to the catch object symbol.)
  1158. // This also applies to a var declaration in the same scope as a let declaration.
  1159. #if DBG
  1160. if (!sym->GetIsCatch())
  1161. {
  1162. // Assert that catch cannot be at function scope and let and var at function scope is redeclaration error.
  1163. Assert(funcInfo->bodyScope != sym->GetScope());
  1164. }
  1165. #endif
  1166. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  1167. Assert(sym && !sym->GetIsCatch() && !sym->GetIsBlockVar());
  1168. }
  1169. if (sym->GetSymbolType() == STVariable && !sym->GetIsModuleExportStorage())
  1170. {
  1171. if (fGlobal)
  1172. {
  1173. Js::PropertyId propertyId = sym->EnsurePosition(this);
  1174. // We do need to initialize some globals to avoid JS errors on loading undefined variables.
  1175. // But we first need to make sure we're not trashing built-ins.
  1176. if (this->flags & fscrEval)
  1177. {
  1178. if (funcInfo->byteCodeFunction->GetIsStrictMode())
  1179. {
  1180. // Check/Init the property of the frame object
  1181. this->m_writer.ElementRootU(Js::OpCode::LdLocalElemUndef,
  1182. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1183. }
  1184. else
  1185. {
  1186. // The check and the init involve the first element in the scope chain.
  1187. this->m_writer.ElementScopedU(
  1188. Js::OpCode::LdElemUndefScoped, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1189. }
  1190. }
  1191. else
  1192. {
  1193. this->m_writer.ElementU(Js::OpCode::LdElemUndef, ByteCodeGenerator::RootObjectRegister,
  1194. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  1195. }
  1196. }
  1197. else if (!sym->GetIsArguments())
  1198. {
  1199. if (sym->NeedsSlotAlloc(funcInfo))
  1200. {
  1201. if (!sym->GetHasNonCommittedReference() ||
  1202. (sym->GetHasFuncAssignment() && funcInfo->GetParsedFunctionBody()->DoStackNestedFunc()))
  1203. {
  1204. // No point in trying to optimize if there are no references before we have to commit to slot.
  1205. // And not safe to delay putting a stack function in the slot, since we may miss boxing.
  1206. sym->SetIsCommittedToSlot();
  1207. }
  1208. }
  1209. // Undef-initialize the home location if it is a register (not closure-captured, or else capture
  1210. // is delayed) or a property of an object.
  1211. if ((!sym->GetHasInit() && !sym->IsInSlot(funcInfo)) ||
  1212. (funcInfo->bodyScope->GetIsObject() && !funcInfo->GetHasCachedScope()))
  1213. {
  1214. // If the current symbol is the duplicate arguments symbol created in the body for split
  1215. // scope then load undef only if the arguments symbol is used in the body.
  1216. if (!funcInfo->IsInnerArgumentsSymbol(sym) || funcInfo->GetHasArguments())
  1217. {
  1218. Js::RegSlot reg = sym->GetLocation();
  1219. if (reg == Js::Constants::NoRegister)
  1220. {
  1221. Assert(sym->IsInSlot(funcInfo));
  1222. reg = funcInfo->AcquireTmpRegister();
  1223. }
  1224. this->m_writer.Reg1(Js::OpCode::LdUndef, reg);
  1225. this->EmitLocalPropInit(reg, sym, funcInfo);
  1226. if (ShouldTrackDebuggerMetadata() && !sym->GetHasInit() && !sym->IsInSlot(funcInfo))
  1227. {
  1228. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), reg, funcInfo->varRegsCount);
  1229. }
  1230. funcInfo->ReleaseTmpRegister(reg);
  1231. }
  1232. }
  1233. }
  1234. else if (ShouldTrackDebuggerMetadata())
  1235. {
  1236. if (!sym->GetHasInit() && !sym->IsInSlot(funcInfo))
  1237. {
  1238. Js::RegSlot reg = sym->GetLocation();
  1239. if (reg != Js::Constants::NoRegister)
  1240. {
  1241. byteCodeFunction->InsertSymbolToRegSlotList(sym->GetName(), reg, funcInfo->varRegsCount);
  1242. }
  1243. }
  1244. }
  1245. sym->SetHasInit(TRUE);
  1246. }
  1247. }
  1248. }
  1249. if (tmpReg != Js::Constants::NoRegister)
  1250. {
  1251. funcInfo->ReleaseTmpRegister(tmpReg);
  1252. }
  1253. for (int i = 0; i < funcInfo->nonUserNonTempRegistersToInitialize.Count(); ++i)
  1254. {
  1255. m_writer.Reg1(Js::OpCode::LdUndef, funcInfo->nonUserNonTempRegistersToInitialize.Item(i));
  1256. }
  1257. }
  1258. void ByteCodeGenerator::InitBlockScopedNonTemps(ParseNode *pnode, FuncInfo *funcInfo)
  1259. {
  1260. // Initialize all non-temp register variables on entry to the enclosing func - in particular,
  1261. // those with lifetimes that begin after the start of user code and may not be initialized normally.
  1262. // This protects us from, for instance, trying to restore garbage on bailout.
  1263. // It was originally done in debugger mode only, but we do it always to avoid issues with boxing
  1264. // garbage on exit from jitted loop bodies.
  1265. while (pnode)
  1266. {
  1267. switch (pnode->nop)
  1268. {
  1269. case knopFncDecl:
  1270. {
  1271. // If this is a block-scoped function, initialize it.
  1272. ParseNode *pnodeName = pnode->sxFnc.pnodeName;
  1273. if (!pnode->sxFnc.IsMethod() && pnodeName && pnodeName->nop == knopVarDecl)
  1274. {
  1275. Symbol *sym = pnodeName->sxVar.sym;
  1276. Assert(sym);
  1277. if (sym->GetLocation() != Js::Constants::NoRegister &&
  1278. sym->GetScope()->IsBlockScope(funcInfo) &&
  1279. sym->GetScope()->GetFunc() == funcInfo)
  1280. {
  1281. this->m_writer.Reg1(Js::OpCode::LdUndef, sym->GetLocation());
  1282. }
  1283. }
  1284. // No need to recurse to the nested scopes, as they belong to a nested function.
  1285. pnode = pnode->sxFnc.pnodeNext;
  1286. break;
  1287. }
  1288. case knopBlock:
  1289. {
  1290. Scope *scope = pnode->sxBlock.scope;
  1291. if (scope)
  1292. {
  1293. if (scope->IsBlockScope(funcInfo))
  1294. {
  1295. Js::RegSlot scopeLoc = scope->GetLocation();
  1296. if (scopeLoc != Js::Constants::NoRegister && !funcInfo->IsTmpReg(scopeLoc))
  1297. {
  1298. this->m_writer.Reg1(Js::OpCode::LdUndef, scopeLoc);
  1299. }
  1300. }
  1301. auto fnInit = [this, funcInfo](ParseNode *pnode)
  1302. {
  1303. Symbol *sym = pnode->sxVar.sym;
  1304. if (!sym->IsInSlot(funcInfo) && !sym->GetIsGlobal() && !sym->GetIsModuleImport())
  1305. {
  1306. this->m_writer.Reg1(Js::OpCode::InitUndecl, pnode->sxVar.sym->GetLocation());
  1307. }
  1308. };
  1309. IterateBlockScopedVariables(pnode, fnInit);
  1310. }
  1311. InitBlockScopedNonTemps(pnode->sxBlock.pnodeScopes, funcInfo);
  1312. pnode = pnode->sxBlock.pnodeNext;
  1313. break;
  1314. }
  1315. case knopCatch:
  1316. InitBlockScopedNonTemps(pnode->sxCatch.pnodeScopes, funcInfo);
  1317. pnode = pnode->sxCatch.pnodeNext;
  1318. break;
  1319. case knopWith:
  1320. {
  1321. Js::RegSlot withLoc = pnode->location;
  1322. AssertMsg(withLoc != Js::Constants::NoRegister && !funcInfo->IsTmpReg(withLoc),
  1323. "We should put with objects at known stack locations in debug mode");
  1324. this->m_writer.Reg1(Js::OpCode::LdUndef, withLoc);
  1325. InitBlockScopedNonTemps(pnode->sxWith.pnodeScopes, funcInfo);
  1326. pnode = pnode->sxWith.pnodeNext;
  1327. break;
  1328. }
  1329. default:
  1330. Assert(false);
  1331. return;
  1332. }
  1333. }
  1334. }
  1335. void ByteCodeGenerator::EmitScopeObjectInit(FuncInfo *funcInfo)
  1336. {
  1337. Assert(!funcInfo->byteCodeFunction->GetFunctionBody()->DoStackNestedFunc());
  1338. if (!funcInfo->GetHasCachedScope() /* || forcing scope/inner func caching */)
  1339. {
  1340. return;
  1341. }
  1342. Scope* currentScope = funcInfo->GetCurrentChildScope();
  1343. uint slotCount = currentScope->GetScopeSlotCount();
  1344. uint cachedFuncCount = 0;
  1345. Js::PropertyId firstFuncSlot = Js::Constants::NoProperty;
  1346. Js::PropertyId firstVarSlot = Js::Constants::NoProperty;
  1347. uint extraAlloc = (slotCount + Js::ActivationObjectEx::ExtraSlotCount()) * sizeof(Js::PropertyId);
  1348. // Create and fill the array of local property ID's.
  1349. // They all have slots assigned to them already (if they need them): see StartEmitFunction.
  1350. Js::PropertyIdArray *propIds = funcInfo->GetParsedFunctionBody()->AllocatePropertyIdArrayForFormals(extraAlloc, slotCount, Js::ActivationObjectEx::ExtraSlotCount());
  1351. ParseNode *pnodeFnc = funcInfo->root;
  1352. ParseNode *pnode;
  1353. Symbol *sym;
  1354. if (funcInfo->GetFuncExprNameReference() && pnodeFnc->sxFnc.GetFuncSymbol()->GetScope() == funcInfo->GetBodyScope())
  1355. {
  1356. Symbol::SaveToPropIdArray(pnodeFnc->sxFnc.GetFuncSymbol(), propIds, this);
  1357. }
  1358. if (funcInfo->GetHasArguments())
  1359. {
  1360. // Because the arguments object can access all instances of same-named formals ("function(x,x){...}"),
  1361. // be sure we initialize any duplicate appearances of a formal parameter to "NoProperty".
  1362. Js::PropertyId slot = 0;
  1363. auto initArg = [&](ParseNode *pnode)
  1364. {
  1365. if (pnode->IsVarLetOrConst())
  1366. {
  1367. Symbol *sym = pnode->sxVar.sym;
  1368. Assert(sym);
  1369. if (sym->GetScopeSlot() == slot)
  1370. {
  1371. // This is the last appearance of the formal, so record the ID.
  1372. Symbol::SaveToPropIdArray(sym, propIds, this);
  1373. }
  1374. else
  1375. {
  1376. // This is an earlier duplicate appearance of the formal, so use NoProperty as a placeholder
  1377. // since this slot can't be accessed by name.
  1378. Assert(sym->GetScopeSlot() != Js::Constants::NoProperty && sym->GetScopeSlot() > slot);
  1379. propIds->elements[slot] = Js::Constants::NoProperty;
  1380. }
  1381. }
  1382. else
  1383. {
  1384. // This is for patterns
  1385. propIds->elements[slot] = Js::Constants::NoProperty;
  1386. }
  1387. slot++;
  1388. };
  1389. MapFormalsWithoutRest(pnodeFnc, initArg);
  1390. // If the rest is in the slot - we need to keep that slot.
  1391. if (pnodeFnc->sxFnc.pnodeRest != nullptr && pnodeFnc->sxFnc.pnodeRest->sxVar.sym->IsInSlot(funcInfo))
  1392. {
  1393. Symbol::SaveToPropIdArray(pnodeFnc->sxFnc.pnodeRest->sxVar.sym, propIds, this);
  1394. }
  1395. }
  1396. else
  1397. {
  1398. MapFormals(pnodeFnc, [&](ParseNode *pnode)
  1399. {
  1400. if (pnode->IsVarLetOrConst())
  1401. {
  1402. Symbol::SaveToPropIdArray(pnode->sxVar.sym, propIds, this);
  1403. }
  1404. });
  1405. }
  1406. auto saveFunctionVarsToPropIdArray = [&](ParseNode *pnodeFunction)
  1407. {
  1408. if (pnodeFunction->sxFnc.IsDeclaration())
  1409. {
  1410. ParseNode *pnodeName = pnodeFunction->sxFnc.pnodeName;
  1411. if (pnodeName != nullptr)
  1412. {
  1413. while (pnodeName->nop == knopList)
  1414. {
  1415. if (pnodeName->sxBin.pnode1->nop == knopVarDecl)
  1416. {
  1417. sym = pnodeName->sxBin.pnode1->sxVar.sym;
  1418. if (sym)
  1419. {
  1420. Symbol::SaveToPropIdArray(sym, propIds, this, &firstFuncSlot);
  1421. }
  1422. }
  1423. pnodeName = pnodeName->sxBin.pnode2;
  1424. }
  1425. if (pnodeName->nop == knopVarDecl)
  1426. {
  1427. sym = pnodeName->sxVar.sym;
  1428. if (sym)
  1429. {
  1430. Symbol::SaveToPropIdArray(sym, propIds, this, &firstFuncSlot);
  1431. cachedFuncCount++;
  1432. }
  1433. }
  1434. }
  1435. }
  1436. };
  1437. MapContainerScopeFunctions(pnodeFnc, saveFunctionVarsToPropIdArray);
  1438. if (currentScope->GetScopeType() != ScopeType_Parameter)
  1439. {
  1440. for (pnode = pnodeFnc->sxFnc.pnodeVars; pnode; pnode = pnode->sxVar.pnodeNext)
  1441. {
  1442. sym = pnode->sxVar.sym;
  1443. if (!(pnode->sxVar.isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  1444. {
  1445. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  1446. {
  1447. sym = currentScope->FindLocalSymbol(sym->GetName());
  1448. }
  1449. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1450. }
  1451. }
  1452. ParseNode *pnodeBlock = pnodeFnc->sxFnc.pnodeScopes;
  1453. for (pnode = pnodeBlock->sxBlock.pnodeLexVars; pnode; pnode = pnode->sxVar.pnodeNext)
  1454. {
  1455. sym = pnode->sxVar.sym;
  1456. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1457. }
  1458. pnodeBlock = pnodeFnc->sxFnc.pnodeBodyScope;
  1459. for (pnode = pnodeBlock->sxBlock.pnodeLexVars; pnode; pnode = pnode->sxVar.pnodeNext)
  1460. {
  1461. sym = pnode->sxVar.sym;
  1462. Symbol::SaveToPropIdArray(sym, propIds, this, &firstVarSlot);
  1463. }
  1464. }
  1465. else
  1466. {
  1467. Assert(!currentScope->GetCanMergeWithBodyScope());
  1468. }
  1469. if (funcInfo->thisScopeSlot != Js::Constants::NoRegister)
  1470. {
  1471. propIds->elements[funcInfo->thisScopeSlot] = Js::PropertyIds::_lexicalThisSlotSymbol;
  1472. }
  1473. if (funcInfo->newTargetScopeSlot != Js::Constants::NoRegister)
  1474. {
  1475. propIds->elements[funcInfo->newTargetScopeSlot] = Js::PropertyIds::_lexicalNewTargetSymbol;
  1476. }
  1477. if (funcInfo->superScopeSlot != Js::Constants::NoRegister)
  1478. {
  1479. propIds->elements[funcInfo->superScopeSlot] = Js::PropertyIds::_superReferenceSymbol;
  1480. }
  1481. if (funcInfo->superCtorScopeSlot != Js::Constants::NoRegister)
  1482. {
  1483. propIds->elements[funcInfo->superCtorScopeSlot] = Js::PropertyIds::_superCtorReferenceSymbol;
  1484. }
  1485. // Write the first func slot and first var slot into the auxiliary data
  1486. Js::PropertyId *slots = propIds->elements + slotCount;
  1487. slots[0] = cachedFuncCount;
  1488. slots[1] = firstFuncSlot;
  1489. slots[2] = firstVarSlot;
  1490. slots[3] = funcInfo->GetParsedFunctionBody()->NewObjectLiteral();
  1491. propIds->hasNonSimpleParams = funcInfo->root->sxFnc.HasNonSimpleParameterList();
  1492. funcInfo->GetParsedFunctionBody()->SetHasCachedScopePropIds(true);
  1493. }
  1494. void ByteCodeGenerator::SetClosureRegisters(FuncInfo* funcInfo, Js::FunctionBody* byteCodeFunction)
  1495. {
  1496. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  1497. {
  1498. byteCodeFunction->MapAndSetLocalFrameDisplayRegister(funcInfo->frameDisplayRegister);
  1499. }
  1500. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  1501. {
  1502. byteCodeFunction->MapAndSetLocalClosureRegister(funcInfo->frameObjRegister);
  1503. byteCodeFunction->SetHasScopeObject(true);
  1504. }
  1505. else if (funcInfo->frameSlotsRegister != Js::Constants::NoRegister)
  1506. {
  1507. byteCodeFunction->MapAndSetLocalClosureRegister(funcInfo->frameSlotsRegister);
  1508. }
  1509. if (funcInfo->paramSlotsRegister != Js::Constants::NoRegister)
  1510. {
  1511. byteCodeFunction->MapAndSetParamClosureRegister(funcInfo->paramSlotsRegister);
  1512. }
  1513. }
  1514. void ByteCodeGenerator::FinalizeRegisters(FuncInfo * funcInfo, Js::FunctionBody * byteCodeFunction)
  1515. {
  1516. if (byteCodeFunction->IsCoroutine())
  1517. {
  1518. // EmitYield uses 'false' to create the IteratorResult object
  1519. funcInfo->AssignFalseConstRegister();
  1520. }
  1521. if (funcInfo->NeedEnvRegister())
  1522. {
  1523. bool constReg = !funcInfo->GetIsTopLevelEventHandler() && funcInfo->IsGlobalFunction() && !(this->flags & fscrEval);
  1524. funcInfo->AssignEnvRegister(constReg);
  1525. }
  1526. // Set the function body's constant count before emitting anything so that the byte code writer
  1527. // can distinguish constants from variables.
  1528. byteCodeFunction->CheckAndSetConstantCount(funcInfo->constRegsCount);
  1529. this->SetClosureRegisters(funcInfo, byteCodeFunction);
  1530. if (this->IsInDebugMode())
  1531. {
  1532. // Give permanent registers to the inner scopes in debug mode.
  1533. uint innerScopeCount = funcInfo->InnerScopeCount();
  1534. byteCodeFunction->SetInnerScopeCount(innerScopeCount);
  1535. if (innerScopeCount)
  1536. {
  1537. funcInfo->SetFirstInnerScopeReg(funcInfo->NextVarRegister());
  1538. for (uint i = 1; i < innerScopeCount; i++)
  1539. {
  1540. funcInfo->NextVarRegister();
  1541. }
  1542. }
  1543. }
  1544. // NOTE: The FB expects the yield reg to be the final non-temp.
  1545. if (byteCodeFunction->IsCoroutine())
  1546. {
  1547. funcInfo->AssignYieldRegister();
  1548. }
  1549. Js::RegSlot firstTmpReg = funcInfo->varRegsCount;
  1550. funcInfo->SetFirstTmpReg(firstTmpReg);
  1551. byteCodeFunction->SetFirstTmpReg(funcInfo->RegCount());
  1552. }
  1553. void ByteCodeGenerator::InitScopeSlotArray(FuncInfo * funcInfo)
  1554. {
  1555. // Record slots info for ScopeSlots/ScopeObject.
  1556. uint scopeSlotCount = funcInfo->bodyScope->GetScopeSlotCount();
  1557. Assert(funcInfo->paramScope == nullptr || funcInfo->paramScope->GetScopeSlotCount() == 0 || !funcInfo->paramScope->GetCanMergeWithBodyScope());
  1558. uint scopeSlotCountForParamScope = funcInfo->paramScope != nullptr ? funcInfo->paramScope->GetScopeSlotCount() : 0;
  1559. if (scopeSlotCount == 0 && scopeSlotCountForParamScope == 0)
  1560. {
  1561. return;
  1562. }
  1563. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1564. if (scopeSlotCount > 0 || scopeSlotCountForParamScope > 0)
  1565. {
  1566. byteCodeFunction->SetScopeSlotArraySizes(scopeSlotCount, scopeSlotCountForParamScope);
  1567. }
  1568. // TODO: Need to add property ids for the case when scopeSlotCountForParamSCope is non-zero
  1569. if (scopeSlotCount)
  1570. {
  1571. Js::PropertyId *propertyIdsForScopeSlotArray = RecyclerNewArrayLeafZ(scriptContext->GetRecycler(), Js::PropertyId, scopeSlotCount);
  1572. byteCodeFunction->SetPropertyIdsForScopeSlotArray(propertyIdsForScopeSlotArray, scopeSlotCount, scopeSlotCountForParamScope);
  1573. AssertMsg(!byteCodeFunction->IsReparsed() || byteCodeFunction->m_wasEverAsmjsMode || byteCodeFunction->scopeSlotArraySize == scopeSlotCount,
  1574. "The slot array size is different between debug and non-debug mode");
  1575. #if DEBUG
  1576. for (UINT i = 0; i < scopeSlotCount; i++)
  1577. {
  1578. propertyIdsForScopeSlotArray[i] = Js::Constants::NoProperty;
  1579. }
  1580. #endif
  1581. auto setPropertyIdForScopeSlotArray =
  1582. [scopeSlotCount, propertyIdsForScopeSlotArray]
  1583. (Js::PropertyId slot, Js::PropertyId propId)
  1584. {
  1585. if (slot < 0 || (uint)slot >= scopeSlotCount)
  1586. {
  1587. Js::Throw::FatalInternalError();
  1588. }
  1589. propertyIdsForScopeSlotArray[slot] = propId;
  1590. };
  1591. auto setPropIdsForScopeSlotArray = [funcInfo, setPropertyIdForScopeSlotArray](Symbol *const sym)
  1592. {
  1593. if (sym->NeedsSlotAlloc(funcInfo))
  1594. {
  1595. if (funcInfo->IsInnerArgumentsSymbol(sym) && !funcInfo->GetHasArguments())
  1596. {
  1597. // In split scope case we have a duplicate symbol for arguments in the body (innerArgumentsSymbol).
  1598. // But if arguments is not referenced in the body we don't have to allocate scope slot for it.
  1599. // If we allocate one, then the debugger will assume that the arguments symbol is there and skip creating the fake one.
  1600. }
  1601. else
  1602. {
  1603. // All properties should get correct propertyId here.
  1604. Assert(sym->HasScopeSlot()); // We can't allocate scope slot now. Any symbol needing scope slot must have allocated it before this point.
  1605. setPropertyIdForScopeSlotArray(sym->GetScopeSlot(), sym->EnsurePosition(funcInfo));
  1606. }
  1607. }
  1608. };
  1609. funcInfo->GetBodyScope()->ForEachSymbol(setPropIdsForScopeSlotArray);
  1610. if (funcInfo->thisScopeSlot != Js::Constants::NoRegister)
  1611. {
  1612. setPropertyIdForScopeSlotArray(funcInfo->thisScopeSlot, Js::PropertyIds::_lexicalThisSlotSymbol);
  1613. }
  1614. if (funcInfo->newTargetScopeSlot != Js::Constants::NoRegister)
  1615. {
  1616. setPropertyIdForScopeSlotArray(funcInfo->newTargetScopeSlot, Js::PropertyIds::_lexicalNewTargetSymbol);
  1617. }
  1618. if (funcInfo->superScopeSlot != Js::Constants::NoRegister)
  1619. {
  1620. setPropertyIdForScopeSlotArray(funcInfo->superScopeSlot, Js::PropertyIds::_superReferenceSymbol);
  1621. }
  1622. if (funcInfo->superCtorScopeSlot != Js::Constants::NoRegister)
  1623. {
  1624. setPropertyIdForScopeSlotArray(funcInfo->superCtorScopeSlot, Js::PropertyIds::_superCtorReferenceSymbol);
  1625. }
  1626. #if DEBUG
  1627. for (UINT i = 0; i < scopeSlotCount; i++)
  1628. {
  1629. Assert(propertyIdsForScopeSlotArray[i] != Js::Constants::NoProperty
  1630. || funcInfo->frameObjRegister != Js::Constants::NoRegister); // ScopeObject may have unassigned entries, e.g. for same-named parameters
  1631. }
  1632. #endif
  1633. }
  1634. }
  1635. // temporarily load all constants and special registers in a single block
  1636. void ByteCodeGenerator::LoadAllConstants(FuncInfo *funcInfo)
  1637. {
  1638. Symbol *sym;
  1639. Js::FunctionBody *byteCodeFunction = funcInfo->GetParsedFunctionBody();
  1640. byteCodeFunction->CreateConstantTable();
  1641. if (funcInfo->nullConstantRegister != Js::Constants::NoRegister)
  1642. {
  1643. byteCodeFunction->RecordNullObject(byteCodeFunction->MapRegSlot(funcInfo->nullConstantRegister));
  1644. }
  1645. if (funcInfo->undefinedConstantRegister != Js::Constants::NoRegister)
  1646. {
  1647. byteCodeFunction->RecordUndefinedObject(byteCodeFunction->MapRegSlot(funcInfo->undefinedConstantRegister));
  1648. }
  1649. if (funcInfo->trueConstantRegister != Js::Constants::NoRegister)
  1650. {
  1651. byteCodeFunction->RecordTrueObject(byteCodeFunction->MapRegSlot(funcInfo->trueConstantRegister));
  1652. }
  1653. if (funcInfo->falseConstantRegister != Js::Constants::NoRegister)
  1654. {
  1655. byteCodeFunction->RecordFalseObject(byteCodeFunction->MapRegSlot(funcInfo->falseConstantRegister));
  1656. }
  1657. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  1658. {
  1659. m_writer.RecordObjectRegister(funcInfo->frameObjRegister);
  1660. if (!funcInfo->GetApplyEnclosesArgs())
  1661. {
  1662. this->EmitScopeObjectInit(funcInfo);
  1663. }
  1664. #if DBG
  1665. uint count = 0;
  1666. funcInfo->GetBodyScope()->ForEachSymbol([&](Symbol *const sym)
  1667. {
  1668. if (sym->NeedsSlotAlloc(funcInfo))
  1669. {
  1670. // All properties should get correct propertyId here.
  1671. count++;
  1672. }
  1673. });
  1674. if (funcInfo->GetParamScope() != nullptr)
  1675. {
  1676. funcInfo->GetParamScope()->ForEachSymbol([&](Symbol *const sym)
  1677. {
  1678. if (sym->NeedsSlotAlloc(funcInfo))
  1679. {
  1680. // All properties should get correct propertyId here.
  1681. count++;
  1682. }
  1683. });
  1684. }
  1685. // A reparse should result in the same size of the activation object.
  1686. // Exclude functions which were created from the ByteCodeCache.
  1687. AssertMsg(!byteCodeFunction->IsReparsed() || byteCodeFunction->HasGeneratedFromByteCodeCache() ||
  1688. byteCodeFunction->scopeObjectSize == count || byteCodeFunction->m_wasEverAsmjsMode,
  1689. "The activation object size is different between debug and non-debug mode");
  1690. byteCodeFunction->scopeObjectSize = count;
  1691. #endif
  1692. }
  1693. else if (funcInfo->frameSlotsRegister != Js::Constants::NoRegister)
  1694. {
  1695. int scopeSlotCount = funcInfo->bodyScope->GetScopeSlotCount();
  1696. int paramSlotCount = funcInfo->paramScope->GetScopeSlotCount();
  1697. if (scopeSlotCount == 0 && paramSlotCount == 0)
  1698. {
  1699. AssertMsg(funcInfo->frameDisplayRegister != Js::Constants::NoRegister, "Why do we need scope slots?");
  1700. m_writer.Reg1(Js::OpCode::LdC_A_Null, funcInfo->frameSlotsRegister);
  1701. }
  1702. }
  1703. if (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject())
  1704. {
  1705. byteCodeFunction->MapAndSetFuncExprScopeRegister(funcInfo->funcExprScope->GetLocation());
  1706. byteCodeFunction->SetEnvDepth((uint16)-1);
  1707. }
  1708. bool thisLoadedFromParams = false;
  1709. if (funcInfo->NeedEnvRegister())
  1710. {
  1711. byteCodeFunction->MapAndSetEnvRegister(funcInfo->GetEnvRegister());
  1712. if (funcInfo->GetIsTopLevelEventHandler())
  1713. {
  1714. byteCodeFunction->MapAndSetThisRegisterForEventHandler(funcInfo->thisPointerRegister);
  1715. // The environment is the namespace hierarchy starting with "this".
  1716. Assert(!funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1717. thisLoadedFromParams = true;
  1718. this->InvalidateCachedOuterScopes(funcInfo);
  1719. }
  1720. else if (funcInfo->IsGlobalFunction() && !(this->flags & fscrEval))
  1721. {
  1722. Assert(funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1723. if (funcInfo->GetIsStrictMode())
  1724. {
  1725. byteCodeFunction->RecordStrictNullDisplayConstant(byteCodeFunction->MapRegSlot(funcInfo->GetEnvRegister()));
  1726. }
  1727. else
  1728. {
  1729. byteCodeFunction->RecordNullDisplayConstant(byteCodeFunction->MapRegSlot(funcInfo->GetEnvRegister()));
  1730. }
  1731. }
  1732. else
  1733. {
  1734. // environment may be required to load "this"
  1735. Assert(!funcInfo->RegIsConst(funcInfo->GetEnvRegister()));
  1736. this->InvalidateCachedOuterScopes(funcInfo);
  1737. }
  1738. }
  1739. if (funcInfo->frameDisplayRegister != Js::Constants::NoRegister)
  1740. {
  1741. m_writer.RecordFrameDisplayRegister(funcInfo->frameDisplayRegister);
  1742. }
  1743. // new.target may be used to construct the 'this' register so make sure to load it first
  1744. if (funcInfo->newTargetRegister != Js::Constants::NoRegister)
  1745. {
  1746. this->LoadNewTargetObject(funcInfo);
  1747. }
  1748. if (funcInfo->thisPointerRegister != Js::Constants::NoRegister)
  1749. {
  1750. this->LoadThisObject(funcInfo, thisLoadedFromParams);
  1751. }
  1752. this->RecordAllIntConstants(funcInfo);
  1753. this->RecordAllStrConstants(funcInfo);
  1754. this->RecordAllStringTemplateCallsiteConstants(funcInfo);
  1755. funcInfo->doubleConstantToRegister.Map([byteCodeFunction](double d, Js::RegSlot location)
  1756. {
  1757. byteCodeFunction->RecordFloatConstant(byteCodeFunction->MapRegSlot(location), d);
  1758. });
  1759. if (funcInfo->GetHasArguments())
  1760. {
  1761. sym = funcInfo->GetArgumentsSymbol();
  1762. Assert(sym);
  1763. Assert(funcInfo->GetHasHeapArguments());
  1764. if (funcInfo->GetCallsEval() || (!funcInfo->GetApplyEnclosesArgs()))
  1765. {
  1766. this->LoadHeapArguments(funcInfo);
  1767. }
  1768. }
  1769. else if (!funcInfo->IsGlobalFunction() && !IsInNonDebugMode())
  1770. {
  1771. uint count = funcInfo->inArgsCount + (funcInfo->root->sxFnc.pnodeRest != nullptr ? 1 : 0) - 1;
  1772. if (count != 0)
  1773. {
  1774. Js::PropertyIdArray *propIds = RecyclerNewPlus(scriptContext->GetRecycler(), count * sizeof(Js::PropertyId), Js::PropertyIdArray, count, 0);
  1775. GetFormalArgsArray(this, funcInfo, propIds);
  1776. byteCodeFunction->SetPropertyIdsOfFormals(propIds);
  1777. }
  1778. }
  1779. //
  1780. // If the function is a function expression with a name,
  1781. // load the function object at runtime to its activation object.
  1782. //
  1783. sym = funcInfo->root->sxFnc.GetFuncSymbol();
  1784. bool funcExprWithName = !funcInfo->IsGlobalFunction() && sym && sym->GetIsFuncExpr();
  1785. if (funcExprWithName)
  1786. {
  1787. if (funcInfo->GetFuncExprNameReference() ||
  1788. (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject()))
  1789. {
  1790. //
  1791. // x = function f(...) { ... }
  1792. // A named function expression's name (Symbol:f) belongs to the enclosing scope.
  1793. // Thus there are no uses of 'f' within the scope of the function (as references to 'f'
  1794. // are looked up in the closure). So, we can't use f's register as it is from the enclosing
  1795. // scope's register namespace. So use a tmp register.
  1796. // In ES5 mode though 'f' is *not* a part of the enclosing scope. So we always assign 'f' a register
  1797. // from it's register namespace, which LdFuncExpr can use.
  1798. //
  1799. Js::RegSlot ldFuncExprDst = sym->GetLocation();
  1800. this->m_writer.Reg1(Js::OpCode::LdFuncExpr, ldFuncExprDst);
  1801. if (sym->IsInSlot(funcInfo))
  1802. {
  1803. Js::RegSlot scopeLocation;
  1804. AnalysisAssert(funcInfo->funcExprScope);
  1805. if (funcInfo->funcExprScope->GetIsObject())
  1806. {
  1807. scopeLocation = funcInfo->funcExprScope->GetLocation();
  1808. this->m_writer.Property(Js::OpCode::StFuncExpr, sym->GetLocation(), scopeLocation,
  1809. funcInfo->FindOrAddReferencedPropertyId(sym->GetPosition()));
  1810. }
  1811. else if (funcInfo->bodyScope->GetIsObject())
  1812. {
  1813. this->m_writer.ElementU(Js::OpCode::StLocalFuncExpr, sym->GetLocation(),
  1814. funcInfo->FindOrAddReferencedPropertyId(sym->GetPosition()));
  1815. }
  1816. else
  1817. {
  1818. Assert(sym->HasScopeSlot());
  1819. this->m_writer.SlotI1(Js::OpCode::StLocalSlot, sym->GetLocation(),
  1820. sym->GetScopeSlot() + Js::ScopeSlots::FirstSlotIndex);
  1821. }
  1822. }
  1823. else if (ShouldTrackDebuggerMetadata())
  1824. {
  1825. funcInfo->byteCodeFunction->GetFunctionBody()->InsertSymbolToRegSlotList(sym->GetName(), sym->GetLocation(), funcInfo->varRegsCount);
  1826. }
  1827. }
  1828. }
  1829. }
  1830. void ByteCodeGenerator::InvalidateCachedOuterScopes(FuncInfo *funcInfo)
  1831. {
  1832. Assert(funcInfo->GetEnvRegister() != Js::Constants::NoRegister);
  1833. // Walk the scope stack, from funcInfo outward, looking for scopes that have been cached.
  1834. Scope *scope = funcInfo->GetBodyScope()->GetEnclosingScope();
  1835. uint32 envIndex = 0;
  1836. while (scope && scope->GetFunc() == funcInfo)
  1837. {
  1838. // Skip over FuncExpr Scope and parameter scope for current funcInfo to get to the first enclosing scope of the outer function.
  1839. scope = scope->GetEnclosingScope();
  1840. }
  1841. for (; scope; scope = scope->GetEnclosingScope())
  1842. {
  1843. FuncInfo *func = scope->GetFunc();
  1844. if (scope == func->GetBodyScope())
  1845. {
  1846. if (func->Escapes() && func->GetHasCachedScope())
  1847. {
  1848. Assert(scope->GetIsObject());
  1849. this->m_writer.Unsigned1(Js::OpCode::InvalCachedScope, envIndex);
  1850. }
  1851. }
  1852. if (scope->GetMustInstantiate())
  1853. {
  1854. envIndex++;
  1855. }
  1856. }
  1857. }
  1858. void ByteCodeGenerator::LoadThisObject(FuncInfo *funcInfo, bool thisLoadedFromParams)
  1859. {
  1860. if (this->scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled() && funcInfo->IsClassConstructor())
  1861. {
  1862. // Derived class constructors initialize 'this' to be Undecl except "extends null" cases
  1863. // - we'll check this value during a super call and during 'this' access
  1864. //
  1865. // Base class constructors or "extends null" cases initialize 'this' to a new object using new.target
  1866. if (funcInfo->IsBaseClassConstructor())
  1867. {
  1868. EmitBaseClassConstructorThisObject(funcInfo);
  1869. }
  1870. else
  1871. {
  1872. Js::ByteCodeLabel thisLabel = this->Writer()->DefineLabel();
  1873. Js::ByteCodeLabel skipLabel = this->Writer()->DefineLabel();
  1874. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  1875. this->Writer()->Reg1(Js::OpCode::LdFuncObj, tmpReg);
  1876. this->Writer()->BrReg1(Js::OpCode::BrOnBaseConstructorKind, thisLabel, tmpReg); // branch when [[ConstructorKind]]=="base"
  1877. funcInfo->ReleaseTmpRegister(tmpReg);
  1878. this->m_writer.Reg1(Js::OpCode::InitUndecl, funcInfo->thisPointerRegister); // not "extends null" case
  1879. this->Writer()->Br(Js::OpCode::Br, skipLabel);
  1880. this->Writer()->MarkLabel(thisLabel);
  1881. EmitBaseClassConstructorThisObject(funcInfo); // "extends null" case
  1882. this->Writer()->MarkLabel(skipLabel);
  1883. }
  1884. }
  1885. else if (!funcInfo->IsGlobalFunction() || (this->flags & fscrEval))
  1886. {
  1887. //
  1888. // thisLoadedFromParams would be true for the event Handler case,
  1889. // "this" would have been loaded from parameters to put in the environment
  1890. //
  1891. if (!thisLoadedFromParams && !funcInfo->IsLambda())
  1892. {
  1893. m_writer.ArgIn0(funcInfo->thisPointerRegister);
  1894. }
  1895. if (!(this->flags & fscrEval) || !funcInfo->IsGlobalFunction())
  1896. {
  1897. // we don't want to emit 'this' for eval, because 'this' value in eval is equal to 'this' value of caller
  1898. // and does not depend on "use strict" inside of eval.
  1899. // so we pass 'this' directly in GlobalObject::EntryEval()
  1900. EmitThis(funcInfo, funcInfo->thisPointerRegister);
  1901. }
  1902. }
  1903. else
  1904. {
  1905. Assert(funcInfo->IsGlobalFunction());
  1906. Js::RegSlot root = funcInfo->nullConstantRegister;
  1907. EmitThis(funcInfo, root);
  1908. }
  1909. }
  1910. void ByteCodeGenerator::LoadNewTargetObject(FuncInfo *funcInfo)
  1911. {
  1912. if (funcInfo->IsClassConstructor())
  1913. {
  1914. Assert(!funcInfo->IsLambda());
  1915. m_writer.ArgIn0(funcInfo->newTargetRegister);
  1916. }
  1917. else if (funcInfo->IsLambda() && !(this->flags & fscrEval))
  1918. {
  1919. Scope *scope;
  1920. Js::PropertyId envIndex = -1;
  1921. GetEnclosingNonLambdaScope(funcInfo, scope, envIndex);
  1922. if (scope->GetFunc()->IsGlobalFunction())
  1923. {
  1924. m_writer.Reg1(Js::OpCode::LdUndef, funcInfo->newTargetRegister);
  1925. }
  1926. else
  1927. {
  1928. Js::PropertyId slot = scope->GetFunc()->newTargetScopeSlot;
  1929. EmitInternalScopedSlotLoad(funcInfo, scope, envIndex, slot, funcInfo->newTargetRegister);
  1930. }
  1931. }
  1932. else if ((funcInfo->IsGlobalFunction() || funcInfo->IsLambda()) && (this->flags & fscrEval))
  1933. {
  1934. Js::RegSlot scopeLocation;
  1935. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  1936. {
  1937. scopeLocation = funcInfo->frameDisplayRegister;
  1938. }
  1939. else if (funcInfo->NeedEnvRegister())
  1940. {
  1941. scopeLocation = funcInfo->GetEnvRegister();
  1942. }
  1943. else
  1944. {
  1945. // If this eval doesn't have environment register or frame display register, we didn't capture anything from a class constructor.
  1946. m_writer.Reg1(Js::OpCode::LdNewTarget, funcInfo->newTargetRegister);
  1947. return;
  1948. }
  1949. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, Js::PropertyIds::_lexicalNewTargetSymbol, false, false);
  1950. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, funcInfo->newTargetRegister, cacheId);
  1951. }
  1952. else if (funcInfo->IsGlobalFunction())
  1953. {
  1954. m_writer.Reg1(Js::OpCode::LdUndef, funcInfo->newTargetRegister);
  1955. }
  1956. else
  1957. {
  1958. m_writer.Reg1(Js::OpCode::LdNewTarget, funcInfo->newTargetRegister);
  1959. }
  1960. }
  1961. void ByteCodeGenerator::EmitScopeSlotLoadThis(FuncInfo *funcInfo, Js::RegSlot regLoc, bool chkUndecl)
  1962. {
  1963. FuncInfo* nonLambdaFunc = funcInfo;
  1964. if (funcInfo->IsLambda())
  1965. {
  1966. nonLambdaFunc = FindEnclosingNonLambda();
  1967. }
  1968. if (nonLambdaFunc->IsClassConstructor() && !nonLambdaFunc->IsBaseClassConstructor())
  1969. {
  1970. // If we are in a derived class constructor and we have a scope slot for 'this',
  1971. // we need to load 'this' from the scope slot. This is to support the case where
  1972. // the call to initialize 'this' via super() is inside a lambda since the lambda
  1973. // can't assign to the 'this' register of the parent constructor.
  1974. if (nonLambdaFunc->thisScopeSlot != Js::Constants::NoRegister)
  1975. {
  1976. Js::PropertyId slot = nonLambdaFunc->thisScopeSlot;
  1977. EmitInternalScopedSlotLoad(funcInfo, slot, regLoc, chkUndecl);
  1978. }
  1979. else if (funcInfo->thisPointerRegister != Js::Constants::NoRegister && chkUndecl)
  1980. {
  1981. this->m_writer.Reg1(Js::OpCode::ChkUndecl, funcInfo->thisPointerRegister);
  1982. }
  1983. else if (chkUndecl)
  1984. {
  1985. // If we don't have a scope slot for 'this' we know that super could not have
  1986. // been called inside a lambda so we can check to see if we called
  1987. // super and assigned to the this register already. If not, this should trigger
  1988. // a ReferenceError.
  1989. EmitUseBeforeDeclarationRuntimeError(this, Js::Constants::NoRegister);
  1990. }
  1991. }
  1992. else if (this->flags & fscrEval && (funcInfo->IsGlobalFunction() || (funcInfo->IsLambda() && nonLambdaFunc->IsGlobalFunction()))
  1993. && funcInfo->GetBodyScope()->GetIsObject())
  1994. {
  1995. Js::RegSlot scopeLocation;
  1996. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  1997. {
  1998. scopeLocation = funcInfo->frameDisplayRegister;
  1999. }
  2000. else if (funcInfo->NeedEnvRegister())
  2001. {
  2002. scopeLocation = funcInfo->GetEnvRegister();
  2003. }
  2004. else
  2005. {
  2006. // If this eval doesn't have environment register or frame display register, we didn't capture anything from a class constructor
  2007. return;
  2008. }
  2009. // CONSIDER [tawoll] - Should we add a ByteCodeGenerator flag (fscrEvalWithClassConstructorParent) and avoid doing this runtime check?
  2010. Js::ByteCodeLabel skipLabel = this->Writer()->DefineLabel();
  2011. this->Writer()->BrReg1(Js::OpCode::BrNotUndecl_A, skipLabel, funcInfo->thisPointerRegister);
  2012. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, Js::PropertyIds::_lexicalThisSlotSymbol, false, false);
  2013. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, funcInfo->thisPointerRegister, cacheId);
  2014. if (chkUndecl)
  2015. {
  2016. this->m_writer.Reg1(Js::OpCode::ChkUndecl, funcInfo->thisPointerRegister);
  2017. }
  2018. this->Writer()->MarkLabel(skipLabel);
  2019. }
  2020. }
  2021. void ByteCodeGenerator::EmitScopeSlotStoreThis(FuncInfo *funcInfo, Js::RegSlot regLoc, bool chkUndecl)
  2022. {
  2023. if (this->flags & fscrEval && (funcInfo->IsGlobalFunction() || (funcInfo->IsLambda() && FindEnclosingNonLambda()->IsGlobalFunction())))
  2024. {
  2025. Js::RegSlot scopeLocation;
  2026. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  2027. {
  2028. scopeLocation = funcInfo->frameDisplayRegister;
  2029. }
  2030. else
  2031. {
  2032. scopeLocation = funcInfo->GetEnvRegister();
  2033. }
  2034. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, Js::PropertyIds::_lexicalThisSlotSymbol, false, true);
  2035. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo->byteCodeFunction->GetIsStrictMode()), funcInfo->thisPointerRegister, cacheId);
  2036. }
  2037. else if (regLoc != Js::Constants::NoRegister)
  2038. {
  2039. EmitInternalScopedSlotStore(funcInfo, regLoc, funcInfo->thisPointerRegister);
  2040. }
  2041. }
  2042. void ByteCodeGenerator::EmitSuperCall(FuncInfo* funcInfo, ParseNode* pnode, BOOL fReturnValue)
  2043. {
  2044. Assert(pnode->sxCall.pnodeTarget->nop == knopSuper);
  2045. FuncInfo* nonLambdaFunc = funcInfo;
  2046. if (funcInfo->IsLambda())
  2047. {
  2048. nonLambdaFunc = this->FindEnclosingNonLambda();
  2049. }
  2050. if (nonLambdaFunc->IsBaseClassConstructor())
  2051. {
  2052. // super() is not allowed in base class constructors. If we detect this, emit a ReferenceError and skip making the call.
  2053. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_ClassSuperInBaseClass));
  2054. return;
  2055. }
  2056. else
  2057. {
  2058. EmitSuperFieldPatch(funcInfo, pnode, this);
  2059. pnode->isUsed = true;
  2060. }
  2061. // We already know pnode->sxCall.pnodeTarget->nop is super but we can't use the super register in case
  2062. // this is an eval and we will load super dynamically from the scope using ScopedLdHomeObj.
  2063. // That means we'll have to rely on the location of the call target to be sure.
  2064. // We have to make sure to allocate the location for the node now, before we try to branch on it.
  2065. Emit(pnode->sxCall.pnodeTarget, this, funcInfo, false, /*isConstructorCall*/ true); // reuse isConstructorCall ("new super()" is illegal)
  2066. //
  2067. // if (super is class constructor) {
  2068. // _this = new.target;
  2069. // } else {
  2070. // _this = NewScObjFull(new.target);
  2071. // }
  2072. //
  2073. // temp = super.call(_this, new.target); // CallFlag_New | CallFlag_NewTarget | CallFlag_ExtraArg
  2074. // if (temp is object) {
  2075. // _this = temp;
  2076. // }
  2077. //
  2078. // if (UndeclBlockVar === this) {
  2079. // this = _this;
  2080. // } else {
  2081. // throw ReferenceError;
  2082. // }
  2083. //
  2084. funcInfo->AcquireLoc(pnode);
  2085. Js::RegSlot thisForSuperCall = funcInfo->AcquireTmpRegister();
  2086. Js::ByteCodeLabel useNewTargetForThisLabel = this->Writer()->DefineLabel();
  2087. Js::ByteCodeLabel makeCallLabel = this->Writer()->DefineLabel();
  2088. Js::ByteCodeLabel useSuperCallResultLabel = this->Writer()->DefineLabel();
  2089. Js::ByteCodeLabel doneLabel = this->Writer()->DefineLabel();
  2090. Js::RegSlot tmpReg = this->EmitLdObjProto(Js::OpCode::LdFuncObjProto, pnode->sxCall.pnodeTarget->location, funcInfo);
  2091. this->Writer()->BrReg1(Js::OpCode::BrOnClassConstructor, useNewTargetForThisLabel, tmpReg);
  2092. this->Writer()->Reg2(Js::OpCode::NewScObjectNoCtorFull, thisForSuperCall, funcInfo->newTargetRegister);
  2093. this->Writer()->Br(Js::OpCode::Br, makeCallLabel);
  2094. this->Writer()->MarkLabel(useNewTargetForThisLabel);
  2095. this->Writer()->Reg2(Js::OpCode::Ld_A, thisForSuperCall, funcInfo->newTargetRegister);
  2096. this->Writer()->MarkLabel(makeCallLabel);
  2097. EmitCall(pnode, Js::Constants::NoRegister, this, funcInfo, fReturnValue, /*fEvaluateComponents*/ true, /*fHasNewTarget*/ true, thisForSuperCall);
  2098. // We have to use another temp for the this value before assigning to this register.
  2099. // This is because IRBuilder does not expect us to use the value of a temp after potentially assigning to that same temp.
  2100. // Ex:
  2101. // _this = new.target;
  2102. // temp = super.call(_this);
  2103. // if (temp is object) {
  2104. // _this = temp; // creates a new sym for _this as it was previously used
  2105. // }
  2106. // this = _this; // tries to loads a value from the old sym (which is dead)
  2107. Js::RegSlot valueForThis = funcInfo->AcquireTmpRegister();
  2108. this->Writer()->BrReg1(Js::OpCode::BrOnObject_A, useSuperCallResultLabel, pnode->location);
  2109. this->Writer()->Reg2(Js::OpCode::Ld_A, valueForThis, thisForSuperCall);
  2110. this->Writer()->Br(Js::OpCode::Br, doneLabel);
  2111. this->Writer()->MarkLabel(useSuperCallResultLabel);
  2112. this->Writer()->Reg2(Js::OpCode::Ld_A, valueForThis, pnode->location);
  2113. this->Writer()->MarkLabel(doneLabel);
  2114. // The call is done and we know what we will bind to 'this' so let's check to see if 'this' is already decl.
  2115. // We may need to load 'this' from the scope slot.
  2116. EmitScopeSlotLoadThis(funcInfo, funcInfo->thisPointerRegister, false);
  2117. Js::ByteCodeLabel skipLabel = this->Writer()->DefineLabel();
  2118. Js::RegSlot tmpUndeclReg = funcInfo->AcquireTmpRegister();
  2119. this->Writer()->Reg1(Js::OpCode::InitUndecl, tmpUndeclReg);
  2120. this->Writer()->BrReg2(Js::OpCode::BrSrEq_A, skipLabel, funcInfo->thisPointerRegister, tmpUndeclReg);
  2121. funcInfo->ReleaseTmpRegister(tmpUndeclReg);
  2122. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_ClassThisAlreadyAssigned));
  2123. this->Writer()->MarkLabel(skipLabel);
  2124. this->Writer()->Reg2(Js::OpCode::StrictLdThis, funcInfo->thisPointerRegister, valueForThis);
  2125. funcInfo->ReleaseTmpRegister(valueForThis);
  2126. funcInfo->ReleaseTmpRegister(thisForSuperCall);
  2127. // We already assigned the result of super() to the 'this' register but we need to store it in the scope slot, too. If there is one.
  2128. this->EmitScopeSlotStoreThis(funcInfo, nonLambdaFunc->thisScopeSlot);
  2129. }
  2130. void ByteCodeGenerator::EmitClassConstructorEndCode(FuncInfo *funcInfo)
  2131. {
  2132. if (funcInfo->thisPointerRegister != Js::Constants::NoRegister)
  2133. {
  2134. // We need to try and load 'this' from the scope slot, if there is one.
  2135. EmitScopeSlotLoadThis(funcInfo, funcInfo->thisPointerRegister);
  2136. this->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, funcInfo->thisPointerRegister);
  2137. }
  2138. }
  2139. void ByteCodeGenerator::EmitBaseClassConstructorThisObject(FuncInfo *funcInfo)
  2140. {
  2141. this->Writer()->Reg2(Js::OpCode::NewScObjectNoCtorFull, funcInfo->thisPointerRegister, funcInfo->newTargetRegister);
  2142. }
  2143. void ByteCodeGenerator::EmitInternalScopedSlotLoad(FuncInfo *funcInfo, Js::RegSlot slot, Js::RegSlot symbolRegister, bool chkUndecl)
  2144. {
  2145. Scope* scope = nullptr;
  2146. if (funcInfo->IsLambda())
  2147. {
  2148. Js::PropertyId envIndex = -1;
  2149. GetEnclosingNonLambdaScope(funcInfo, scope, envIndex);
  2150. EmitInternalScopedSlotLoad(funcInfo, scope, envIndex, slot, symbolRegister, chkUndecl);
  2151. }
  2152. else
  2153. {
  2154. scope = funcInfo->GetBodyScope();
  2155. EmitInternalScopedSlotLoad(funcInfo, scope, -1, slot, symbolRegister, chkUndecl);
  2156. }
  2157. }
  2158. void ByteCodeGenerator::EmitInternalScopedSlotLoad(FuncInfo *funcInfo, Scope *scope, Js::PropertyId envIndex, Js::RegSlot slot, Js::RegSlot symbolRegister, bool chkUndecl)
  2159. {
  2160. Assert(slot != Js::Constants::NoProperty);
  2161. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(scope, symbolRegister);
  2162. Js::OpCode opcode;
  2163. Js::RegSlot scopeLocation = scope->GetLocation();
  2164. opcode = this->GetLdSlotOp(scope, envIndex, scopeLocation, funcInfo);
  2165. slot += (scope->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  2166. if (envIndex != -1)
  2167. {
  2168. this->m_writer.SlotI2(opcode, symbolRegister, envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var), slot, profileId);
  2169. }
  2170. else if (scopeLocation != Js::Constants::NoRegister &&
  2171. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  2172. {
  2173. this->m_writer.SlotI1(opcode, symbolRegister, slot, profileId);
  2174. }
  2175. else
  2176. {
  2177. this->m_writer.Slot(opcode, symbolRegister, scopeLocation, slot, profileId);
  2178. }
  2179. if (chkUndecl)
  2180. {
  2181. this->m_writer.Reg1(Js::OpCode::ChkUndecl, symbolRegister);
  2182. }
  2183. }
  2184. void ByteCodeGenerator::EmitInternalScopedSlotStore(FuncInfo *funcInfo, Js::RegSlot slot, Js::RegSlot symbolRegister)
  2185. {
  2186. Assert(slot != Js::Constants::NoProperty);
  2187. Scope* scope = nullptr;
  2188. Js::OpCode opcode;
  2189. Js::PropertyId envIndex = -1;
  2190. if (funcInfo->IsLambda())
  2191. {
  2192. GetEnclosingNonLambdaScope(funcInfo, scope, envIndex);
  2193. }
  2194. else
  2195. {
  2196. scope = funcInfo->GetBodyScope();
  2197. }
  2198. Js::RegSlot scopeLocation = scope->GetLocation();
  2199. opcode = this->GetStSlotOp(scope, envIndex, scopeLocation, false, funcInfo);
  2200. slot += (scope->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  2201. if (envIndex != -1)
  2202. {
  2203. this->m_writer.SlotI2(opcode, symbolRegister, envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var), slot);
  2204. }
  2205. else if (scopeLocation != Js::Constants::NoRegister &&
  2206. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  2207. {
  2208. this->m_writer.SlotI1(opcode, symbolRegister, slot);
  2209. }
  2210. else if (scope->GetIsObject())
  2211. {
  2212. this->m_writer.Slot(opcode, symbolRegister, scopeLocation, slot);
  2213. }
  2214. else
  2215. {
  2216. this->m_writer.SlotI2(opcode, symbolRegister, scope->GetInnerScopeIndex(), slot);
  2217. }
  2218. }
  2219. void ByteCodeGenerator::EmitInternalScopeObjInit(FuncInfo *funcInfo, Scope *scope, Js::RegSlot valueLocation, Js::PropertyId propertyId)
  2220. {
  2221. Js::RegSlot scopeLocation = scope->GetLocation();
  2222. Js::OpCode opcode = this->GetInitFldOp(scope, scopeLocation, funcInfo);
  2223. if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  2224. {
  2225. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  2226. this->m_writer.ElementP(opcode, valueLocation, cacheId);
  2227. }
  2228. else if (scope->HasInnerScopeIndex())
  2229. {
  2230. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
  2231. this->m_writer.ElementPIndexed(opcode, valueLocation, scope->GetInnerScopeIndex(), cacheId);
  2232. }
  2233. else
  2234. {
  2235. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  2236. this->m_writer.PatchableProperty(opcode, valueLocation, scopeLocation, cacheId);
  2237. }
  2238. }
  2239. void ByteCodeGenerator::GetEnclosingNonLambdaScope(FuncInfo *funcInfo, Scope * &scope, Js::PropertyId &envIndex)
  2240. {
  2241. Assert(funcInfo->IsLambda());
  2242. envIndex = -1;
  2243. for (scope = GetCurrentScope(); scope; scope = scope->GetEnclosingScope())
  2244. {
  2245. if (scope->GetMustInstantiate() && scope->GetFunc() != funcInfo)
  2246. {
  2247. envIndex++;
  2248. }
  2249. if (((scope == scope->GetFunc()->GetBodyScope() || scope == scope->GetFunc()->GetParamScope()) && !scope->GetFunc()->IsLambda()) || scope->IsGlobalEvalBlockScope())
  2250. {
  2251. break;
  2252. }
  2253. }
  2254. }
  2255. void ByteCodeGenerator::EmitThis(FuncInfo *funcInfo, Js::RegSlot fromRegister)
  2256. {
  2257. if (funcInfo->IsLambda())
  2258. {
  2259. Scope *scope;
  2260. Js::PropertyId envIndex = -1;
  2261. GetEnclosingNonLambdaScope(funcInfo, scope, envIndex);
  2262. FuncInfo* parent = scope->GetFunc();
  2263. if (parent->IsGlobalFunction())
  2264. {
  2265. if (this->flags & fscrEval)
  2266. {
  2267. scope = parent->GetGlobalEvalBlockScope();
  2268. Js::PropertyId slot = parent->thisScopeSlot;
  2269. EmitInternalScopedSlotLoad(funcInfo, scope, envIndex, slot, funcInfo->thisPointerRegister, false);
  2270. }
  2271. else
  2272. {
  2273. // Always load global object via LdThis of null to get the possibly protected via secureHostObject global object.
  2274. this->m_writer.Reg2Int1(Js::OpCode::LdThis, funcInfo->thisPointerRegister, funcInfo->nullConstantRegister, this->GetModuleID());
  2275. }
  2276. }
  2277. else if (!parent->IsClassConstructor() || parent->IsBaseClassConstructor())
  2278. {
  2279. // In a lambda inside a derived class constructor, 'this' should be loaded from the scope slot whenever 'this' is accessed.
  2280. // It's safe to load 'this' into the register for base class constructors because there is no complex assignment to 'this'
  2281. // via super call chain.
  2282. Js::PropertyId slot = parent->thisScopeSlot;
  2283. EmitInternalScopedSlotLoad(funcInfo, scope, envIndex, slot, funcInfo->thisPointerRegister, false);
  2284. }
  2285. }
  2286. else if (funcInfo->byteCodeFunction->GetIsStrictMode() && (!funcInfo->IsGlobalFunction() || this->flags & fscrEval))
  2287. {
  2288. m_writer.Reg2(Js::OpCode::StrictLdThis, funcInfo->thisPointerRegister, fromRegister);
  2289. }
  2290. else
  2291. {
  2292. m_writer.Reg2Int1(Js::OpCode::LdThis, funcInfo->thisPointerRegister, fromRegister, this->GetModuleID());
  2293. }
  2294. }
  2295. void ByteCodeGenerator::EmitLoadFormalIntoRegister(ParseNode *pnodeFormal, Js::RegSlot pos, FuncInfo *funcInfo)
  2296. {
  2297. if (pnodeFormal->IsVarLetOrConst())
  2298. {
  2299. // Get the param from its argument position into its assigned register.
  2300. // The position should match the location, otherwise, it has been shadowed by parameter with the same name
  2301. Symbol *formal = pnodeFormal->sxVar.sym;
  2302. if (formal->GetLocation() + 1 == pos)
  2303. {
  2304. // Transfer to the frame object, etc., if necessary.
  2305. this->EmitLocalPropInit(formal->GetLocation(), formal, funcInfo);
  2306. }
  2307. if (ShouldTrackDebuggerMetadata() && !formal->IsInSlot(funcInfo))
  2308. {
  2309. Assert(!formal->GetHasInit());
  2310. funcInfo->GetParsedFunctionBody()->InsertSymbolToRegSlotList(formal->GetName(), formal->GetLocation(), funcInfo->varRegsCount);
  2311. }
  2312. }
  2313. }
  2314. void ByteCodeGenerator::HomeArguments(FuncInfo *funcInfo)
  2315. {
  2316. // Transfer formal parameters to their home locations on the local frame.
  2317. if (funcInfo->GetHasArguments())
  2318. {
  2319. if (funcInfo->root->sxFnc.pnodeRest != nullptr)
  2320. {
  2321. // Since we don't have to iterate over arguments here, we'll trust the location to be correct.
  2322. EmitLoadFormalIntoRegister(funcInfo->root->sxFnc.pnodeRest, funcInfo->root->sxFnc.pnodeRest->sxVar.sym->GetLocation() + 1, funcInfo);
  2323. }
  2324. // The arguments object creation helper does this work for us.
  2325. return;
  2326. }
  2327. Js::ArgSlot pos = 1;
  2328. auto loadFormal = [&](ParseNode *pnodeFormal)
  2329. {
  2330. EmitLoadFormalIntoRegister(pnodeFormal, pos, funcInfo);
  2331. pos++;
  2332. };
  2333. MapFormals(funcInfo->root, loadFormal);
  2334. }
  2335. void ByteCodeGenerator::DefineLabels(FuncInfo *funcInfo)
  2336. {
  2337. funcInfo->singleExit = m_writer.DefineLabel();
  2338. SList<ParseNode *>::Iterator iter(&funcInfo->targetStatements);
  2339. while (iter.Next())
  2340. {
  2341. ParseNode * node = iter.Data();
  2342. node->sxStmt.breakLabel = m_writer.DefineLabel();
  2343. node->sxStmt.continueLabel = m_writer.DefineLabel();
  2344. node->emitLabels = true;
  2345. }
  2346. }
  2347. void ByteCodeGenerator::EmitGlobalBody(FuncInfo *funcInfo)
  2348. {
  2349. // Emit global code (global scope or eval), fixing up the return register with the implicit
  2350. // return value.
  2351. ParseNode *pnode = funcInfo->root->sxFnc.pnodeBody;
  2352. ParseNode *pnodeLastVal = funcInfo->root->sxProg.pnodeLastValStmt;
  2353. if (pnodeLastVal == nullptr)
  2354. {
  2355. // We're not guaranteed to compute any values, so fix up the return register at the top
  2356. // in case.
  2357. this->m_writer.Reg1(Js::OpCode::LdUndef, ReturnRegister);
  2358. }
  2359. while (pnode->nop == knopList)
  2360. {
  2361. ParseNode *stmt = pnode->sxBin.pnode1;
  2362. if (stmt == pnodeLastVal)
  2363. {
  2364. pnodeLastVal = nullptr;
  2365. }
  2366. if (pnodeLastVal == nullptr && (this->flags & fscrReturnExpression))
  2367. {
  2368. EmitTopLevelStatement(stmt, funcInfo, true);
  2369. }
  2370. else
  2371. {
  2372. // Haven't hit the post-dominating return value yet,
  2373. // so don't bother with the return register.
  2374. EmitTopLevelStatement(stmt, funcInfo, false);
  2375. }
  2376. pnode = pnode->sxBin.pnode2;
  2377. }
  2378. EmitTopLevelStatement(pnode, funcInfo, false);
  2379. }
  2380. void ByteCodeGenerator::EmitFunctionBody(FuncInfo *funcInfo)
  2381. {
  2382. // Emit a function body. Only explicit returns and the implicit "undef" at the bottom
  2383. // get copied to the return register.
  2384. ParseNode *pnodeBody = funcInfo->root->sxFnc.pnodeBody;
  2385. ParseNode *pnode = pnodeBody;
  2386. while (pnode->nop == knopList)
  2387. {
  2388. ParseNode *stmt = pnode->sxBin.pnode1;
  2389. if (stmt->CapturesSyms())
  2390. {
  2391. CapturedSymMap *map = funcInfo->EnsureCapturedSymMap();
  2392. SList<Symbol*> *list = map->Item(stmt);
  2393. FOREACH_SLIST_ENTRY(Symbol*, sym, list)
  2394. {
  2395. if (!sym->GetIsCommittedToSlot())
  2396. {
  2397. Assert(sym->GetLocation() != Js::Constants::NoProperty);
  2398. sym->SetIsCommittedToSlot();
  2399. ParseNode *decl = sym->GetDecl();
  2400. Assert(decl);
  2401. if (PHASE_TRACE(Js::DelayCapturePhase, funcInfo->byteCodeFunction))
  2402. {
  2403. Output::Print(_u("--- DelayCapture: Committed symbol '%s' to slot.\n"), sym->GetName());
  2404. Output::Flush();
  2405. }
  2406. // REVIEW[ianhall]: HACK to work around this causing an error due to sym not yet being initialized
  2407. // what is this doing? Why are we assigning sym to itself?
  2408. bool old = sym->GetNeedDeclaration();
  2409. sym->SetNeedDeclaration(false);
  2410. this->EmitPropStore(sym->GetLocation(), sym, sym->GetPid(), funcInfo, decl->nop == knopLetDecl, decl->nop == knopConstDecl);
  2411. sym->SetNeedDeclaration(old);
  2412. }
  2413. }
  2414. NEXT_SLIST_ENTRY;
  2415. }
  2416. EmitTopLevelStatement(stmt, funcInfo, false);
  2417. pnode = pnode->sxBin.pnode2;
  2418. }
  2419. Assert(!pnode->CapturesSyms());
  2420. EmitTopLevelStatement(pnode, funcInfo, false);
  2421. }
  2422. void ByteCodeGenerator::EmitProgram(ParseNode *pnodeProg)
  2423. {
  2424. // Indicate that the binding phase is over.
  2425. this->isBinding = false;
  2426. this->trackEnvDepth = true;
  2427. AssignPropertyIds(pnodeProg->sxFnc.funcInfo->byteCodeFunction);
  2428. int32 initSize = this->maxAstSize / AstBytecodeRatioEstimate;
  2429. // Use the temp allocator in bytecode write temp buffer.
  2430. m_writer.InitData(this->alloc, initSize);
  2431. #ifdef LOG_BYTECODE_AST_RATIO
  2432. // log the max Ast size
  2433. Output::Print(_u("Max Ast size: %d"), initSize);
  2434. #endif
  2435. Assert(pnodeProg && pnodeProg->nop == knopProg);
  2436. if (this->parentScopeInfo)
  2437. {
  2438. // Scope stack is already set up the way we want it, so don't visit the global scope.
  2439. // Start emitting with the nested scope (i.e., the deferred function).
  2440. this->EmitScopeList(pnodeProg->sxProg.pnodeScopes);
  2441. }
  2442. else
  2443. {
  2444. this->EmitScopeList(pnodeProg);
  2445. }
  2446. }
  2447. void ByteCodeGenerator::EmitInitCapturedThis(FuncInfo* funcInfo, Scope* scope)
  2448. {
  2449. if (scope->GetIsObject())
  2450. {
  2451. // Ensure space for the this slot
  2452. this->EmitInternalScopeObjInit(funcInfo, scope, funcInfo->thisPointerRegister, Js::PropertyIds::_lexicalThisSlotSymbol);
  2453. }
  2454. else
  2455. {
  2456. this->EmitInternalScopedSlotStore(funcInfo, funcInfo->thisScopeSlot, funcInfo->thisPointerRegister);
  2457. }
  2458. }
  2459. void ByteCodeGenerator::EmitInitCapturedNewTarget(FuncInfo* funcInfo, Scope* scope)
  2460. {
  2461. if (scope->GetIsObject())
  2462. {
  2463. // Ensure space for the new.target slot
  2464. this->EmitInternalScopeObjInit(funcInfo, scope, funcInfo->newTargetRegister, Js::PropertyIds::_lexicalNewTargetSymbol);
  2465. }
  2466. else
  2467. {
  2468. this->EmitInternalScopedSlotStore(funcInfo, funcInfo->newTargetScopeSlot, funcInfo->newTargetRegister);
  2469. }
  2470. }
  2471. void EmitDestructuredObject(ParseNode *lhs, Js::RegSlot rhsLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  2472. void EmitDestructuredValueOrInitializer(ParseNodePtr lhsElementNode, Js::RegSlot rhsLocation, ParseNodePtr initializer, bool isNonPatternAssignmentTarget, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo);
  2473. void ByteCodeGenerator::PopulateFormalsScope(uint beginOffset, FuncInfo *funcInfo, ParseNode *pnode)
  2474. {
  2475. Js::DebuggerScope *debuggerScope = nullptr;
  2476. auto processArg = [&](ParseNode *pnodeArg) {
  2477. if (pnodeArg->IsVarLetOrConst())
  2478. {
  2479. if (debuggerScope == nullptr)
  2480. {
  2481. debuggerScope = RecordStartScopeObject(pnode, funcInfo->paramScope && funcInfo->paramScope->GetIsObject() ? Js::DiagParamScopeInObject : Js::DiagParamScope);
  2482. debuggerScope->SetBegin(beginOffset);
  2483. }
  2484. debuggerScope->AddProperty(pnodeArg->sxVar.sym->GetLocation(), pnodeArg->sxVar.sym->EnsurePosition(funcInfo), Js::DebuggerScopePropertyFlags_None);
  2485. }
  2486. };
  2487. MapFormals(pnode, processArg);
  2488. MapFormalsFromPattern(pnode, processArg);
  2489. if (debuggerScope != nullptr)
  2490. {
  2491. RecordEndScopeObject(pnode);
  2492. }
  2493. }
  2494. void ByteCodeGenerator::EmitDefaultArgs(FuncInfo *funcInfo, ParseNode *pnode)
  2495. {
  2496. uint beginOffset = m_writer.GetCurrentOffset();
  2497. auto emitDefaultArg = [&](ParseNode *pnodeArg)
  2498. {
  2499. if (pnodeArg->nop == knopParamPattern)
  2500. {
  2501. this->StartStatement(pnodeArg);
  2502. Assert(pnodeArg->sxParamPattern.location != Js::Constants::NoRegister);
  2503. ParseNodePtr pnode1 = pnodeArg->sxParamPattern.pnode1;
  2504. if (pnode1->IsPattern())
  2505. {
  2506. EmitAssignment(nullptr, pnode1, pnodeArg->sxParamPattern.location, this, funcInfo);
  2507. }
  2508. else
  2509. {
  2510. Assert(pnode1->nop == knopAsg);
  2511. Assert(pnode1->sxBin.pnode1->IsPattern());
  2512. EmitDestructuredValueOrInitializer(pnode1->sxBin.pnode1,
  2513. pnodeArg->sxParamPattern.location,
  2514. pnode1->sxBin.pnode2,
  2515. false /*isNonPatternAssignmentTarget*/,
  2516. this,
  2517. funcInfo);
  2518. }
  2519. this->EndStatement(pnodeArg);
  2520. return;
  2521. }
  2522. else if (pnodeArg->IsVarLetOrConst())
  2523. {
  2524. Js::RegSlot location = pnodeArg->sxVar.sym->GetLocation();
  2525. if (pnodeArg->sxVar.pnodeInit == nullptr)
  2526. {
  2527. // Since the formal hasn't been initialized in LdLetHeapArguments, we'll initialize it here.
  2528. pnodeArg->sxVar.sym->SetNeedDeclaration(false);
  2529. EmitPropStore(location, pnodeArg->sxVar.sym, pnodeArg->sxVar.pid, funcInfo, true);
  2530. return;
  2531. }
  2532. // Load the default argument if we got undefined, skip RHS evaluation otherwise.
  2533. Js::ByteCodeLabel noDefaultLabel = this->m_writer.DefineLabel();
  2534. Js::ByteCodeLabel endLabel = this->m_writer.DefineLabel();
  2535. this->StartStatement(pnodeArg);
  2536. // Let us use strict not equal to differentiate between null and undefined
  2537. m_writer.BrReg2(Js::OpCode::BrSrNeq_A, noDefaultLabel, location, funcInfo->undefinedConstantRegister);
  2538. Emit(pnodeArg->sxVar.pnodeInit, this, funcInfo, false);
  2539. pnodeArg->sxVar.sym->SetNeedDeclaration(false); // After emit to prevent foo(a = a)
  2540. if (funcInfo->GetHasArguments() && pnodeArg->sxVar.sym->IsInSlot(funcInfo))
  2541. {
  2542. EmitPropStore(pnodeArg->sxVar.pnodeInit->location, pnodeArg->sxVar.sym, pnodeArg->sxVar.pid, funcInfo, true);
  2543. m_writer.Br(endLabel);
  2544. }
  2545. else
  2546. {
  2547. EmitAssignment(nullptr, pnodeArg, pnodeArg->sxVar.pnodeInit->location, this, funcInfo);
  2548. }
  2549. funcInfo->ReleaseLoc(pnodeArg->sxVar.pnodeInit);
  2550. m_writer.MarkLabel(noDefaultLabel);
  2551. if (funcInfo->GetHasArguments() && pnodeArg->sxVar.sym->IsInSlot(funcInfo))
  2552. {
  2553. EmitPropStore(location, pnodeArg->sxVar.sym, pnodeArg->sxVar.pid, funcInfo, true);
  2554. m_writer.MarkLabel(endLabel);
  2555. }
  2556. this->EndStatement(pnodeArg);
  2557. }
  2558. };
  2559. // If the function is async, we wrap the default arguments in a try catch and reject a Promise in case of error.
  2560. if (pnode->sxFnc.IsAsync())
  2561. {
  2562. uint cacheId;
  2563. Js::ByteCodeLabel catchLabel = m_writer.DefineLabel();
  2564. Js::ByteCodeLabel doneLabel = m_writer.DefineLabel();
  2565. Js::RegSlot catchArgLocation = funcInfo->AcquireTmpRegister();
  2566. Js::RegSlot promiseLocation = funcInfo->AcquireTmpRegister();
  2567. Js::RegSlot rejectLocation = funcInfo->AcquireTmpRegister();
  2568. // try
  2569. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  2570. m_writer.Br(Js::OpCode::TryCatch, catchLabel);
  2571. // Rest cannot have a default argument, so we ignore it.
  2572. MapFormalsWithoutRest(pnode, emitDefaultArg);
  2573. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  2574. m_writer.Empty(Js::OpCode::Leave);
  2575. m_writer.Br(doneLabel);
  2576. // catch
  2577. m_writer.MarkLabel(catchLabel);
  2578. m_writer.Reg1(Js::OpCode::Catch, catchArgLocation);
  2579. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  2580. m_writer.Empty(Js::OpCode::Nop);
  2581. // return Promise.reject(error);
  2582. cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(Js::PropertyIds::Promise, false, false);
  2583. m_writer.PatchableRootProperty(Js::OpCode::LdRootFld, promiseLocation, cacheId, false, false);
  2584. EmitInvoke(rejectLocation, promiseLocation, Js::PropertyIds::reject, this, funcInfo, catchArgLocation);
  2585. m_writer.Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, rejectLocation);
  2586. m_writer.RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  2587. m_writer.Empty(Js::OpCode::Leave);
  2588. m_writer.Br(funcInfo->singleExit);
  2589. m_writer.Empty(Js::OpCode::Leave);
  2590. m_writer.MarkLabel(doneLabel);
  2591. this->SetHasTry(true);
  2592. funcInfo->ReleaseTmpRegister(rejectLocation);
  2593. funcInfo->ReleaseTmpRegister(promiseLocation);
  2594. funcInfo->ReleaseTmpRegister(catchArgLocation);
  2595. }
  2596. else
  2597. {
  2598. // Rest cannot have a default argument, so we ignore it.
  2599. MapFormalsWithoutRest(pnode, emitDefaultArg);
  2600. }
  2601. if (m_writer.GetCurrentOffset() > beginOffset)
  2602. {
  2603. PopulateFormalsScope(beginOffset, funcInfo, pnode);
  2604. }
  2605. }
  2606. void ByteCodeGenerator::EmitOneFunction(ParseNode *pnode)
  2607. {
  2608. Assert(pnode && (pnode->nop == knopProg || pnode->nop == knopFncDecl));
  2609. FuncInfo *funcInfo = pnode->sxFnc.funcInfo;
  2610. Assert(funcInfo != nullptr);
  2611. if (funcInfo->IsFakeGlobalFunction(this->flags))
  2612. {
  2613. return;
  2614. }
  2615. Js::ParseableFunctionInfo* deferParseFunction = funcInfo->byteCodeFunction;
  2616. deferParseFunction->SetGrfscr(deferParseFunction->GetGrfscr() | (this->flags & ~fscrDeferredFncExpression));
  2617. deferParseFunction->SetSourceInfo(this->GetCurrentSourceIndex(),
  2618. funcInfo->root,
  2619. !!(this->flags & fscrEvalCode),
  2620. ((this->flags & fscrDynamicCode) && !(this->flags & fscrEvalCode)));
  2621. deferParseFunction->SetInParamsCount(funcInfo->inArgsCount);
  2622. if (pnode->sxFnc.HasDefaultArguments())
  2623. {
  2624. deferParseFunction->SetReportedInParamsCount(pnode->sxFnc.firstDefaultArg + 1);
  2625. }
  2626. else
  2627. {
  2628. deferParseFunction->SetReportedInParamsCount(funcInfo->inArgsCount);
  2629. }
  2630. if (funcInfo->root->sxFnc.pnodeBody == nullptr)
  2631. {
  2632. if (!PHASE_OFF1(Js::SkipNestedDeferredPhase))
  2633. {
  2634. deferParseFunction->BuildDeferredStubs(funcInfo->root);
  2635. }
  2636. Assert(!deferParseFunction->IsFunctionBody() || deferParseFunction->GetFunctionBody()->GetByteCode() != nullptr);
  2637. return;
  2638. }
  2639. Js::FunctionBody* byteCodeFunction = funcInfo->GetParsedFunctionBody();
  2640. // We've now done a full parse of this function, so we no longer need to remember the extents
  2641. // and attributes of the top-level nested functions. (The above code has run for all of those,
  2642. // so they have pointers to the stub sub-trees they need.)
  2643. byteCodeFunction->SetDeferredStubs(nullptr);
  2644. if (byteCodeFunction->GetByteCode() != nullptr)
  2645. {
  2646. // Previously compiled function nested within a re-deferred and re-compiled function.
  2647. return;
  2648. }
  2649. try
  2650. {
  2651. // Bug : 301517
  2652. // In the debug mode the hasOnlyThis optimization needs to be disabled, since user can break in this function
  2653. // and do operation on 'this' and its property, which may not be defined yet.
  2654. if (funcInfo->root->sxFnc.HasOnlyThisStmts() && !IsInDebugMode())
  2655. {
  2656. byteCodeFunction->SetHasOnlyThisStmts(true);
  2657. }
  2658. if (byteCodeFunction->IsInlineApplyDisabled() || this->scriptContext->GetConfig()->IsNoNative())
  2659. {
  2660. if ((pnode->nop == knopFncDecl) && (funcInfo->GetHasHeapArguments()) && (!funcInfo->GetCallsEval()) && ApplyEnclosesArgs(pnode, this))
  2661. {
  2662. bool applyEnclosesArgs = true;
  2663. for (ParseNode* pnodeVar = funcInfo->root->sxFnc.pnodeVars; pnodeVar; pnodeVar = pnodeVar->sxVar.pnodeNext)
  2664. {
  2665. Symbol* sym = pnodeVar->sxVar.sym;
  2666. if (sym->GetSymbolType() == STVariable && !sym->GetIsArguments())
  2667. {
  2668. applyEnclosesArgs = false;
  2669. break;
  2670. }
  2671. }
  2672. auto constAndLetCheck = [](ParseNode *pnodeBlock, bool *applyEnclosesArgs)
  2673. {
  2674. if (*applyEnclosesArgs)
  2675. {
  2676. for (auto lexvar = pnodeBlock->sxBlock.pnodeLexVars; lexvar; lexvar = lexvar->sxVar.pnodeNext)
  2677. {
  2678. Symbol* sym = lexvar->sxVar.sym;
  2679. if (sym->GetSymbolType() == STVariable && !sym->GetIsArguments())
  2680. {
  2681. *applyEnclosesArgs = false;
  2682. break;
  2683. }
  2684. }
  2685. }
  2686. };
  2687. constAndLetCheck(funcInfo->root->sxFnc.pnodeScopes, &applyEnclosesArgs);
  2688. constAndLetCheck(funcInfo->root->sxFnc.pnodeBodyScope, &applyEnclosesArgs);
  2689. funcInfo->SetApplyEnclosesArgs(applyEnclosesArgs);
  2690. }
  2691. }
  2692. if (!funcInfo->IsGlobalFunction())
  2693. {
  2694. // Note: Do not set the stack nested func flag if the function has been redeferred and recompiled.
  2695. // In that case the flag already has the value we want.
  2696. if (CanStackNestedFunc(funcInfo, true) && byteCodeFunction->GetCompileCount() == 0)
  2697. {
  2698. #if DBG
  2699. byteCodeFunction->SetCanDoStackNestedFunc();
  2700. #endif
  2701. if (funcInfo->root->sxFnc.astSize <= PnFnc::MaxStackClosureAST)
  2702. {
  2703. byteCodeFunction->SetStackNestedFunc(true);
  2704. }
  2705. }
  2706. }
  2707. InitScopeSlotArray(funcInfo);
  2708. FinalizeRegisters(funcInfo, byteCodeFunction);
  2709. DebugOnly(Js::RegSlot firstTmpReg = funcInfo->varRegsCount);
  2710. // Reserve temp registers for the inner scopes. We prefer temps because the JIT will then renumber them
  2711. // and see different lifetimes. (Note that debug mode requires permanent registers. See FinalizeRegisters.)
  2712. uint innerScopeCount = funcInfo->InnerScopeCount();
  2713. if (!this->IsInDebugMode())
  2714. {
  2715. byteCodeFunction->SetInnerScopeCount(innerScopeCount);
  2716. if (innerScopeCount)
  2717. {
  2718. funcInfo->SetFirstInnerScopeReg(funcInfo->AcquireTmpRegister());
  2719. for (uint i = 1; i < innerScopeCount; i++)
  2720. {
  2721. funcInfo->AcquireTmpRegister();
  2722. }
  2723. }
  2724. }
  2725. funcInfo->inlineCacheMap = Anew(alloc, FuncInfo::InlineCacheMap,
  2726. alloc,
  2727. funcInfo->RegCount() // Pass the actual register count. // TODO: Check if we can reduce this count
  2728. );
  2729. funcInfo->rootObjectLoadInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2730. alloc,
  2731. 10);
  2732. funcInfo->rootObjectLoadMethodInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2733. alloc,
  2734. 10);
  2735. funcInfo->rootObjectStoreInlineCacheMap = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2736. alloc,
  2737. 10);
  2738. funcInfo->referencedPropertyIdToMapIndex = Anew(alloc, FuncInfo::RootObjectInlineCacheIdMap,
  2739. alloc,
  2740. 10);
  2741. byteCodeFunction->AllocateLiteralRegexArray();
  2742. m_callSiteId = 0;
  2743. m_writer.Begin(byteCodeFunction, alloc, this->DoJitLoopBodies(funcInfo), funcInfo->hasLoop, this->IsInDebugMode());
  2744. this->PushFuncInfo(_u("EmitOneFunction"), funcInfo);
  2745. this->inPrologue = true;
  2746. // Class constructors do not have a [[call]] slot but we don't implement a generic way to express this.
  2747. // What we do is emit a check for the new flag here. If we don't have CallFlags_New set, the opcode will throw.
  2748. // We need to do this before emitting 'this' since the base class constructor will try to construct a new object.
  2749. if (funcInfo->IsClassConstructor())
  2750. {
  2751. m_writer.Empty(Js::OpCode::ChkNewCallFlag);
  2752. }
  2753. Scope* currentScope = funcInfo->GetCurrentChildScope();
  2754. Scope* paramScope = funcInfo->GetParamScope();
  2755. Scope* bodyScope = funcInfo->GetBodyScope();
  2756. // For now, emit all constant loads at top of function (should instead put in closest dominator of uses).
  2757. LoadAllConstants(funcInfo);
  2758. HomeArguments(funcInfo);
  2759. if (!currentScope->GetCanMergeWithBodyScope())
  2760. {
  2761. byteCodeFunction->SetParamAndBodyScopeNotMerged();
  2762. // Pop the body scope before emitting the default args
  2763. PopScope();
  2764. Assert(this->GetCurrentScope() == paramScope);
  2765. }
  2766. if (funcInfo->root->sxFnc.pnodeRest != nullptr)
  2767. {
  2768. byteCodeFunction->SetHasRestParameter();
  2769. }
  2770. if (funcInfo->thisScopeSlot != Js::Constants::NoRegister && !(funcInfo->IsLambda() || (funcInfo->IsGlobalFunction() && this->flags & fscrEval)))
  2771. {
  2772. EmitInitCapturedThis(funcInfo, funcInfo->bodyScope);
  2773. }
  2774. // Any function with a super reference or an eval call inside a method or a constructor needs to load super,
  2775. if ((funcInfo->HasSuperReference() || (funcInfo->GetCallsEval() && (funcInfo->root->sxFnc.IsMethod() || funcInfo->root->sxFnc.IsConstructor())))
  2776. // unless we are already inside the 'global' scope inside an eval (in which case 'ScopedLdHomeObj' is emitted at every 'super' reference).
  2777. && !((GetFlags() & fscrEval) && funcInfo->IsGlobalFunction()))
  2778. {
  2779. if (funcInfo->IsLambda())
  2780. {
  2781. Scope *scope;
  2782. Js::PropertyId envIndex = -1;
  2783. GetEnclosingNonLambdaScope(funcInfo, scope, envIndex);
  2784. FuncInfo* parent = scope->GetFunc();
  2785. if (!parent->IsGlobalFunction())
  2786. {
  2787. // lambda in non-global scope (eval and non-eval)
  2788. EmitInternalScopedSlotLoad(funcInfo, scope, envIndex, parent->superScopeSlot, funcInfo->superRegister);
  2789. if (funcInfo->superCtorRegister != Js::Constants::NoRegister)
  2790. {
  2791. EmitInternalScopedSlotLoad(funcInfo, scope, envIndex, parent->superCtorScopeSlot, funcInfo->superCtorRegister);
  2792. }
  2793. }
  2794. else if (!(GetFlags() & fscrEval))
  2795. {
  2796. // lambda in non-eval global scope
  2797. m_writer.Reg1(Js::OpCode::LdUndef, funcInfo->superRegister);
  2798. }
  2799. // lambda in eval global scope: ScopedLdHomeObj will handle error throwing
  2800. }
  2801. else
  2802. {
  2803. m_writer.Reg1(Js::OpCode::LdHomeObj, funcInfo->superRegister);
  2804. if (funcInfo->superCtorRegister != Js::Constants::NoRegister) // super() is allowed only in derived class constructors
  2805. {
  2806. m_writer.Reg1(Js::OpCode::LdFuncObj, funcInfo->superCtorRegister);
  2807. }
  2808. if (!funcInfo->IsGlobalFunction())
  2809. {
  2810. if (bodyScope->GetIsObject() && bodyScope->GetLocation() != Js::Constants::NoRegister)
  2811. {
  2812. // Stash the super reference in case something inside the eval or lambda references it.
  2813. uint cacheId = funcInfo->FindOrAddInlineCacheId(bodyScope->GetLocation(), Js::PropertyIds::_superReferenceSymbol, false, true);
  2814. m_writer.ElementP(Js::OpCode::InitLocalFld, funcInfo->superRegister, cacheId);
  2815. if (funcInfo->superCtorRegister != Js::Constants::NoRegister)
  2816. {
  2817. cacheId = funcInfo->FindOrAddInlineCacheId(bodyScope->GetLocation(), Js::PropertyIds::_superCtorReferenceSymbol, false, true);
  2818. m_writer.ElementP(Js::OpCode::InitLocalFld, funcInfo->superCtorRegister, cacheId);
  2819. }
  2820. }
  2821. else if (funcInfo->superScopeSlot == Js::Constants::NoProperty || funcInfo->superCtorScopeSlot == Js::Constants::NoProperty)
  2822. {
  2823. // While the diag locals walker will pick up super from scoped slots or an activation object,
  2824. // it will not pick it up when it is only in a register.
  2825. byteCodeFunction->InsertSymbolToRegSlotList(funcInfo->superRegister, Js::PropertyIds::_superReferenceSymbol, funcInfo->varRegsCount);
  2826. if (funcInfo->superCtorRegister != Js::Constants::NoRegister)
  2827. {
  2828. byteCodeFunction->InsertSymbolToRegSlotList(funcInfo->superCtorRegister, Js::PropertyIds::_superCtorReferenceSymbol, funcInfo->varRegsCount);
  2829. }
  2830. }
  2831. }
  2832. }
  2833. }
  2834. if (funcInfo->newTargetScopeSlot != Js::Constants::NoRegister && !funcInfo->IsGlobalFunction())
  2835. {
  2836. EmitInitCapturedNewTarget(funcInfo, bodyScope);
  2837. }
  2838. // We don't want to load super if we are already in an eval. ScopedLdHomeObj will take care of loading super in that case.
  2839. if (!(GetFlags() & fscrEval) && !bodyScope->GetIsObject())
  2840. {
  2841. if (funcInfo->superScopeSlot != Js::Constants::NoRegister)
  2842. {
  2843. this->EmitInternalScopedSlotStore(funcInfo, funcInfo->superScopeSlot, funcInfo->superRegister);
  2844. }
  2845. if (funcInfo->superCtorScopeSlot != Js::Constants::NoRegister)
  2846. {
  2847. this->EmitInternalScopedSlotStore(funcInfo, funcInfo->superCtorScopeSlot, funcInfo->superCtorRegister);
  2848. }
  2849. }
  2850. if (byteCodeFunction->DoStackNestedFunc())
  2851. {
  2852. uint nestedCount = byteCodeFunction->GetNestedCount();
  2853. for (uint i = 0; i < nestedCount; i++)
  2854. {
  2855. Js::FunctionProxy * nested = byteCodeFunction->GetNestedFunctionProxy(i);
  2856. if (nested->IsFunctionBody())
  2857. {
  2858. nested->GetFunctionBody()->SetStackNestedFuncParent(byteCodeFunction->GetFunctionInfo());
  2859. }
  2860. }
  2861. }
  2862. if (funcInfo->IsGlobalFunction())
  2863. {
  2864. EnsureNoRedeclarations(pnode->sxFnc.pnodeScopes, funcInfo);
  2865. }
  2866. ::BeginEmitBlock(pnode->sxFnc.pnodeScopes, this, funcInfo);
  2867. DefineLabels(funcInfo);
  2868. if (pnode->sxFnc.HasNonSimpleParameterList())
  2869. {
  2870. this->InitBlockScopedNonTemps(funcInfo->root->sxFnc.pnodeScopes, funcInfo);
  2871. EmitDefaultArgs(funcInfo, pnode);
  2872. if (!currentScope->GetCanMergeWithBodyScope())
  2873. {
  2874. Assert(this->GetCurrentScope() == paramScope);
  2875. // Push the body scope
  2876. PushScope(bodyScope);
  2877. funcInfo->SetCurrentChildScope(bodyScope);
  2878. // Mark the beginning of the body scope so that new scope slots can be created.
  2879. this->Writer()->Empty(Js::OpCode::BeginBodyScope);
  2880. }
  2881. }
  2882. InitSpecialScopeSlots(funcInfo);
  2883. // Emit all scope-wide function definitions before emitting function bodies
  2884. // so that calls may reference functions they precede lexically.
  2885. // Note, global eval scope is a fake local scope and is handled as if it were
  2886. // a lexical block instead of a true global scope, so do not define the functions
  2887. // here. They will be defined during BeginEmitBlock.
  2888. if (!(funcInfo->IsGlobalFunction() && this->IsEvalWithNoParentScopeInfo()))
  2889. {
  2890. // This only handles function declarations, which param scope cannot have any.
  2891. DefineFunctions(funcInfo);
  2892. }
  2893. DefineUserVars(funcInfo);
  2894. if (pnode->sxFnc.HasNonSimpleParameterList())
  2895. {
  2896. this->InitBlockScopedNonTemps(funcInfo->root->sxFnc.pnodeBodyScope, funcInfo);
  2897. }
  2898. else
  2899. {
  2900. this->InitBlockScopedNonTemps(funcInfo->root->sxFnc.pnodeScopes, funcInfo);
  2901. }
  2902. if (!pnode->sxFnc.HasNonSimpleParameterList() && funcInfo->GetHasArguments() && !NeedScopeObjectForArguments(funcInfo, pnode))
  2903. {
  2904. // If we didn't create a scope object and didn't have default args, we still need to transfer the formals to their slots.
  2905. MapFormalsWithoutRest(pnode, [&](ParseNode *pnodeArg) { EmitPropStore(pnodeArg->sxVar.sym->GetLocation(), pnodeArg->sxVar.sym, pnodeArg->sxVar.pid, funcInfo); });
  2906. }
  2907. // Rest needs to trigger use before declaration until all default args have been processed.
  2908. if (pnode->sxFnc.pnodeRest != nullptr)
  2909. {
  2910. pnode->sxFnc.pnodeRest->sxVar.sym->SetNeedDeclaration(false);
  2911. }
  2912. if (paramScope && !paramScope->GetCanMergeWithBodyScope())
  2913. {
  2914. // Emit bytecode to copy the initial values from param names to their corresponding body bindings.
  2915. // We have to do this after the rest param is marked as false for need declaration.
  2916. paramScope->ForEachSymbol([&](Symbol* param) {
  2917. Symbol* varSym = funcInfo->GetBodyScope()->FindLocalSymbol(param->GetName());
  2918. Assert(varSym || pnode->sxFnc.pnodeName->sxVar.sym == param);
  2919. Assert(param->GetIsArguments() || param->IsInSlot(funcInfo));
  2920. if (param->GetIsArguments() && !funcInfo->GetHasArguments())
  2921. {
  2922. // Do not copy the arguments to the body if it is not used
  2923. }
  2924. else if (varSym && varSym->GetSymbolType() == STVariable && (varSym->IsInSlot(funcInfo) || varSym->GetLocation() != Js::Constants::NoRegister))
  2925. {
  2926. // Simulating EmitPropLoad here. We can't directly call the method as we have to use the param scope specifically.
  2927. // Walking the scope chain is not possible at this time.
  2928. Js::RegSlot tempReg = funcInfo->AcquireTmpRegister();
  2929. Js::PropertyId slot = param->EnsureScopeSlot(funcInfo);
  2930. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(paramScope, slot);
  2931. Js::OpCode op = paramScope->GetIsObject() ? Js::OpCode::LdParamObjSlot : Js::OpCode::LdParamSlot;
  2932. slot = slot + (paramScope->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  2933. this->m_writer.SlotI1(op, tempReg, slot, profileId);
  2934. if (ShouldTrackDebuggerMetadata() && !varSym->GetIsArguments() && !varSym->IsInSlot(funcInfo))
  2935. {
  2936. byteCodeFunction->InsertSymbolToRegSlotList(varSym->GetName(), varSym->GetLocation(), funcInfo->varRegsCount);
  2937. }
  2938. this->EmitPropStore(tempReg, varSym, varSym->GetPid(), funcInfo);
  2939. funcInfo->ReleaseTmpRegister(tempReg);
  2940. }
  2941. });
  2942. // In split scope as the body has a separate closure we have to copy the value of this and other special slots
  2943. // from param scope to the body scope
  2944. auto copySpecialSymbolsToBody = [this, funcInfo, paramScope] (Js::PropertyId src, Js::PropertyId dest)
  2945. {
  2946. if (dest != Js::Constants::NoProperty)
  2947. {
  2948. Js::RegSlot tempReg = funcInfo->AcquireTmpRegister();
  2949. Js::PropertyId slot = src;
  2950. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(paramScope, slot);
  2951. Js::OpCode op = paramScope->GetIsObject() ? Js::OpCode::LdParamObjSlot : Js::OpCode::LdParamSlot;
  2952. slot = slot + (paramScope->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  2953. this->m_writer.SlotI1(op, tempReg, slot, profileId);
  2954. op = funcInfo->bodyScope->GetIsObject() ? Js::OpCode::StLocalObjSlot : Js::OpCode::StLocalSlot;
  2955. slot = dest + (funcInfo->bodyScope->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  2956. this->m_writer.SlotI1(op, tempReg, slot);
  2957. funcInfo->ReleaseTmpRegister(tempReg);
  2958. }
  2959. };
  2960. copySpecialSymbolsToBody(funcInfo->innerThisScopeSlot, funcInfo->thisScopeSlot);
  2961. copySpecialSymbolsToBody(funcInfo->innerSuperScopeSlot, funcInfo->superScopeSlot);
  2962. copySpecialSymbolsToBody(funcInfo->innerSuperCtorScopeSlot, funcInfo->superCtorScopeSlot);
  2963. copySpecialSymbolsToBody(funcInfo->innerNewTargetScopeSlot, funcInfo->newTargetScopeSlot);
  2964. }
  2965. if (pnode->sxFnc.pnodeBodyScope != nullptr)
  2966. {
  2967. ::BeginEmitBlock(pnode->sxFnc.pnodeBodyScope, this, funcInfo);
  2968. }
  2969. this->inPrologue = false;
  2970. if (funcInfo->IsGlobalFunction())
  2971. {
  2972. EmitGlobalBody(funcInfo);
  2973. }
  2974. else
  2975. {
  2976. EmitFunctionBody(funcInfo);
  2977. }
  2978. if (pnode->sxFnc.pnodeBodyScope != nullptr)
  2979. {
  2980. ::EndEmitBlock(pnode->sxFnc.pnodeBodyScope, this, funcInfo);
  2981. }
  2982. ::EndEmitBlock(pnode->sxFnc.pnodeScopes, this, funcInfo);
  2983. if (!this->IsInDebugMode())
  2984. {
  2985. // Release the temp registers that we reserved for inner scopes above.
  2986. if (innerScopeCount)
  2987. {
  2988. Js::RegSlot tmpReg = funcInfo->FirstInnerScopeReg() + innerScopeCount - 1;
  2989. for (uint i = 0; i < innerScopeCount; i++)
  2990. {
  2991. funcInfo->ReleaseTmpRegister(tmpReg);
  2992. tmpReg--;
  2993. }
  2994. }
  2995. }
  2996. Assert(funcInfo->firstTmpReg == firstTmpReg);
  2997. Assert(funcInfo->curTmpReg == firstTmpReg);
  2998. Assert(byteCodeFunction->GetFirstTmpReg() == firstTmpReg + byteCodeFunction->GetConstantCount());
  2999. byteCodeFunction->CheckAndSetVarCount(funcInfo->varRegsCount);
  3000. byteCodeFunction->CheckAndSetOutParamMaxDepth(funcInfo->outArgsMaxDepth);
  3001. byteCodeFunction->SetForInLoopDepth(funcInfo->GetMaxForInLoopLevel());
  3002. // Do a uint32 add just to verify that we haven't overflowed the reg slot type.
  3003. UInt32Math::Add(funcInfo->varRegsCount, funcInfo->constRegsCount);
  3004. #if DBG_DUMP
  3005. if (PHASE_STATS1(Js::ByteCodePhase))
  3006. {
  3007. Output::Print(_u(" BCode: %-10d, Aux: %-10d, AuxC: %-10d Total: %-10d, %s\n"),
  3008. m_writer.ByteCodeDataSize(),
  3009. m_writer.AuxiliaryDataSize(),
  3010. m_writer.AuxiliaryContextDataSize(),
  3011. m_writer.ByteCodeDataSize() + m_writer.AuxiliaryDataSize() + m_writer.AuxiliaryContextDataSize(),
  3012. funcInfo->name);
  3013. this->scriptContext->byteCodeDataSize += m_writer.ByteCodeDataSize();
  3014. this->scriptContext->byteCodeAuxiliaryDataSize += m_writer.AuxiliaryDataSize();
  3015. this->scriptContext->byteCodeAuxiliaryContextDataSize += m_writer.AuxiliaryContextDataSize();
  3016. }
  3017. #endif
  3018. this->MapCacheIdsToPropertyIds(funcInfo);
  3019. this->MapReferencedPropertyIds(funcInfo);
  3020. Assert(this->TopFuncInfo() == funcInfo);
  3021. PopFuncInfo(_u("EmitOneFunction"));
  3022. m_writer.SetCallSiteCount(m_callSiteId);
  3023. #ifdef LOG_BYTECODE_AST_RATIO
  3024. m_writer.End(funcInfo->root->sxFnc.astSize, this->maxAstSize);
  3025. #else
  3026. m_writer.End();
  3027. #endif
  3028. }
  3029. catch (...)
  3030. {
  3031. // Failed to generate byte-code for this function body (likely OOM or stack overflow). Notify the function body so that
  3032. // it can revert intermediate state changes that may have taken place during byte code generation before the failure.
  3033. byteCodeFunction->ResetByteCodeGenState();
  3034. m_writer.Reset();
  3035. throw;
  3036. }
  3037. #ifdef PERF_HINT
  3038. if (PHASE_TRACE1(Js::PerfHintPhase) && !byteCodeFunction->GetIsGlobalFunc())
  3039. {
  3040. if (byteCodeFunction->GetHasTry())
  3041. {
  3042. WritePerfHint(PerfHints::HasTryBlock_Verbose, byteCodeFunction);
  3043. }
  3044. if (funcInfo->GetCallsEval())
  3045. {
  3046. WritePerfHint(PerfHints::CallsEval_Verbose, byteCodeFunction);
  3047. }
  3048. else if (funcInfo->GetChildCallsEval())
  3049. {
  3050. WritePerfHint(PerfHints::ChildCallsEval, byteCodeFunction);
  3051. }
  3052. }
  3053. #endif
  3054. byteCodeFunction->SetInitialDefaultEntryPoint();
  3055. byteCodeFunction->SetCompileCount(UInt32Math::Add(byteCodeFunction->GetCompileCount(), 1));
  3056. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  3057. if (byteCodeFunction->IsInDebugMode() != scriptContext->IsScriptContextInDebugMode()) // debug mode mismatch
  3058. {
  3059. if (m_utf8SourceInfo->GetIsLibraryCode())
  3060. {
  3061. Assert(!byteCodeFunction->IsInDebugMode()); // Library script byteCode is never in debug mode
  3062. }
  3063. else
  3064. {
  3065. Js::Throw::FatalInternalError();
  3066. }
  3067. }
  3068. #endif
  3069. #if DBG_DUMP
  3070. if (PHASE_DUMP(Js::ByteCodePhase, funcInfo->byteCodeFunction) && Js::Configuration::Global.flags.Verbose)
  3071. {
  3072. pnode->Dump();
  3073. }
  3074. if (this->Trace() || PHASE_DUMP(Js::ByteCodePhase, funcInfo->byteCodeFunction))
  3075. {
  3076. Js::ByteCodeDumper::Dump(byteCodeFunction);
  3077. }
  3078. if (PHASE_DUMP(Js::DebuggerScopePhase, funcInfo->byteCodeFunction))
  3079. {
  3080. byteCodeFunction->DumpScopes();
  3081. }
  3082. #endif
  3083. #if ENABLE_NATIVE_CODEGEN
  3084. if ((!PHASE_OFF(Js::BackEndPhase, funcInfo->byteCodeFunction))
  3085. && !this->forceNoNative
  3086. && !this->scriptContext->GetConfig()->IsNoNative())
  3087. {
  3088. GenerateFunction(this->scriptContext->GetNativeCodeGenerator(), byteCodeFunction);
  3089. }
  3090. #endif
  3091. }
  3092. void ByteCodeGenerator::MapCacheIdsToPropertyIds(FuncInfo *funcInfo)
  3093. {
  3094. Js::FunctionBody *functionBody = funcInfo->GetParsedFunctionBody();
  3095. uint rootObjectLoadInlineCacheStart = funcInfo->GetInlineCacheCount();
  3096. uint rootObjectLoadMethodInlineCacheStart = rootObjectLoadInlineCacheStart + funcInfo->GetRootObjectLoadInlineCacheCount();
  3097. uint rootObjectStoreInlineCacheStart = rootObjectLoadMethodInlineCacheStart + funcInfo->GetRootObjectLoadMethodInlineCacheCount();
  3098. uint totalFieldAccessInlineCacheCount = rootObjectStoreInlineCacheStart + funcInfo->GetRootObjectStoreInlineCacheCount();
  3099. functionBody->CreateCacheIdToPropertyIdMap(rootObjectLoadInlineCacheStart, rootObjectLoadMethodInlineCacheStart,
  3100. rootObjectStoreInlineCacheStart, totalFieldAccessInlineCacheCount, funcInfo->GetIsInstInlineCacheCount());
  3101. if (totalFieldAccessInlineCacheCount == 0)
  3102. {
  3103. return;
  3104. }
  3105. funcInfo->inlineCacheMap->Map([functionBody](Js::RegSlot regSlot, FuncInfo::InlineCacheIdMap *inlineCacheIdMap)
  3106. {
  3107. inlineCacheIdMap->Map([functionBody](Js::PropertyId propertyId, FuncInfo::InlineCacheList* inlineCacheList)
  3108. {
  3109. if (inlineCacheList)
  3110. {
  3111. inlineCacheList->Iterate([functionBody, propertyId](InlineCacheUnit cacheUnit)
  3112. {
  3113. CompileAssert(offsetof(InlineCacheUnit, cacheId) == offsetof(InlineCacheUnit, loadCacheId));
  3114. if (cacheUnit.loadCacheId != -1)
  3115. {
  3116. functionBody->SetPropertyIdForCacheId(cacheUnit.loadCacheId, propertyId);
  3117. }
  3118. if (cacheUnit.loadMethodCacheId != -1)
  3119. {
  3120. functionBody->SetPropertyIdForCacheId(cacheUnit.loadMethodCacheId, propertyId);
  3121. }
  3122. if (cacheUnit.storeCacheId != -1)
  3123. {
  3124. functionBody->SetPropertyIdForCacheId(cacheUnit.storeCacheId, propertyId);
  3125. }
  3126. });
  3127. }
  3128. });
  3129. });
  3130. funcInfo->rootObjectLoadInlineCacheMap->Map([functionBody, rootObjectLoadInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  3131. {
  3132. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectLoadInlineCacheStart, propertyId);
  3133. });
  3134. funcInfo->rootObjectLoadMethodInlineCacheMap->Map([functionBody, rootObjectLoadMethodInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  3135. {
  3136. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectLoadMethodInlineCacheStart, propertyId);
  3137. });
  3138. funcInfo->rootObjectStoreInlineCacheMap->Map([functionBody, rootObjectStoreInlineCacheStart](Js::PropertyId propertyId, uint cacheId)
  3139. {
  3140. functionBody->SetPropertyIdForCacheId(cacheId + rootObjectStoreInlineCacheStart, propertyId);
  3141. });
  3142. SListBase<uint>::Iterator valueOfIter(&funcInfo->valueOfStoreCacheIds);
  3143. while (valueOfIter.Next())
  3144. {
  3145. functionBody->SetPropertyIdForCacheId(valueOfIter.Data(), Js::PropertyIds::valueOf);
  3146. }
  3147. SListBase<uint>::Iterator toStringIter(&funcInfo->toStringStoreCacheIds);
  3148. while (toStringIter.Next())
  3149. {
  3150. functionBody->SetPropertyIdForCacheId(toStringIter.Data(), Js::PropertyIds::toString);
  3151. }
  3152. #if DBG
  3153. functionBody->VerifyCacheIdToPropertyIdMap();
  3154. #endif
  3155. }
  3156. void ByteCodeGenerator::MapReferencedPropertyIds(FuncInfo * funcInfo)
  3157. {
  3158. Js::FunctionBody *functionBody = funcInfo->GetParsedFunctionBody();
  3159. uint referencedPropertyIdCount = funcInfo->GetReferencedPropertyIdCount();
  3160. functionBody->CreateReferencedPropertyIdMap(referencedPropertyIdCount);
  3161. funcInfo->referencedPropertyIdToMapIndex->Map([functionBody](Js::PropertyId propertyId, uint mapIndex)
  3162. {
  3163. functionBody->SetReferencedPropertyIdWithMapIndex(mapIndex, propertyId);
  3164. });
  3165. #if DBG
  3166. functionBody->VerifyReferencedPropertyIdMap();
  3167. #endif
  3168. }
  3169. void ByteCodeGenerator::EmitScopeList(ParseNode *pnode, ParseNode *breakOnBodyScopeNode)
  3170. {
  3171. while (pnode)
  3172. {
  3173. if (breakOnBodyScopeNode != nullptr && breakOnBodyScopeNode == pnode)
  3174. {
  3175. break;
  3176. }
  3177. switch (pnode->nop)
  3178. {
  3179. case knopFncDecl:
  3180. #ifdef ASMJS_PLAT
  3181. if (pnode->sxFnc.GetAsmjsMode())
  3182. {
  3183. Js::ExclusiveContext context(this, GetScriptContext());
  3184. if (Js::AsmJSCompiler::Compile(&context, pnode, pnode->sxFnc.pnodeParams))
  3185. {
  3186. pnode = pnode->sxFnc.pnodeNext;
  3187. break;
  3188. }
  3189. else if (CONFIG_FLAG(AsmJsStopOnError))
  3190. {
  3191. exit(JSERR_AsmJsCompileError);
  3192. }
  3193. else if (!(flags & fscrDeferFncParse))
  3194. {
  3195. // If deferral is not allowed, throw and reparse everything with asm.js disabled.
  3196. throw Js::AsmJsParseException();
  3197. }
  3198. }
  3199. #endif
  3200. // FALLTHROUGH
  3201. case knopProg:
  3202. if (pnode->sxFnc.funcInfo)
  3203. {
  3204. FuncInfo* funcInfo = pnode->sxFnc.funcInfo;
  3205. Scope* paramScope = funcInfo->GetParamScope();
  3206. if (paramScope && !paramScope->GetCanMergeWithBodyScope())
  3207. {
  3208. funcInfo->SetCurrentChildScope(paramScope);
  3209. }
  3210. else
  3211. {
  3212. funcInfo->SetCurrentChildScope(funcInfo->GetBodyScope());
  3213. }
  3214. this->StartEmitFunction(pnode);
  3215. // Persist outer func scope info if nested func is deferred
  3216. if (CONFIG_FLAG(DeferNested))
  3217. {
  3218. FuncInfo* parentFunc = TopFuncInfo();
  3219. Js::ScopeInfo::SaveScopeInfoForDeferParse(this, parentFunc, funcInfo);
  3220. PushFuncInfo(_u("StartEmitFunction"), funcInfo);
  3221. }
  3222. if (paramScope && !paramScope->GetCanMergeWithBodyScope())
  3223. {
  3224. // Before emitting the body scoped functions let us switch the special scope slot to use the body ones
  3225. pnode->sxFnc.funcInfo->UseInnerSpecialScopeSlots();
  3226. this->EmitScopeList(pnode->sxFnc.pnodeBodyScope->sxBlock.pnodeScopes);
  3227. }
  3228. else
  3229. {
  3230. this->EmitScopeList(pnode->sxFnc.pnodeScopes);
  3231. }
  3232. this->EmitOneFunction(pnode);
  3233. this->EndEmitFunction(pnode);
  3234. Assert(pnode->sxFnc.pnodeBody == nullptr || funcInfo->isReused || funcInfo->GetCurrentChildScope() == funcInfo->GetBodyScope());
  3235. funcInfo->SetCurrentChildScope(nullptr);
  3236. }
  3237. pnode = pnode->sxFnc.pnodeNext;
  3238. break;
  3239. case knopBlock:
  3240. this->StartEmitBlock(pnode);
  3241. this->EmitScopeList(pnode->sxBlock.pnodeScopes);
  3242. this->EndEmitBlock(pnode);
  3243. pnode = pnode->sxBlock.pnodeNext;
  3244. break;
  3245. case knopCatch:
  3246. this->StartEmitCatch(pnode);
  3247. this->EmitScopeList(pnode->sxCatch.pnodeScopes);
  3248. this->EndEmitCatch(pnode);
  3249. pnode = pnode->sxCatch.pnodeNext;
  3250. break;
  3251. case knopWith:
  3252. this->StartEmitWith(pnode);
  3253. this->EmitScopeList(pnode->sxWith.pnodeScopes);
  3254. this->EndEmitWith(pnode);
  3255. pnode = pnode->sxWith.pnodeNext;
  3256. break;
  3257. default:
  3258. AssertMsg(false, "Unexpected opcode in tree of scopes");
  3259. break;
  3260. }
  3261. }
  3262. }
  3263. void EnsureFncDeclScopeSlot(ParseNode *pnodeFnc, FuncInfo *funcInfo)
  3264. {
  3265. if (pnodeFnc->sxFnc.pnodeName)
  3266. {
  3267. Assert(pnodeFnc->sxFnc.pnodeName->nop == knopVarDecl);
  3268. Symbol *sym = pnodeFnc->sxFnc.pnodeName->sxVar.sym;
  3269. // If this function is shadowing the arguments symbol in body then skip it.
  3270. // We will allocate scope slot for the arguments symbol during EmitLocalPropInit.
  3271. if (sym && !sym->GetIsArguments())
  3272. {
  3273. sym->EnsureScopeSlot(funcInfo);
  3274. }
  3275. }
  3276. }
  3277. // Similar to EnsureFncScopeSlot visitor function, but verifies that a slot is needed before assigning it.
  3278. void CheckFncDeclScopeSlot(ParseNode *pnodeFnc, FuncInfo *funcInfo)
  3279. {
  3280. if (pnodeFnc->sxFnc.pnodeName && pnodeFnc->sxFnc.pnodeName->nop == knopVarDecl)
  3281. {
  3282. Assert(pnodeFnc->sxFnc.pnodeName->nop == knopVarDecl);
  3283. Symbol *sym = pnodeFnc->sxFnc.pnodeName->sxVar.sym;
  3284. if (sym && sym->NeedsSlotAlloc(funcInfo))
  3285. {
  3286. sym->EnsureScopeSlot(funcInfo);
  3287. }
  3288. }
  3289. }
  3290. void ByteCodeGenerator::EnsureSpecialScopeSlots(FuncInfo* funcInfo, Scope* scope)
  3291. {
  3292. if (scope->GetIsObject())
  3293. {
  3294. if (funcInfo->isThisLexicallyCaptured)
  3295. {
  3296. funcInfo->EnsureThisScopeSlot();
  3297. }
  3298. if (((!funcInfo->IsLambda() && funcInfo->GetCallsEval())
  3299. || funcInfo->isSuperLexicallyCaptured))
  3300. {
  3301. if (funcInfo->superRegister != Js::Constants::NoRegister)
  3302. {
  3303. funcInfo->EnsureSuperScopeSlot();
  3304. }
  3305. if (funcInfo->superCtorRegister != Js::Constants::NoRegister)
  3306. {
  3307. funcInfo->EnsureSuperCtorScopeSlot();
  3308. }
  3309. }
  3310. if (funcInfo->isNewTargetLexicallyCaptured)
  3311. {
  3312. funcInfo->EnsureNewTargetScopeSlot();
  3313. }
  3314. }
  3315. else
  3316. {
  3317. // Don't rely on the Emit() pass to assign scope slots where needed, because peeps/shortcuts
  3318. // may cause some expressions not to be emitted. Assign the slots we need before we start
  3319. // emitting the prolog.
  3320. // TODO: Investigate moving detection of non-local references to Emit() so we don't assign
  3321. // slots to symbols that are never referenced in emitted code.
  3322. if (funcInfo->isThisLexicallyCaptured)
  3323. {
  3324. funcInfo->EnsureThisScopeSlot();
  3325. }
  3326. if (funcInfo->isSuperLexicallyCaptured)
  3327. {
  3328. funcInfo->EnsureSuperScopeSlot();
  3329. }
  3330. if (funcInfo->isSuperCtorLexicallyCaptured)
  3331. {
  3332. funcInfo->EnsureSuperCtorScopeSlot();
  3333. }
  3334. if (funcInfo->isNewTargetLexicallyCaptured)
  3335. {
  3336. funcInfo->EnsureNewTargetScopeSlot();
  3337. }
  3338. }
  3339. }
  3340. void ByteCodeGenerator::InitSpecialScopeSlots(FuncInfo* funcInfo)
  3341. {
  3342. if (funcInfo->bodyScope->GetIsObject())
  3343. {
  3344. // In split scope make sure to do init fld for the duplicate special scope slots
  3345. if (funcInfo->innerThisScopeSlot != Js::Constants::NoProperty)
  3346. {
  3347. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->bodyScope->GetLocation(), Js::PropertyIds::_lexicalThisSlotSymbol, false, true);
  3348. m_writer.ElementP(Js::OpCode::InitLocalFld, funcInfo->thisPointerRegister, cacheId);
  3349. }
  3350. if (funcInfo->innerSuperScopeSlot != Js::Constants::NoProperty)
  3351. {
  3352. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->bodyScope->GetLocation(), Js::PropertyIds::_superReferenceSymbol, false, true);
  3353. m_writer.ElementP(Js::OpCode::InitLocalFld, funcInfo->superRegister, cacheId);
  3354. }
  3355. if (funcInfo->innerSuperCtorScopeSlot != Js::Constants::NoProperty)
  3356. {
  3357. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->bodyScope->GetLocation(), Js::PropertyIds::_superCtorReferenceSymbol, false, true);
  3358. m_writer.ElementP(Js::OpCode::InitLocalFld, funcInfo->superCtorRegister, cacheId);
  3359. }
  3360. if (funcInfo->innerNewTargetScopeSlot != Js::Constants::NoProperty)
  3361. {
  3362. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->bodyScope->GetLocation(), Js::PropertyIds::_lexicalNewTargetSymbol, false, true);
  3363. m_writer.ElementP(Js::OpCode::InitLocalFld, funcInfo->newTargetRegister, cacheId);
  3364. }
  3365. }
  3366. }
  3367. void ByteCodeGenerator::StartEmitFunction(ParseNode *pnodeFnc)
  3368. {
  3369. Assert(pnodeFnc->nop == knopFncDecl || pnodeFnc->nop == knopProg);
  3370. FuncInfo *funcInfo = pnodeFnc->sxFnc.funcInfo;
  3371. if (funcInfo->byteCodeFunction->IsFunctionParsed())
  3372. {
  3373. if (!(flags & (fscrEval | fscrImplicitThis | fscrImplicitParents)))
  3374. {
  3375. // Only set the environment depth if it's truly known (i.e., not in eval or event handler).
  3376. funcInfo->GetParsedFunctionBody()->SetEnvDepth(this->envDepth);
  3377. }
  3378. if (pnodeFnc->sxFnc.FIBPreventsDeferral())
  3379. {
  3380. for (Scope *scope = this->currentScope; scope; scope = scope->GetEnclosingScope())
  3381. {
  3382. if (scope->GetScopeType() != ScopeType_FunctionBody &&
  3383. scope->GetScopeType() != ScopeType_Global &&
  3384. scope->GetScopeType() != ScopeType_GlobalEvalBlock &&
  3385. scope->GetMustInstantiate())
  3386. {
  3387. funcInfo->byteCodeFunction->SetAttributes((Js::FunctionInfo::Attributes)(funcInfo->byteCodeFunction->GetAttributes() & ~Js::FunctionInfo::Attributes::CanDefer));
  3388. break;
  3389. }
  3390. }
  3391. }
  3392. }
  3393. if (funcInfo->GetCallsEval())
  3394. {
  3395. funcInfo->byteCodeFunction->SetDontInline(true);
  3396. }
  3397. Scope * const funcExprScope = funcInfo->funcExprScope;
  3398. if (funcExprScope)
  3399. {
  3400. if (funcInfo->GetCallsEval())
  3401. {
  3402. Assert(funcExprScope->GetIsObject());
  3403. }
  3404. if (funcExprScope->GetIsObject())
  3405. {
  3406. funcExprScope->SetCapturesAll(true);
  3407. funcExprScope->SetMustInstantiate(true);
  3408. PushScope(funcExprScope);
  3409. }
  3410. else
  3411. {
  3412. Symbol *sym = funcInfo->root->sxFnc.GetFuncSymbol();
  3413. if (funcInfo->paramScope->GetCanMergeWithBodyScope())
  3414. {
  3415. funcInfo->bodyScope->AddSymbol(sym);
  3416. }
  3417. else
  3418. {
  3419. funcInfo->paramScope->AddSymbol(sym);
  3420. }
  3421. sym->EnsureScopeSlot(funcInfo);
  3422. }
  3423. }
  3424. Scope * const bodyScope = funcInfo->GetBodyScope();
  3425. Scope * const paramScope = funcInfo->GetParamScope();
  3426. if (pnodeFnc->nop != knopProg)
  3427. {
  3428. if (!bodyScope->GetIsObject() && NeedObjectAsFunctionScope(funcInfo, pnodeFnc))
  3429. {
  3430. Assert(bodyScope->GetIsObject());
  3431. }
  3432. if (bodyScope->GetIsObject())
  3433. {
  3434. bodyScope->SetLocation(funcInfo->frameObjRegister);
  3435. }
  3436. else
  3437. {
  3438. bodyScope->SetLocation(funcInfo->frameSlotsRegister);
  3439. }
  3440. if (!paramScope->GetCanMergeWithBodyScope())
  3441. {
  3442. if (paramScope->GetIsObject())
  3443. {
  3444. paramScope->SetLocation(funcInfo->frameObjRegister);
  3445. }
  3446. else
  3447. {
  3448. paramScope->SetLocation(funcInfo->frameSlotsRegister);
  3449. }
  3450. }
  3451. if (bodyScope->GetIsObject())
  3452. {
  3453. // Win8 908700: Disable under F12 debugger because there are too many cached scopes holding onto locals.
  3454. funcInfo->SetHasCachedScope(
  3455. !PHASE_OFF(Js::CachedScopePhase, funcInfo->byteCodeFunction) &&
  3456. !funcInfo->Escapes() &&
  3457. funcInfo->frameObjRegister != Js::Constants::NoRegister &&
  3458. !ApplyEnclosesArgs(pnodeFnc, this) &&
  3459. funcInfo->paramScope->GetCanMergeWithBodyScope() && // There is eval in the param scope
  3460. (PHASE_FORCE(Js::CachedScopePhase, funcInfo->byteCodeFunction) || !IsInDebugMode())
  3461. #if ENABLE_TTD
  3462. && !funcInfo->GetParsedFunctionBody()->GetScriptContext()->GetThreadContext()->IsRuntimeInTTDMode()
  3463. #endif
  3464. );
  3465. if (funcInfo->GetHasCachedScope())
  3466. {
  3467. Assert(funcInfo->funcObjRegister == Js::Constants::NoRegister);
  3468. Symbol *funcSym = funcInfo->root->sxFnc.GetFuncSymbol();
  3469. if (funcSym && funcSym->GetIsFuncExpr())
  3470. {
  3471. if (funcSym->GetLocation() == Js::Constants::NoRegister)
  3472. {
  3473. funcInfo->funcObjRegister = funcInfo->NextVarRegister();
  3474. }
  3475. else
  3476. {
  3477. funcInfo->funcObjRegister = funcSym->GetLocation();
  3478. }
  3479. }
  3480. else
  3481. {
  3482. funcInfo->funcObjRegister = funcInfo->NextVarRegister();
  3483. }
  3484. Assert(funcInfo->funcObjRegister != Js::Constants::NoRegister);
  3485. }
  3486. ParseNode *pnode;
  3487. Symbol *sym;
  3488. if (funcInfo->GetHasArguments())
  3489. {
  3490. // Process function's formal parameters
  3491. MapFormals(pnodeFnc, [&](ParseNode *pnode)
  3492. {
  3493. if (pnode->IsVarLetOrConst())
  3494. {
  3495. pnode->sxVar.sym->EnsureScopeSlot(funcInfo);
  3496. }
  3497. });
  3498. MapFormalsFromPattern(pnodeFnc, [&](ParseNode *pnode) { pnode->sxVar.sym->EnsureScopeSlot(funcInfo); });
  3499. // Only allocate scope slot for "arguments" when really necessary. "hasDeferredChild"
  3500. // doesn't require scope slot for "arguments" because inner functions can't access
  3501. // outer function's arguments directly.
  3502. sym = funcInfo->GetArgumentsSymbol();
  3503. Assert(sym);
  3504. if (sym->NeedsSlotAlloc(funcInfo))
  3505. {
  3506. sym->EnsureScopeSlot(funcInfo);
  3507. }
  3508. }
  3509. sym = funcInfo->root->sxFnc.GetFuncSymbol();
  3510. if (sym && sym->NeedsSlotAlloc(funcInfo))
  3511. {
  3512. if (funcInfo->funcExprScope && funcInfo->funcExprScope->GetIsObject())
  3513. {
  3514. sym->SetScopeSlot(0);
  3515. }
  3516. else if (funcInfo->GetFuncExprNameReference())
  3517. {
  3518. sym->EnsureScopeSlot(funcInfo);
  3519. }
  3520. }
  3521. if (!funcInfo->GetHasArguments())
  3522. {
  3523. Symbol *formal;
  3524. Js::ArgSlot pos = 1;
  3525. auto moveArgToReg = [&](ParseNode *pnode)
  3526. {
  3527. if (pnode->IsVarLetOrConst())
  3528. {
  3529. formal = pnode->sxVar.sym;
  3530. // Get the param from its argument position into its assigned register.
  3531. // The position should match the location; otherwise, it has been shadowed by parameter with the same name.
  3532. if (formal->GetLocation() + 1 == pos)
  3533. {
  3534. pnode->sxVar.sym->EnsureScopeSlot(funcInfo);
  3535. }
  3536. }
  3537. pos++;
  3538. };
  3539. MapFormals(pnodeFnc, moveArgToReg);
  3540. MapFormalsFromPattern(pnodeFnc, [&](ParseNode *pnode) { pnode->sxVar.sym->EnsureScopeSlot(funcInfo); });
  3541. }
  3542. this->EnsureSpecialScopeSlots(funcInfo, bodyScope);
  3543. auto ensureFncDeclScopeSlots = [&](ParseNode *pnodeScope)
  3544. {
  3545. for (pnode = pnodeScope; pnode;)
  3546. {
  3547. switch (pnode->nop)
  3548. {
  3549. case knopFncDecl:
  3550. if (pnode->sxFnc.IsDeclaration())
  3551. {
  3552. EnsureFncDeclScopeSlot(pnode, funcInfo);
  3553. }
  3554. pnode = pnode->sxFnc.pnodeNext;
  3555. break;
  3556. case knopBlock:
  3557. pnode = pnode->sxBlock.pnodeNext;
  3558. break;
  3559. case knopCatch:
  3560. pnode = pnode->sxCatch.pnodeNext;
  3561. break;
  3562. case knopWith:
  3563. pnode = pnode->sxWith.pnodeNext;
  3564. break;
  3565. }
  3566. }
  3567. };
  3568. pnodeFnc->sxFnc.MapContainerScopes(ensureFncDeclScopeSlots);
  3569. for (pnode = pnodeFnc->sxFnc.pnodeVars; pnode; pnode = pnode->sxVar.pnodeNext)
  3570. {
  3571. sym = pnode->sxVar.sym;
  3572. if (!(pnode->sxVar.isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  3573. {
  3574. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  3575. {
  3576. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  3577. }
  3578. if (sym->GetSymbolType() == STVariable && !sym->GetIsArguments()
  3579. && (!funcInfo->IsInnerArgumentsSymbol(sym) || funcInfo->GetHasArguments()))
  3580. {
  3581. sym->EnsureScopeSlot(funcInfo);
  3582. }
  3583. }
  3584. }
  3585. if (pnodeFnc->sxFnc.pnodeBody)
  3586. {
  3587. Assert(pnodeFnc->sxFnc.pnodeScopes->nop == knopBlock);
  3588. this->EnsureLetConstScopeSlots(pnodeFnc->sxFnc.pnodeBodyScope, funcInfo);
  3589. }
  3590. }
  3591. else
  3592. {
  3593. ParseNode *pnode;
  3594. Symbol *sym;
  3595. this->EnsureSpecialScopeSlots(funcInfo, bodyScope);
  3596. pnodeFnc->sxFnc.MapContainerScopes([&](ParseNode *pnodeScope) { this->EnsureFncScopeSlots(pnodeScope, funcInfo); });
  3597. for (pnode = pnodeFnc->sxFnc.pnodeVars; pnode; pnode = pnode->sxVar.pnodeNext)
  3598. {
  3599. sym = pnode->sxVar.sym;
  3600. if (!(pnode->sxVar.isBlockScopeFncDeclVar && sym->GetIsBlockVar()))
  3601. {
  3602. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  3603. {
  3604. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  3605. }
  3606. if (sym->GetSymbolType() == STVariable && sym->NeedsSlotAlloc(funcInfo) && !sym->GetIsArguments()
  3607. && (!funcInfo->IsInnerArgumentsSymbol(sym) || funcInfo->GetHasArguments()))
  3608. {
  3609. sym->EnsureScopeSlot(funcInfo);
  3610. }
  3611. }
  3612. }
  3613. auto ensureScopeSlot = [&](ParseNode *pnode)
  3614. {
  3615. if (pnode->IsVarLetOrConst())
  3616. {
  3617. sym = pnode->sxVar.sym;
  3618. if (sym->GetSymbolType() == STFormal && sym->NeedsSlotAlloc(funcInfo))
  3619. {
  3620. sym->EnsureScopeSlot(funcInfo);
  3621. }
  3622. }
  3623. };
  3624. // Process function's formal parameters
  3625. MapFormals(pnodeFnc, ensureScopeSlot);
  3626. MapFormalsFromPattern(pnodeFnc, ensureScopeSlot);
  3627. if (funcInfo->GetHasArguments())
  3628. {
  3629. sym = funcInfo->GetArgumentsSymbol();
  3630. Assert(sym);
  3631. // There is no eval so the arguments may be captured in a lambda.
  3632. // But we cannot relay on slots getting allocated while the lambda is emitted as the function body may be reparsed.
  3633. sym->EnsureScopeSlot(funcInfo);
  3634. }
  3635. if (pnodeFnc->sxFnc.pnodeBody)
  3636. {
  3637. this->EnsureLetConstScopeSlots(pnodeFnc->sxFnc.pnodeScopes, funcInfo);
  3638. this->EnsureLetConstScopeSlots(pnodeFnc->sxFnc.pnodeBodyScope, funcInfo);
  3639. }
  3640. }
  3641. if (!paramScope->GetCanMergeWithBodyScope() && bodyScope->GetScopeSlotCount() == 0 && !bodyScope->GetHasOwnLocalInClosure())
  3642. {
  3643. // When we have split scope the body scope may be wrongly marked as must instantiate even though the capture occurred
  3644. // in param scope. This check is to make sure if no capture occurs in body scope make in not must instantiate.
  3645. bodyScope->SetMustInstantiate(false);
  3646. }
  3647. else
  3648. {
  3649. bodyScope->SetMustInstantiate(funcInfo->frameObjRegister != Js::Constants::NoRegister || funcInfo->frameSlotsRegister != Js::Constants::NoRegister);
  3650. }
  3651. paramScope->SetMustInstantiate(!paramScope->GetCanMergeWithBodyScope());
  3652. }
  3653. else
  3654. {
  3655. bool newScopeForEval = (funcInfo->byteCodeFunction->GetIsStrictMode() && (this->GetFlags() & fscrEval));
  3656. if (newScopeForEval)
  3657. {
  3658. Assert(bodyScope->GetIsObject());
  3659. }
  3660. }
  3661. if (paramScope && !paramScope->GetCanMergeWithBodyScope())
  3662. {
  3663. ParseNodePtr paramBlock = pnodeFnc->sxFnc.pnodeScopes;
  3664. Assert(paramBlock->nop == knopBlock && paramBlock->sxBlock.blockType == Parameter);
  3665. PushScope(paramScope);
  3666. // While emitting the functions we have to stop when we see the body scope block.
  3667. // Otherwise functions defined in the body scope will not be able to get the right references.
  3668. this->EmitScopeList(paramBlock->sxBlock.pnodeScopes, pnodeFnc->sxFnc.pnodeBodyScope);
  3669. Assert(this->GetCurrentScope() == paramScope);
  3670. }
  3671. PushScope(bodyScope);
  3672. }
  3673. void ByteCodeGenerator::EmitModuleExportAccess(Symbol* sym, Js::OpCode opcode, Js::RegSlot location, FuncInfo* funcInfo)
  3674. {
  3675. if (EnsureSymbolModuleSlots(sym, funcInfo))
  3676. {
  3677. this->Writer()->SlotI2(opcode, location, sym->GetModuleIndex(), sym->GetScopeSlot());
  3678. }
  3679. else
  3680. {
  3681. this->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(ERRInvalidExportName));
  3682. if (opcode == Js::OpCode::LdModuleSlot)
  3683. {
  3684. this->Writer()->Reg1(Js::OpCode::LdUndef, location);
  3685. }
  3686. }
  3687. }
  3688. bool ByteCodeGenerator::EnsureSymbolModuleSlots(Symbol* sym, FuncInfo* funcInfo)
  3689. {
  3690. Assert(sym->GetIsModuleExportStorage());
  3691. if (sym->GetModuleIndex() != Js::Constants::NoProperty && sym->GetScopeSlot() != Js::Constants::NoProperty)
  3692. {
  3693. return true;
  3694. }
  3695. Js::JavascriptLibrary* library = this->GetScriptContext()->GetLibrary();
  3696. library->EnsureModuleRecordList();
  3697. uint moduleIndex = this->GetModuleID();
  3698. uint moduleSlotIndex;
  3699. Js::SourceTextModuleRecord* moduleRecord = library->GetModuleRecord(moduleIndex);
  3700. if (sym->GetIsModuleImport())
  3701. {
  3702. Js::PropertyId localImportNameId = sym->EnsurePosition(funcInfo);
  3703. Js::ModuleNameRecord* moduleNameRecord = nullptr;
  3704. if (!moduleRecord->ResolveImport(localImportNameId, &moduleNameRecord))
  3705. {
  3706. return false;
  3707. }
  3708. AnalysisAssert(moduleNameRecord != nullptr);
  3709. Assert(moduleNameRecord->module->IsSourceTextModuleRecord());
  3710. Js::SourceTextModuleRecord* resolvedModuleRecord = (Js::SourceTextModuleRecord*)moduleNameRecord->module;
  3711. moduleIndex = resolvedModuleRecord->GetModuleId();
  3712. moduleSlotIndex = resolvedModuleRecord->GetLocalExportSlotIndexByLocalName(moduleNameRecord->bindingName);
  3713. }
  3714. else
  3715. {
  3716. Js::PropertyId exportNameId = sym->EnsurePosition(funcInfo);
  3717. moduleSlotIndex = moduleRecord->GetLocalExportSlotIndexByLocalName(exportNameId);
  3718. }
  3719. sym->SetModuleIndex(moduleIndex);
  3720. sym->SetScopeSlot(moduleSlotIndex);
  3721. return true;
  3722. }
  3723. void ByteCodeGenerator::EmitAssignmentToDefaultModuleExport(ParseNode* pnode, FuncInfo* funcInfo)
  3724. {
  3725. // We are assigning pnode to the default export of the current module.
  3726. uint moduleIndex = this->GetModuleID();
  3727. Js::JavascriptLibrary* library = this->GetScriptContext()->GetLibrary();
  3728. library->EnsureModuleRecordList();
  3729. Js::SourceTextModuleRecord* moduleRecord = library->GetModuleRecord(moduleIndex);
  3730. uint moduleSlotIndex = moduleRecord->GetLocalExportSlotIndexByExportName(Js::PropertyIds::default_);
  3731. this->Writer()->SlotI2(Js::OpCode::StModuleSlot, pnode->location, moduleIndex, moduleSlotIndex);
  3732. }
  3733. void ByteCodeGenerator::EnsureLetConstScopeSlots(ParseNode *pnodeBlock, FuncInfo *funcInfo)
  3734. {
  3735. bool callsEval = pnodeBlock->sxBlock.GetCallsEval() || pnodeBlock->sxBlock.GetChildCallsEval();
  3736. auto ensureLetConstSlots = ([this, funcInfo, callsEval](ParseNode *pnode)
  3737. {
  3738. Symbol *sym = pnode->sxVar.sym;
  3739. if (callsEval || sym->NeedsSlotAlloc(funcInfo))
  3740. {
  3741. sym->EnsureScopeSlot(funcInfo);
  3742. this->ProcessCapturedSym(sym);
  3743. }
  3744. });
  3745. IterateBlockScopedVariables(pnodeBlock, ensureLetConstSlots);
  3746. }
  3747. void ByteCodeGenerator::EnsureFncScopeSlots(ParseNode *pnode, FuncInfo *funcInfo)
  3748. {
  3749. while (pnode)
  3750. {
  3751. switch (pnode->nop)
  3752. {
  3753. case knopFncDecl:
  3754. if (pnode->sxFnc.IsDeclaration())
  3755. {
  3756. CheckFncDeclScopeSlot(pnode, funcInfo);
  3757. }
  3758. pnode = pnode->sxFnc.pnodeNext;
  3759. break;
  3760. case knopBlock:
  3761. pnode = pnode->sxBlock.pnodeNext;
  3762. break;
  3763. case knopCatch:
  3764. pnode = pnode->sxCatch.pnodeNext;
  3765. break;
  3766. case knopWith:
  3767. pnode = pnode->sxWith.pnodeNext;
  3768. break;
  3769. }
  3770. }
  3771. }
  3772. void ByteCodeGenerator::EndEmitFunction(ParseNode *pnodeFnc)
  3773. {
  3774. Assert(pnodeFnc->nop == knopFncDecl || pnodeFnc->nop == knopProg);
  3775. Assert(pnodeFnc->nop == knopFncDecl && currentScope->GetEnclosingScope() != nullptr || pnodeFnc->nop == knopProg);
  3776. PopScope(); // function body
  3777. FuncInfo *funcInfo = pnodeFnc->sxFnc.funcInfo;
  3778. Scope* paramScope = funcInfo->paramScope;
  3779. if (paramScope && !paramScope->GetCanMergeWithBodyScope())
  3780. {
  3781. Assert(this->GetCurrentScope() == paramScope);
  3782. PopScope(); // Pop the param scope
  3783. }
  3784. Scope *scope = funcInfo->funcExprScope;
  3785. if (scope && scope->GetMustInstantiate())
  3786. {
  3787. Assert(currentScope == scope);
  3788. PopScope();
  3789. }
  3790. if (CONFIG_FLAG(DeferNested))
  3791. {
  3792. Assert(funcInfo == this->TopFuncInfo());
  3793. PopFuncInfo(_u("EndEmitFunction"));
  3794. }
  3795. }
  3796. void ByteCodeGenerator::StartEmitCatch(ParseNode *pnodeCatch)
  3797. {
  3798. Assert(pnodeCatch->nop == knopCatch);
  3799. Scope *scope = pnodeCatch->sxCatch.scope;
  3800. FuncInfo *funcInfo = scope->GetFunc();
  3801. // 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).
  3802. if (funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval() || (this->flags & (fscrEval | fscrImplicitThis | fscrImplicitParents)))
  3803. {
  3804. scope->SetIsObject();
  3805. }
  3806. if (pnodeCatch->sxCatch.pnodeParam->nop == knopParamPattern)
  3807. {
  3808. scope->SetCapturesAll(funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval());
  3809. scope->SetMustInstantiate(scope->Count() > 0 && (scope->GetMustInstantiate() || scope->GetCapturesAll() || funcInfo->IsGlobalFunction()));
  3810. Parser::MapBindIdentifier(pnodeCatch->sxCatch.pnodeParam->sxParamPattern.pnode1, [&](ParseNodePtr item)
  3811. {
  3812. Symbol *sym = item->sxVar.sym;
  3813. if (funcInfo->IsGlobalFunction())
  3814. {
  3815. sym->SetIsGlobalCatch(true);
  3816. }
  3817. Assert(sym->GetScopeSlot() == Js::Constants::NoProperty);
  3818. if (sym->NeedsSlotAlloc(funcInfo))
  3819. {
  3820. sym->EnsureScopeSlot(funcInfo);
  3821. }
  3822. });
  3823. // In the case of pattern we will always going to push the scope.
  3824. PushScope(scope);
  3825. }
  3826. else
  3827. {
  3828. Symbol *sym = pnodeCatch->sxCatch.pnodeParam->sxPid.sym;
  3829. // Catch object is stored in the catch scope if there may be an ambiguous lookup or a var declaration that hides it.
  3830. scope->SetCapturesAll(funcInfo->GetCallsEval() || funcInfo->GetChildCallsEval() || sym->GetHasNonLocalReference());
  3831. scope->SetMustInstantiate(scope->GetCapturesAll() || funcInfo->IsGlobalFunction());
  3832. if (funcInfo->IsGlobalFunction())
  3833. {
  3834. sym->SetIsGlobalCatch(true);
  3835. }
  3836. if (scope->GetMustInstantiate())
  3837. {
  3838. if (sym->IsInSlot(funcInfo))
  3839. {
  3840. // Since there is only one symbol we are pushing to slot.
  3841. // Also in order to make IsInSlot to return true - forcing the sym-has-non-local-reference.
  3842. this->ProcessCapturedSym(sym);
  3843. sym->EnsureScopeSlot(funcInfo);
  3844. }
  3845. }
  3846. PushScope(scope);
  3847. }
  3848. }
  3849. void ByteCodeGenerator::EndEmitCatch(ParseNode *pnodeCatch)
  3850. {
  3851. Assert(pnodeCatch->nop == knopCatch);
  3852. Assert(currentScope == pnodeCatch->sxCatch.scope);
  3853. PopScope();
  3854. }
  3855. void ByteCodeGenerator::StartEmitBlock(ParseNode *pnodeBlock)
  3856. {
  3857. if (!BlockHasOwnScope(pnodeBlock, this))
  3858. {
  3859. return;
  3860. }
  3861. Assert(pnodeBlock->nop == knopBlock);
  3862. PushBlock(pnodeBlock);
  3863. Scope *scope = pnodeBlock->sxBlock.scope;
  3864. if (pnodeBlock->sxBlock.GetCallsEval() || pnodeBlock->sxBlock.GetChildCallsEval() || (this->flags & (fscrEval | fscrImplicitThis | fscrImplicitParents)))
  3865. {
  3866. Assert(scope->GetIsObject());
  3867. }
  3868. // TODO: Consider nested deferred parsing.
  3869. if (scope->GetMustInstantiate())
  3870. {
  3871. FuncInfo *funcInfo = scope->GetFunc();
  3872. if (scope->IsGlobalEvalBlockScope() && funcInfo->isThisLexicallyCaptured)
  3873. {
  3874. funcInfo->EnsureThisScopeSlot();
  3875. }
  3876. this->EnsureFncScopeSlots(pnodeBlock->sxBlock.pnodeScopes, funcInfo);
  3877. this->EnsureLetConstScopeSlots(pnodeBlock, funcInfo);
  3878. PushScope(scope);
  3879. }
  3880. }
  3881. void ByteCodeGenerator::EndEmitBlock(ParseNode *pnodeBlock)
  3882. {
  3883. if (!BlockHasOwnScope(pnodeBlock, this))
  3884. {
  3885. return;
  3886. }
  3887. Assert(pnodeBlock->nop == knopBlock);
  3888. Scope *scope = pnodeBlock->sxBlock.scope;
  3889. if (scope && scope->GetMustInstantiate())
  3890. {
  3891. Assert(currentScope == pnodeBlock->sxBlock.scope);
  3892. PopScope();
  3893. }
  3894. PopBlock();
  3895. }
  3896. void ByteCodeGenerator::StartEmitWith(ParseNode *pnodeWith)
  3897. {
  3898. Assert(pnodeWith->nop == knopWith);
  3899. Scope *scope = pnodeWith->sxWith.scope;
  3900. Assert(scope->GetIsObject());
  3901. PushScope(scope);
  3902. }
  3903. void ByteCodeGenerator::EndEmitWith(ParseNode *pnodeWith)
  3904. {
  3905. Assert(pnodeWith->nop == knopWith);
  3906. Assert(currentScope == pnodeWith->sxWith.scope);
  3907. PopScope();
  3908. }
  3909. Js::RegSlot ByteCodeGenerator::PrependLocalScopes(Js::RegSlot evalEnv, Js::RegSlot tempLoc, FuncInfo *funcInfo)
  3910. {
  3911. Scope *currScope = this->currentScope;
  3912. Scope *funcScope = funcInfo->GetCurrentChildScope() ? funcInfo->GetCurrentChildScope() : funcInfo->GetBodyScope();
  3913. if (currScope == funcScope)
  3914. {
  3915. return evalEnv;
  3916. }
  3917. bool acquireTempLoc = tempLoc == Js::Constants::NoRegister;
  3918. if (acquireTempLoc)
  3919. {
  3920. tempLoc = funcInfo->AcquireTmpRegister();
  3921. }
  3922. // The with/catch objects must be prepended to the environment we pass to eval() or to a func declared inside with,
  3923. // but the list must first be reversed so that innermost scopes appear first in the list.
  3924. while (currScope != funcScope)
  3925. {
  3926. Scope *innerScope;
  3927. for (innerScope = currScope; innerScope->GetEnclosingScope() != funcScope; innerScope = innerScope->GetEnclosingScope())
  3928. ;
  3929. if (innerScope->GetMustInstantiate())
  3930. {
  3931. if (!innerScope->HasInnerScopeIndex())
  3932. {
  3933. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  3934. {
  3935. this->m_writer.Reg2(Js::OpCode::LdInnerFrameDisplayNoParent, tempLoc, innerScope->GetLocation());
  3936. }
  3937. else
  3938. {
  3939. this->m_writer.Reg3(Js::OpCode::LdInnerFrameDisplay, tempLoc, innerScope->GetLocation(), evalEnv);
  3940. }
  3941. }
  3942. else
  3943. {
  3944. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  3945. {
  3946. this->m_writer.Reg1Unsigned1(Js::OpCode::LdIndexedFrameDisplayNoParent, tempLoc, innerScope->GetInnerScopeIndex());
  3947. }
  3948. else
  3949. {
  3950. this->m_writer.Reg2Int1(Js::OpCode::LdIndexedFrameDisplay, tempLoc, evalEnv, innerScope->GetInnerScopeIndex());
  3951. }
  3952. }
  3953. evalEnv = tempLoc;
  3954. }
  3955. funcScope = innerScope;
  3956. }
  3957. if (acquireTempLoc)
  3958. {
  3959. funcInfo->ReleaseTmpRegister(tempLoc);
  3960. }
  3961. return evalEnv;
  3962. }
  3963. void ByteCodeGenerator::EmitLoadInstance(Symbol *sym, IdentPtr pid, Js::RegSlot *pThisLocation, Js::RegSlot *pInstLocation, FuncInfo *funcInfo)
  3964. {
  3965. Js::ByteCodeLabel doneLabel = 0;
  3966. bool fLabelDefined = false;
  3967. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  3968. Js::RegSlot thisLocation = *pThisLocation;
  3969. Js::RegSlot instLocation = *pInstLocation;
  3970. Js::PropertyId envIndex = -1;
  3971. Scope *scope = nullptr;
  3972. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  3973. Assert(symScope);
  3974. if (sym != nullptr && sym->GetIsModuleExportStorage())
  3975. {
  3976. *pInstLocation = Js::Constants::NoRegister;
  3977. return;
  3978. }
  3979. for (;;)
  3980. {
  3981. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  3982. if (scope == this->globalScope)
  3983. {
  3984. break;
  3985. }
  3986. if (scope != symScope)
  3987. {
  3988. // We're not sure where the function is (eval/with/etc).
  3989. // So we're going to need registers to hold the instance where we (dynamically) find
  3990. // the function, and possibly to hold the "this" pointer we will pass to it.
  3991. // Assign them here so that they can't overlap with the scopeLocation assigned below.
  3992. // Otherwise we wind up with temp lifetime confusion in the IRBuilder. (Win8 281689)
  3993. if (instLocation == Js::Constants::NoRegister)
  3994. {
  3995. instLocation = funcInfo->AcquireTmpRegister();
  3996. // The "this" pointer will not be the same as the instance, so give it its own register.
  3997. thisLocation = funcInfo->AcquireTmpRegister();
  3998. }
  3999. }
  4000. if (envIndex == -1)
  4001. {
  4002. Assert(funcInfo == scope->GetFunc());
  4003. scopeLocation = scope->GetLocation();
  4004. }
  4005. if (scope == symScope)
  4006. {
  4007. break;
  4008. }
  4009. // Found a scope to which the property may have been added.
  4010. Assert(scope && scope->GetIsDynamic());
  4011. if (!fLabelDefined)
  4012. {
  4013. fLabelDefined = true;
  4014. doneLabel = this->m_writer.DefineLabel();
  4015. }
  4016. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4017. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4018. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4019. if (envIndex != -1)
  4020. {
  4021. this->m_writer.BrEnvProperty(
  4022. Js::OpCode::BrOnNoEnvProperty, nextLabel,
  4023. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4024. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4025. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  4026. Assert(scope->GetIsObject());
  4027. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, tmpReg,
  4028. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4029. Js::OpCode op = unwrapWithObj ? Js::OpCode::UnwrapWithObj : Js::OpCode::Ld_A;
  4030. this->m_writer.Reg2(op, instLocation, tmpReg);
  4031. if (thisLocation != Js::Constants::NoRegister)
  4032. {
  4033. this->m_writer.Reg2(op, thisLocation, tmpReg);
  4034. }
  4035. funcInfo->ReleaseTmpRegister(tmpReg);
  4036. }
  4037. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4038. {
  4039. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4040. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4041. Assert(!unwrapWithObj);
  4042. Assert(scope->GetIsObject());
  4043. this->m_writer.Reg1(Js::OpCode::LdLocalObj, instLocation);
  4044. if (thisLocation != Js::Constants::NoRegister)
  4045. {
  4046. this->m_writer.Reg1(Js::OpCode::LdLocalObj, thisLocation);
  4047. }
  4048. }
  4049. else
  4050. {
  4051. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4052. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4053. Js::OpCode op = unwrapWithObj ? Js::OpCode::UnwrapWithObj : Js::OpCode::Ld_A;
  4054. this->m_writer.Reg2(op, instLocation, scopeLocation);
  4055. if (thisLocation != Js::Constants::NoRegister)
  4056. {
  4057. this->m_writer.Reg2(op, thisLocation, scopeLocation);
  4058. }
  4059. }
  4060. this->m_writer.Br(doneLabel);
  4061. this->m_writer.MarkLabel(nextLabel);
  4062. }
  4063. if (sym == nullptr || sym->GetIsGlobal())
  4064. {
  4065. if (this->flags & (fscrEval | fscrImplicitThis | fscrImplicitParents))
  4066. {
  4067. // Load of a symbol with unknown scope from within eval.
  4068. // Get it from the closure environment.
  4069. if (instLocation == Js::Constants::NoRegister)
  4070. {
  4071. instLocation = funcInfo->AcquireTmpRegister();
  4072. }
  4073. // TODO: It should be possible to avoid this double call to ScopedLdInst by having it return both
  4074. // results at once. The reason for the uncertainty here is that we don't know whether the callee
  4075. // belongs to a "with" object. If it does, we have to pass the "with" object as "this"; in all other
  4076. // cases, we pass "undefined". For now, there are apparently no significant performance issues.
  4077. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4078. if (thisLocation == Js::Constants::NoRegister)
  4079. {
  4080. thisLocation = funcInfo->AcquireTmpRegister();
  4081. }
  4082. this->m_writer.ScopedProperty2(Js::OpCode::ScopedLdInst, instLocation,
  4083. funcInfo->FindOrAddReferencedPropertyId(propertyId), thisLocation);
  4084. }
  4085. else
  4086. {
  4087. if (instLocation == Js::Constants::NoRegister)
  4088. {
  4089. instLocation = ByteCodeGenerator::RootObjectRegister;
  4090. }
  4091. else
  4092. {
  4093. this->m_writer.Reg2(Js::OpCode::Ld_A, instLocation, ByteCodeGenerator::RootObjectRegister);
  4094. }
  4095. if (thisLocation == Js::Constants::NoRegister)
  4096. {
  4097. thisLocation = funcInfo->undefinedConstantRegister;
  4098. }
  4099. else
  4100. {
  4101. this->m_writer.Reg2(Js::OpCode::Ld_A, thisLocation, funcInfo->undefinedConstantRegister);
  4102. }
  4103. }
  4104. }
  4105. else if (instLocation != Js::Constants::NoRegister)
  4106. {
  4107. if (envIndex != -1)
  4108. {
  4109. Assert(scope->GetIsObject());
  4110. this->m_writer.SlotI1(Js::OpCode::LdEnvObj, instLocation,
  4111. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4112. }
  4113. else if (scope->HasInnerScopeIndex())
  4114. {
  4115. this->m_writer.Reg1Unsigned1(Js::OpCode::LdInnerScope, instLocation, scope->GetInnerScopeIndex());
  4116. }
  4117. else if (symScope != funcInfo->GetBodyScope())
  4118. {
  4119. this->m_writer.Reg2(Js::OpCode::Ld_A, instLocation, scopeLocation);
  4120. }
  4121. else
  4122. {
  4123. Assert(funcInfo->frameObjRegister != Js::Constants::NoRegister);
  4124. this->m_writer.Reg1(Js::OpCode::LdLocalObj, instLocation);
  4125. }
  4126. if (thisLocation != Js::Constants::NoRegister)
  4127. {
  4128. this->m_writer.Reg2(Js::OpCode::Ld_A, thisLocation, funcInfo->undefinedConstantRegister);
  4129. }
  4130. else
  4131. {
  4132. thisLocation = funcInfo->undefinedConstantRegister;
  4133. }
  4134. }
  4135. *pThisLocation = thisLocation;
  4136. *pInstLocation = instLocation;
  4137. if (fLabelDefined)
  4138. {
  4139. this->m_writer.MarkLabel(doneLabel);
  4140. }
  4141. }
  4142. void ByteCodeGenerator::EmitGlobalFncDeclInit(Js::RegSlot rhsLocation, Js::PropertyId propertyId, FuncInfo * funcInfo)
  4143. {
  4144. // Note: declared variables and assignments in the global function go to the root object directly.
  4145. if (this->flags & fscrEval)
  4146. {
  4147. // Func decl's always get their init values before any use, so we don't pre-initialize the property to undef.
  4148. // That means that we have to use ScopedInitFld so that we initialize the property on the right instance
  4149. // even if the instance doesn't have the property yet (i.e., collapse the init-to-undef and the store
  4150. // into one operation). See WOOB 1121763 and 1120973.
  4151. this->m_writer.ScopedProperty(Js::OpCode::ScopedInitFunc, rhsLocation,
  4152. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4153. }
  4154. else
  4155. {
  4156. this->EmitPatchableRootProperty(Js::OpCode::InitRootFld, rhsLocation, propertyId, false, true, funcInfo);
  4157. }
  4158. }
  4159. void
  4160. ByteCodeGenerator::EmitPatchableRootProperty(Js::OpCode opcode,
  4161. Js::RegSlot regSlot, Js::PropertyId propertyId, bool isLoadMethod, bool isStore, FuncInfo * funcInfo)
  4162. {
  4163. uint cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, isLoadMethod, isStore);
  4164. this->m_writer.PatchableRootProperty(opcode, regSlot, cacheId, isLoadMethod, isStore);
  4165. }
  4166. void ByteCodeGenerator::EmitLocalPropInit(Js::RegSlot rhsLocation, Symbol *sym, FuncInfo *funcInfo)
  4167. {
  4168. Scope *scope = sym->GetScope();
  4169. // Check consistency of sym->IsInSlot.
  4170. Assert(sym->NeedsSlotAlloc(funcInfo) || sym->GetScopeSlot() == Js::Constants::NoProperty);
  4171. // Arrived at the scope in which the property was defined.
  4172. if (sym->NeedsSlotAlloc(funcInfo))
  4173. {
  4174. // The property is in memory rather than register. We'll have to load it from the slots.
  4175. if (scope->GetIsObject())
  4176. {
  4177. Assert(!this->TopFuncInfo()->GetParsedFunctionBody()->DoStackNestedFunc());
  4178. Js::PropertyId propertyId = sym->EnsurePosition(this);
  4179. Js::RegSlot objReg;
  4180. if (scope->HasInnerScopeIndex())
  4181. {
  4182. objReg = funcInfo->InnerScopeToRegSlot(scope);
  4183. }
  4184. else
  4185. {
  4186. objReg = scope->GetLocation();
  4187. }
  4188. uint cacheId = funcInfo->FindOrAddInlineCacheId(objReg, propertyId, false, true);
  4189. Js::OpCode op = this->GetInitFldOp(scope, objReg, funcInfo, sym->GetIsNonSimpleParameter());
  4190. if (objReg != Js::Constants::NoRegister && objReg == funcInfo->frameObjRegister)
  4191. {
  4192. this->m_writer.ElementP(op, rhsLocation, cacheId);
  4193. }
  4194. else if (scope->HasInnerScopeIndex())
  4195. {
  4196. this->m_writer.ElementPIndexed(op, rhsLocation, scope->GetInnerScopeIndex(), cacheId);
  4197. }
  4198. else
  4199. {
  4200. this->m_writer.PatchableProperty(op, rhsLocation, scope->GetLocation(), cacheId);
  4201. }
  4202. }
  4203. else
  4204. {
  4205. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4206. Js::PropertyId slot = sym->EnsureScopeSlot(funcInfo);
  4207. Js::RegSlot slotReg = scope->GetCanMerge() ? funcInfo->frameSlotsRegister : scope->GetLocation();
  4208. // Now store the property to its slot.
  4209. Js::OpCode op = this->GetStSlotOp(scope, -1, slotReg, false, funcInfo);
  4210. if (slotReg != Js::Constants::NoRegister && slotReg == funcInfo->frameSlotsRegister)
  4211. {
  4212. this->m_writer.SlotI1(op, rhsLocation, slot + Js::ScopeSlots::FirstSlotIndex);
  4213. }
  4214. else
  4215. {
  4216. this->m_writer.SlotI2(op, rhsLocation, scope->GetInnerScopeIndex(), slot + Js::ScopeSlots::FirstSlotIndex);
  4217. }
  4218. }
  4219. }
  4220. if (sym->GetLocation() != Js::Constants::NoRegister && rhsLocation != sym->GetLocation())
  4221. {
  4222. this->m_writer.Reg2(Js::OpCode::Ld_A, sym->GetLocation(), rhsLocation);
  4223. }
  4224. }
  4225. Js::OpCode
  4226. ByteCodeGenerator::GetStSlotOp(Scope *scope, int envIndex, Js::RegSlot scopeLocation, bool chkBlockVar, FuncInfo *funcInfo)
  4227. {
  4228. Js::OpCode op;
  4229. if (envIndex != -1)
  4230. {
  4231. if (scope->GetIsObject())
  4232. {
  4233. op = Js::OpCode::StEnvObjSlot;
  4234. }
  4235. else
  4236. {
  4237. op = Js::OpCode::StEnvSlot;
  4238. }
  4239. }
  4240. else if (scopeLocation != Js::Constants::NoRegister &&
  4241. scopeLocation == funcInfo->frameSlotsRegister)
  4242. {
  4243. op = Js::OpCode::StLocalSlot;
  4244. }
  4245. else if (scopeLocation != Js::Constants::NoRegister &&
  4246. scopeLocation == funcInfo->frameObjRegister)
  4247. {
  4248. op = Js::OpCode::StLocalObjSlot;
  4249. }
  4250. else
  4251. {
  4252. Assert(scope->HasInnerScopeIndex());
  4253. if (scope->GetIsObject())
  4254. {
  4255. op = Js::OpCode::StInnerObjSlot;
  4256. }
  4257. else
  4258. {
  4259. op = Js::OpCode::StInnerSlot;
  4260. }
  4261. }
  4262. if (chkBlockVar)
  4263. {
  4264. op = this->ToChkUndeclOp(op);
  4265. }
  4266. return op;
  4267. }
  4268. Js::OpCode
  4269. ByteCodeGenerator::GetInitFldOp(Scope *scope, Js::RegSlot scopeLocation, FuncInfo *funcInfo, bool letDecl)
  4270. {
  4271. Js::OpCode op;
  4272. if (scopeLocation != Js::Constants::NoRegister &&
  4273. scopeLocation == funcInfo->frameObjRegister)
  4274. {
  4275. op = letDecl ? Js::OpCode::InitLocalLetFld : Js::OpCode::InitLocalFld;
  4276. }
  4277. else if (scope->HasInnerScopeIndex())
  4278. {
  4279. op = letDecl ? Js::OpCode::InitInnerLetFld : Js::OpCode::InitInnerFld;
  4280. }
  4281. else
  4282. {
  4283. op = letDecl ? Js::OpCode::InitLetFld : Js::OpCode::InitFld;
  4284. }
  4285. return op;
  4286. }
  4287. void ByteCodeGenerator::EmitPropStore(Js::RegSlot rhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool isLetDecl, bool isConstDecl, bool isFncDeclVar)
  4288. {
  4289. Js::ByteCodeLabel doneLabel = 0;
  4290. bool fLabelDefined = false;
  4291. Js::PropertyId envIndex = -1;
  4292. Scope *symScope = sym == nullptr || sym->GetIsGlobal() ? this->globalScope : sym->GetScope();
  4293. Assert(symScope);
  4294. // isFncDeclVar denotes that the symbol being stored to here is the var
  4295. // binding of a function declaration and we know we want to store directly
  4296. // to it, skipping over any dynamic scopes that may lie in between.
  4297. Scope *scope = nullptr;
  4298. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4299. bool scopeAcquired = false;
  4300. Js::OpCode op;
  4301. if (sym && sym->GetIsModuleExportStorage())
  4302. {
  4303. if (!isConstDecl && sym->GetDecl() && sym->GetDecl()->nop == knopConstDecl)
  4304. {
  4305. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4306. }
  4307. EmitModuleExportAccess(sym, Js::OpCode::StModuleSlot, rhsLocation, funcInfo);
  4308. return;
  4309. }
  4310. if (isFncDeclVar)
  4311. {
  4312. // async functions allow for the fncDeclVar to be in the body or parameter scope
  4313. // of the parent function, so we need to calculate envIndex in lieu of the while
  4314. // loop below.
  4315. do
  4316. {
  4317. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4318. } while (scope != symScope);
  4319. Assert(scope == symScope);
  4320. scopeLocation = scope->GetLocation();
  4321. }
  4322. while (!isFncDeclVar)
  4323. {
  4324. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4325. if (scope == this->globalScope)
  4326. {
  4327. break;
  4328. }
  4329. if (envIndex == -1)
  4330. {
  4331. Assert(funcInfo == scope->GetFunc());
  4332. scopeLocation = scope->GetLocation();
  4333. }
  4334. if (scope == symScope)
  4335. {
  4336. break;
  4337. }
  4338. // Found a scope to which the property may have been added.
  4339. Assert(scope && scope->GetIsDynamic());
  4340. if (!fLabelDefined)
  4341. {
  4342. fLabelDefined = true;
  4343. doneLabel = this->m_writer.DefineLabel();
  4344. }
  4345. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4346. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4347. Js::RegSlot unwrappedScopeLocation = scopeLocation;
  4348. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4349. if (envIndex != -1)
  4350. {
  4351. this->m_writer.BrEnvProperty(
  4352. Js::OpCode::BrOnNoEnvProperty,
  4353. nextLabel,
  4354. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4355. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4356. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4357. Assert(scope->GetIsObject());
  4358. this->m_writer.SlotI1(
  4359. Js::OpCode::LdEnvObj,
  4360. instLocation,
  4361. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4362. if (unwrapWithObj)
  4363. {
  4364. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4365. }
  4366. this->m_writer.PatchableProperty(
  4367. Js::OpCode::StFld,
  4368. rhsLocation,
  4369. instLocation,
  4370. funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, true));
  4371. funcInfo->ReleaseTmpRegister(instLocation);
  4372. }
  4373. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4374. {
  4375. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4376. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4377. Assert(!unwrapWithObj);
  4378. this->m_writer.ElementP(Js::OpCode::StLocalFld, rhsLocation,
  4379. funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true));
  4380. }
  4381. else
  4382. {
  4383. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4384. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4385. if (unwrapWithObj)
  4386. {
  4387. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4388. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4389. scopeLocation = unwrappedScopeLocation;
  4390. }
  4391. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, true);
  4392. this->m_writer.PatchableProperty(Js::OpCode::StFld, rhsLocation, scopeLocation, cacheId);
  4393. if (unwrapWithObj)
  4394. {
  4395. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4396. }
  4397. }
  4398. this->m_writer.Br(doneLabel);
  4399. this->m_writer.MarkLabel(nextLabel);
  4400. }
  4401. // Arrived at the scope in which the property was defined.
  4402. if (sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo)
  4403. {
  4404. EmitUseBeforeDeclarationRuntimeError(this, Js::Constants::NoRegister);
  4405. // Intentionally continue on to do normal EmitPropStore behavior so
  4406. // that the bytecode ends up well-formed for the backend. This is
  4407. // in contrast to EmitPropLoad and EmitPropTypeof where they both
  4408. // tell EmitUseBeforeDeclarationRuntimeError to emit a LdUndef in place
  4409. // of their load and then they skip emitting their own bytecode.
  4410. // Potayto potahto.
  4411. }
  4412. if (sym == nullptr || sym->GetIsGlobal())
  4413. {
  4414. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4415. if (this->flags & fscrEval)
  4416. {
  4417. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4418. {
  4419. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->frameDisplayRegister, propertyId, false, true);
  4420. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo), rhsLocation, cacheId);
  4421. }
  4422. else
  4423. {
  4424. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, true);
  4425. bool isConsoleScopeLetConst = this->IsConsoleScopeEval() && (isLetDecl || isConstDecl);
  4426. // In "eval", store to a symbol with unknown scope goes through the closure environment.
  4427. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo, isConsoleScopeLetConst), rhsLocation, cacheId);
  4428. }
  4429. }
  4430. else if (this->flags & (fscrImplicitThis | fscrImplicitParents))
  4431. {
  4432. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, true);
  4433. // In "eval", store to a symbol with unknown scope goes through the closure environment.
  4434. this->m_writer.ElementP(GetScopedStFldOpCode(funcInfo), rhsLocation, cacheId);
  4435. }
  4436. else
  4437. {
  4438. this->EmitPatchableRootProperty(GetStFldOpCode(funcInfo, true, isLetDecl, isConstDecl, false), rhsLocation, propertyId, false, true, funcInfo);
  4439. }
  4440. }
  4441. else if (sym->GetIsFuncExpr())
  4442. {
  4443. // Store to function expr variable.
  4444. // strict mode: we need to throw type error
  4445. if (funcInfo->byteCodeFunction->GetIsStrictMode())
  4446. {
  4447. // Note that in this case the sym's location belongs to the parent function, so we can't use it.
  4448. // It doesn't matter which register we use, as long as it's valid for this function.
  4449. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_CantAssignToReadOnly));
  4450. }
  4451. }
  4452. else if (sym->IsInSlot(funcInfo) || envIndex != -1)
  4453. {
  4454. if (!isConstDecl && sym->GetDecl() && sym->GetDecl()->nop == knopConstDecl)
  4455. {
  4456. // This is a case where const reassignment can't be proven statically (e.g., eval, with) so
  4457. // we have to catch it at runtime.
  4458. this->m_writer.W1(
  4459. Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4460. }
  4461. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4462. Js::PropertyId slot = sym->EnsureScopeSlot(funcInfo);
  4463. bool chkBlockVar = !isLetDecl && !isConstDecl && NeedCheckBlockVar(sym, scope, funcInfo);
  4464. // The property is in memory rather than register. We'll have to load it from the slots.
  4465. op = this->GetStSlotOp(scope, envIndex, scopeLocation, chkBlockVar, funcInfo);
  4466. if (envIndex != -1)
  4467. {
  4468. this->m_writer.SlotI2(op, rhsLocation,
  4469. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var),
  4470. slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex));
  4471. }
  4472. else if (scopeLocation != Js::Constants::NoRegister &&
  4473. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4474. {
  4475. this->m_writer.SlotI1(op, rhsLocation,
  4476. slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex));
  4477. }
  4478. else
  4479. {
  4480. Assert(scope->HasInnerScopeIndex());
  4481. this->m_writer.SlotI2(op, rhsLocation, scope->GetInnerScopeIndex(),
  4482. slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex));
  4483. }
  4484. if (this->ShouldTrackDebuggerMetadata() && (isLetDecl || isConstDecl))
  4485. {
  4486. Js::PropertyId location = scope->GetIsObject() ? sym->GetLocation() : slot;
  4487. this->UpdateDebuggerPropertyInitializationOffset(location, sym->GetPosition(), false);
  4488. }
  4489. }
  4490. else if (isConstDecl)
  4491. {
  4492. this->m_writer.Reg2(Js::OpCode::InitConst, sym->GetLocation(), rhsLocation);
  4493. if (this->ShouldTrackDebuggerMetadata())
  4494. {
  4495. this->UpdateDebuggerPropertyInitializationOffset(sym->GetLocation(), sym->GetPosition());
  4496. }
  4497. }
  4498. else
  4499. {
  4500. if (!isConstDecl && sym->GetDecl() && sym->GetDecl()->nop == knopConstDecl)
  4501. {
  4502. // This is a case where const reassignment can't be proven statically (e.g., eval, with) so
  4503. // we have to catch it at runtime.
  4504. this->m_writer.W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(ERRAssignmentToConst));
  4505. }
  4506. if (rhsLocation != sym->GetLocation())
  4507. {
  4508. this->m_writer.Reg2(Js::OpCode::Ld_A, sym->GetLocation(), rhsLocation);
  4509. if (this->ShouldTrackDebuggerMetadata() && isLetDecl)
  4510. {
  4511. this->UpdateDebuggerPropertyInitializationOffset(sym->GetLocation(), sym->GetPosition());
  4512. }
  4513. }
  4514. }
  4515. if (fLabelDefined)
  4516. {
  4517. this->m_writer.MarkLabel(doneLabel);
  4518. }
  4519. if (scopeAcquired)
  4520. {
  4521. funcInfo->ReleaseTmpRegister(scopeLocation);
  4522. }
  4523. }
  4524. Js::OpCode
  4525. ByteCodeGenerator::GetLdSlotOp(Scope *scope, int envIndex, Js::RegSlot scopeLocation, FuncInfo *funcInfo)
  4526. {
  4527. Js::OpCode op;
  4528. if (envIndex != -1)
  4529. {
  4530. if (scope->GetIsObject())
  4531. {
  4532. op = Js::OpCode::LdEnvObjSlot;
  4533. }
  4534. else
  4535. {
  4536. op = Js::OpCode::LdEnvSlot;
  4537. }
  4538. }
  4539. else if (scopeLocation != Js::Constants::NoRegister &&
  4540. scopeLocation == funcInfo->frameSlotsRegister)
  4541. {
  4542. op = Js::OpCode::LdLocalSlot;
  4543. }
  4544. else if (scopeLocation != Js::Constants::NoRegister &&
  4545. scopeLocation == funcInfo->frameObjRegister)
  4546. {
  4547. op = Js::OpCode::LdLocalObjSlot;
  4548. }
  4549. else if (scope->HasInnerScopeIndex())
  4550. {
  4551. if (scope->GetIsObject())
  4552. {
  4553. op = Js::OpCode::LdInnerObjSlot;
  4554. }
  4555. else
  4556. {
  4557. op = Js::OpCode::LdInnerSlot;
  4558. }
  4559. }
  4560. else
  4561. {
  4562. Assert(scope->GetIsObject());
  4563. op = Js::OpCode::LdObjSlot;
  4564. }
  4565. return op;
  4566. }
  4567. void ByteCodeGenerator::EmitPropLoad(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo)
  4568. {
  4569. // If sym belongs to a parent frame, get it from the closure environment.
  4570. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4571. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4572. // Otherwise, just copy the value to the lhsLocation.
  4573. Js::ByteCodeLabel doneLabel = 0;
  4574. bool fLabelDefined = false;
  4575. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4576. Js::PropertyId envIndex = -1;
  4577. Scope *scope = nullptr;
  4578. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4579. Assert(symScope);
  4580. if (sym && sym->GetIsModuleExportStorage())
  4581. {
  4582. EmitModuleExportAccess(sym, Js::OpCode::LdModuleSlot, lhsLocation, funcInfo);
  4583. return;
  4584. }
  4585. for (;;)
  4586. {
  4587. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4588. if (scope == this->globalScope)
  4589. {
  4590. break;
  4591. }
  4592. scopeLocation = scope->GetLocation();
  4593. if (scope == symScope)
  4594. {
  4595. break;
  4596. }
  4597. // Found a scope to which the property may have been added.
  4598. Assert(scope && scope->GetIsDynamic());
  4599. if (!fLabelDefined)
  4600. {
  4601. fLabelDefined = true;
  4602. doneLabel = this->m_writer.DefineLabel();
  4603. }
  4604. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4605. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4606. Js::RegSlot unwrappedScopeLocation = Js::Constants::NoRegister;
  4607. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4608. if (envIndex != -1)
  4609. {
  4610. this->m_writer.BrEnvProperty(
  4611. Js::OpCode::BrOnNoEnvProperty,
  4612. nextLabel,
  4613. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4614. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4615. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4616. Assert(scope->GetIsObject());
  4617. this->m_writer.SlotI1(
  4618. Js::OpCode::LdEnvObj,
  4619. instLocation,
  4620. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4621. if (unwrapWithObj)
  4622. {
  4623. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4624. }
  4625. this->m_writer.PatchableProperty(
  4626. Js::OpCode::LdFld,
  4627. lhsLocation,
  4628. instLocation,
  4629. funcInfo->FindOrAddInlineCacheId(instLocation, propertyId, false, false));
  4630. funcInfo->ReleaseTmpRegister(instLocation);
  4631. }
  4632. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4633. {
  4634. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4635. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4636. Assert(!unwrapWithObj);
  4637. this->m_writer.ElementP(Js::OpCode::LdLocalFld, lhsLocation,
  4638. funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, false));
  4639. }
  4640. else
  4641. {
  4642. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4643. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4644. if (unwrapWithObj)
  4645. {
  4646. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4647. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4648. scopeLocation = unwrappedScopeLocation;
  4649. }
  4650. uint cacheId = funcInfo->FindOrAddInlineCacheId(scopeLocation, propertyId, false, false);
  4651. this->m_writer.PatchableProperty(Js::OpCode::LdFld, lhsLocation, scopeLocation, cacheId);
  4652. if (unwrapWithObj)
  4653. {
  4654. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4655. }
  4656. }
  4657. this->m_writer.Br(doneLabel);
  4658. this->m_writer.MarkLabel(nextLabel);
  4659. }
  4660. // Arrived at the scope in which the property was defined.
  4661. if (sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo)
  4662. {
  4663. // Ensure this symbol has a slot if it needs one.
  4664. if (sym->IsInSlot(funcInfo))
  4665. {
  4666. Js::PropertyId slot = sym->EnsureScopeSlot(funcInfo);
  4667. funcInfo->FindOrAddSlotProfileId(scope, slot);
  4668. }
  4669. EmitUseBeforeDeclarationRuntimeError(this, lhsLocation);
  4670. }
  4671. else if (sym == nullptr || sym->GetIsGlobal())
  4672. {
  4673. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4674. if (this->flags & fscrEval)
  4675. {
  4676. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  4677. {
  4678. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->frameDisplayRegister, propertyId, false, false);
  4679. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4680. }
  4681. else
  4682. {
  4683. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, false);
  4684. // Load of a symbol with unknown scope from within eval
  4685. // Get it from the closure environment.
  4686. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4687. }
  4688. }
  4689. else if (this->flags & (fscrImplicitThis | fscrImplicitParents))
  4690. {
  4691. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->GetEnvRegister(), propertyId, false, false);
  4692. // Load of a symbol with unknown scope from within eval or event handler.
  4693. // Get it from the closure environment.
  4694. this->m_writer.ElementP(Js::OpCode::ScopedLdFld, lhsLocation, cacheId);
  4695. }
  4696. else
  4697. {
  4698. // Special case non-writable built-ins
  4699. // TODO: support non-writable global property in general by detecting what attribute the property have current?
  4700. // But can't be done if we are byte code serialized, because the attribute might be different for use fields
  4701. // next time we run. May want to catch that in the JIT.
  4702. Js::OpCode opcode = Js::OpCode::LdRootFld;
  4703. // These properties are non-writable
  4704. switch (propertyId)
  4705. {
  4706. case Js::PropertyIds::NaN:
  4707. opcode = Js::OpCode::LdNaN;
  4708. break;
  4709. case Js::PropertyIds::Infinity:
  4710. opcode = Js::OpCode::LdInfinity;
  4711. break;
  4712. case Js::PropertyIds::undefined:
  4713. opcode = Js::OpCode::LdUndef;
  4714. break;
  4715. }
  4716. if (opcode == Js::OpCode::LdRootFld)
  4717. {
  4718. this->EmitPatchableRootProperty(Js::OpCode::LdRootFld, lhsLocation, propertyId, false, false, funcInfo);
  4719. }
  4720. else
  4721. {
  4722. this->Writer()->Reg1(opcode, lhsLocation);
  4723. }
  4724. }
  4725. }
  4726. else if (sym->IsInSlot(funcInfo) || envIndex != -1)
  4727. {
  4728. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  4729. Js::PropertyId slot = sym->EnsureScopeSlot(funcInfo);
  4730. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(scope, slot);
  4731. bool chkBlockVar = NeedCheckBlockVar(sym, scope, funcInfo);
  4732. Js::OpCode op;
  4733. // Now get the property from its slot.
  4734. op = this->GetLdSlotOp(scope, envIndex, scopeLocation, funcInfo);
  4735. slot = slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  4736. if (envIndex != -1)
  4737. {
  4738. this->m_writer.SlotI2(op, lhsLocation, envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var), slot, profileId);
  4739. }
  4740. else if (scopeLocation != Js::Constants::NoRegister &&
  4741. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  4742. {
  4743. this->m_writer.SlotI1(op, lhsLocation, slot, profileId);
  4744. }
  4745. else if (scope->HasInnerScopeIndex())
  4746. {
  4747. this->m_writer.SlotI2(op, lhsLocation, scope->GetInnerScopeIndex(), slot, profileId);
  4748. }
  4749. else
  4750. {
  4751. Assert(scope->GetIsObject());
  4752. this->m_writer.Slot(op, lhsLocation, scopeLocation, slot, profileId);
  4753. }
  4754. if (chkBlockVar)
  4755. {
  4756. this->m_writer.Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4757. }
  4758. }
  4759. else
  4760. {
  4761. if (lhsLocation != sym->GetLocation())
  4762. {
  4763. this->m_writer.Reg2(Js::OpCode::Ld_A, lhsLocation, sym->GetLocation());
  4764. }
  4765. if (sym->GetIsBlockVar() && ((sym->GetDecl()->nop == knopLetDecl || sym->GetDecl()->nop == knopConstDecl) && sym->GetDecl()->sxVar.isSwitchStmtDecl))
  4766. {
  4767. this->m_writer.Reg1(Js::OpCode::ChkUndecl, lhsLocation);
  4768. }
  4769. }
  4770. if (fLabelDefined)
  4771. {
  4772. this->m_writer.MarkLabel(doneLabel);
  4773. }
  4774. }
  4775. bool ByteCodeGenerator::NeedCheckBlockVar(Symbol* sym, Scope* scope, FuncInfo* funcInfo) const
  4776. {
  4777. bool tdz = sym->GetIsBlockVar()
  4778. && (scope->GetFunc() != funcInfo || ((sym->GetDecl()->nop == knopLetDecl || sym->GetDecl()->nop == knopConstDecl) && sym->GetDecl()->sxVar.isSwitchStmtDecl));
  4779. return tdz || sym->GetIsNonSimpleParameter();
  4780. }
  4781. void ByteCodeGenerator::EmitPropDelete(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo)
  4782. {
  4783. // If sym belongs to a parent frame, delete it from the closure environment.
  4784. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4785. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4786. // Otherwise, just return false.
  4787. Js::ByteCodeLabel doneLabel = 0;
  4788. bool fLabelDefined = false;
  4789. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4790. Js::PropertyId envIndex = -1;
  4791. Scope *scope = nullptr;
  4792. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4793. Assert(symScope);
  4794. for (;;)
  4795. {
  4796. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4797. if (scope == this->globalScope)
  4798. {
  4799. scopeLocation = ByteCodeGenerator::RootObjectRegister;
  4800. }
  4801. else if (envIndex == -1)
  4802. {
  4803. Assert(funcInfo == scope->GetFunc());
  4804. scopeLocation = scope->GetLocation();
  4805. }
  4806. if (scope == symScope)
  4807. {
  4808. break;
  4809. }
  4810. // Found a scope to which the property may have been added.
  4811. Assert(scope && scope->GetIsDynamic());
  4812. if (!fLabelDefined)
  4813. {
  4814. fLabelDefined = true;
  4815. doneLabel = this->m_writer.DefineLabel();
  4816. }
  4817. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4818. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4819. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4820. if (envIndex != -1)
  4821. {
  4822. this->m_writer.BrEnvProperty(
  4823. Js::OpCode::BrOnNoEnvProperty,
  4824. nextLabel,
  4825. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4826. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4827. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4828. Assert(scope->GetIsObject());
  4829. this->m_writer.SlotI1(
  4830. Js::OpCode::LdEnvObj,
  4831. instLocation,
  4832. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4833. if (unwrapWithObj)
  4834. {
  4835. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4836. }
  4837. this->m_writer.Property(Js::OpCode::DeleteFld, lhsLocation, instLocation,
  4838. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4839. funcInfo->ReleaseTmpRegister(instLocation);
  4840. }
  4841. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4842. {
  4843. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4844. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4845. Assert(!unwrapWithObj);
  4846. this->m_writer.ElementU(Js::OpCode::DeleteLocalFld, lhsLocation,
  4847. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4848. }
  4849. else
  4850. {
  4851. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4852. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4853. Js::RegSlot unwrappedScopeLocation = Js::Constants::NoRegister;
  4854. if (unwrapWithObj)
  4855. {
  4856. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4857. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4858. scopeLocation = unwrappedScopeLocation;
  4859. }
  4860. this->m_writer.Property(Js::OpCode::DeleteFld, lhsLocation, scopeLocation,
  4861. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4862. if (unwrapWithObj)
  4863. {
  4864. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  4865. }
  4866. }
  4867. this->m_writer.Br(doneLabel);
  4868. this->m_writer.MarkLabel(nextLabel);
  4869. }
  4870. // Arrived at the scope in which the property was defined.
  4871. if (sym == nullptr || sym->GetIsGlobal())
  4872. {
  4873. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4874. if (this->flags & (fscrEval | fscrImplicitThis | fscrImplicitParents))
  4875. {
  4876. this->m_writer.ScopedProperty(Js::OpCode::ScopedDeleteFld, lhsLocation,
  4877. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4878. }
  4879. else
  4880. {
  4881. this->m_writer.Property(Js::OpCode::DeleteRootFld, lhsLocation, ByteCodeGenerator::RootObjectRegister,
  4882. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4883. }
  4884. }
  4885. else
  4886. {
  4887. // The delete will look like a non-local reference, so make sure a slot is reserved.
  4888. sym->EnsureScopeSlot(funcInfo);
  4889. this->m_writer.Reg1(Js::OpCode::LdFalse, lhsLocation);
  4890. }
  4891. if (fLabelDefined)
  4892. {
  4893. this->m_writer.MarkLabel(doneLabel);
  4894. }
  4895. }
  4896. void ByteCodeGenerator::EmitTypeOfFld(FuncInfo * funcInfo, Js::PropertyId propertyId, Js::RegSlot value, Js::RegSlot instance, Js::OpCode ldFldOp)
  4897. {
  4898. uint cacheId;
  4899. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  4900. switch (ldFldOp)
  4901. {
  4902. case Js::OpCode::LdRootFldForTypeOf:
  4903. cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, false, false);
  4904. this->Writer()->PatchableRootProperty(ldFldOp, tmpReg, cacheId, false, false);
  4905. break;
  4906. case Js::OpCode::LdLocalFld:
  4907. case Js::OpCode::ScopedLdFldForTypeOf:
  4908. cacheId = funcInfo->FindOrAddInlineCacheId(instance, propertyId, false, false);
  4909. this->Writer()->ElementP(ldFldOp, tmpReg, cacheId);
  4910. break;
  4911. default:
  4912. cacheId = funcInfo->FindOrAddInlineCacheId(instance, propertyId, false, false);
  4913. this->Writer()->PatchableProperty(ldFldOp, tmpReg, instance, cacheId);
  4914. break;
  4915. }
  4916. this->Writer()->Reg2(Js::OpCode::Typeof, value, tmpReg);
  4917. funcInfo->ReleaseTmpRegister(tmpReg);
  4918. }
  4919. void ByteCodeGenerator::EmitPropTypeof(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo)
  4920. {
  4921. // If sym belongs to a parent frame, delete it from the closure environment.
  4922. // If it belongs to this func, but there's a non-local reference, get it from the heap-allocated frame.
  4923. // (TODO: optimize this by getting the sym from its normal location if there are no non-local defs.)
  4924. // Otherwise, just return false
  4925. Js::ByteCodeLabel doneLabel = 0;
  4926. bool fLabelDefined = false;
  4927. Js::RegSlot scopeLocation = Js::Constants::NoRegister;
  4928. Js::PropertyId envIndex = -1;
  4929. Scope *scope = nullptr;
  4930. Scope *symScope = sym ? sym->GetScope() : this->globalScope;
  4931. Assert(symScope);
  4932. if (sym && sym->GetIsModuleExportStorage())
  4933. {
  4934. Js::RegSlot tmpLocation = funcInfo->AcquireTmpRegister();
  4935. EmitModuleExportAccess(sym, Js::OpCode::LdModuleSlot, tmpLocation, funcInfo);
  4936. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, tmpLocation);
  4937. funcInfo->ReleaseTmpRegister(tmpLocation);
  4938. return;
  4939. }
  4940. for (;;)
  4941. {
  4942. scope = this->FindScopeForSym(symScope, scope, &envIndex, funcInfo);
  4943. if (scope == this->globalScope)
  4944. {
  4945. scopeLocation = ByteCodeGenerator::RootObjectRegister;
  4946. }
  4947. else if (envIndex == -1)
  4948. {
  4949. Assert(funcInfo == scope->GetFunc());
  4950. scopeLocation = scope->GetLocation();
  4951. }
  4952. if (scope == symScope)
  4953. {
  4954. break;
  4955. }
  4956. // Found a scope to which the property may have been added.
  4957. Assert(scope && scope->GetIsDynamic());
  4958. if (!fLabelDefined)
  4959. {
  4960. fLabelDefined = true;
  4961. doneLabel = this->m_writer.DefineLabel();
  4962. }
  4963. Js::ByteCodeLabel nextLabel = this->m_writer.DefineLabel();
  4964. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  4965. bool unwrapWithObj = scope->GetScopeType() == ScopeType_With && scriptContext->GetConfig()->IsES6UnscopablesEnabled();
  4966. if (envIndex != -1)
  4967. {
  4968. this->m_writer.BrEnvProperty(Js::OpCode::BrOnNoEnvProperty, nextLabel,
  4969. funcInfo->FindOrAddReferencedPropertyId(propertyId),
  4970. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4971. Js::RegSlot instLocation = funcInfo->AcquireTmpRegister();
  4972. Assert(scope->GetIsObject());
  4973. this->m_writer.SlotI1(Js::OpCode::LdEnvObj,
  4974. instLocation,
  4975. envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var));
  4976. if (unwrapWithObj)
  4977. {
  4978. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, instLocation, instLocation);
  4979. }
  4980. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, instLocation, Js::OpCode::LdFldForTypeOf);
  4981. funcInfo->ReleaseTmpRegister(instLocation);
  4982. }
  4983. else if (scopeLocation != Js::Constants::NoRegister && scopeLocation == funcInfo->frameObjRegister)
  4984. {
  4985. this->m_writer.BrLocalProperty(Js::OpCode::BrOnNoLocalProperty, nextLabel,
  4986. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4987. Assert(!unwrapWithObj);
  4988. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, scopeLocation, Js::OpCode::LdLocalFld);
  4989. }
  4990. else
  4991. {
  4992. this->m_writer.BrProperty(Js::OpCode::BrOnNoProperty, nextLabel, scopeLocation,
  4993. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  4994. Js::RegSlot unwrappedScopeLocation = Js::Constants::NoRegister;
  4995. if (unwrapWithObj)
  4996. {
  4997. unwrappedScopeLocation = funcInfo->AcquireTmpRegister();
  4998. this->m_writer.Reg2(Js::OpCode::UnwrapWithObj, unwrappedScopeLocation, scopeLocation);
  4999. scopeLocation = unwrappedScopeLocation;
  5000. }
  5001. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, scopeLocation, Js::OpCode::LdFldForTypeOf);
  5002. if (unwrapWithObj)
  5003. {
  5004. funcInfo->ReleaseTmpRegister(unwrappedScopeLocation);
  5005. }
  5006. }
  5007. this->m_writer.Br(doneLabel);
  5008. this->m_writer.MarkLabel(nextLabel);
  5009. }
  5010. // Arrived at the scope in which the property was defined.
  5011. if (sym && sym->GetNeedDeclaration() && scope->GetFunc() == funcInfo)
  5012. {
  5013. // Ensure this symbol has a slot if it needs one.
  5014. if (sym->IsInSlot(funcInfo))
  5015. {
  5016. Js::PropertyId slot = sym->EnsureScopeSlot(funcInfo);
  5017. funcInfo->FindOrAddSlotProfileId(scope, slot);
  5018. }
  5019. EmitUseBeforeDeclarationRuntimeError(this, lhsLocation);
  5020. }
  5021. else if (sym == nullptr || sym->GetIsGlobal())
  5022. {
  5023. Js::PropertyId propertyId = sym ? sym->EnsurePosition(this) : pid->GetPropertyId();
  5024. if (this->flags & fscrEval)
  5025. {
  5026. if (funcInfo->byteCodeFunction->GetIsStrictMode() && funcInfo->IsGlobalFunction())
  5027. {
  5028. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->frameDisplayRegister, Js::OpCode::ScopedLdFldForTypeOf);
  5029. }
  5030. else
  5031. {
  5032. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->GetEnvRegister(), Js::OpCode::ScopedLdFldForTypeOf);
  5033. }
  5034. }
  5035. else if (this->flags & (fscrImplicitThis | fscrImplicitParents))
  5036. {
  5037. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, funcInfo->GetEnvRegister(), Js::OpCode::ScopedLdFldForTypeOf);
  5038. }
  5039. else
  5040. {
  5041. this->EmitTypeOfFld(funcInfo, propertyId, lhsLocation, ByteCodeGenerator::RootObjectRegister, Js::OpCode::LdRootFldForTypeOf);
  5042. }
  5043. }
  5044. else if (sym->IsInSlot(funcInfo) || envIndex != -1)
  5045. {
  5046. // Make sure the property has a slot. This will bump up the size of the slot array if necessary.
  5047. Js::PropertyId slot = sym->EnsureScopeSlot(funcInfo);
  5048. Js::ProfileId profileId = funcInfo->FindOrAddSlotProfileId(scope, slot);
  5049. Js::RegSlot tmpLocation = funcInfo->AcquireTmpRegister();
  5050. bool chkBlockVar = NeedCheckBlockVar(sym, scope, funcInfo);
  5051. Js::OpCode op;
  5052. op = this->GetLdSlotOp(scope, envIndex, scopeLocation, funcInfo);
  5053. slot = slot + (sym->GetScope()->GetIsObject() ? 0 : Js::ScopeSlots::FirstSlotIndex);
  5054. if (envIndex != -1)
  5055. {
  5056. this->m_writer.SlotI2(op, tmpLocation, envIndex + Js::FrameDisplay::GetOffsetOfScopes() / sizeof(Js::Var), slot, profileId);
  5057. }
  5058. else if (scopeLocation != Js::Constants::NoRegister &&
  5059. (scopeLocation == funcInfo->frameSlotsRegister || scopeLocation == funcInfo->frameObjRegister))
  5060. {
  5061. this->m_writer.SlotI1(op, tmpLocation, slot, profileId);
  5062. }
  5063. else if (scope->HasInnerScopeIndex())
  5064. {
  5065. this->m_writer.SlotI2(op, tmpLocation, scope->GetInnerScopeIndex(), slot, profileId);
  5066. }
  5067. else
  5068. {
  5069. Assert(scope->GetIsObject());
  5070. this->m_writer.Slot(op, tmpLocation, scopeLocation, slot, profileId);
  5071. }
  5072. if (chkBlockVar)
  5073. {
  5074. this->m_writer.Reg1(Js::OpCode::ChkUndecl, tmpLocation);
  5075. }
  5076. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, tmpLocation);
  5077. funcInfo->ReleaseTmpRegister(tmpLocation);
  5078. }
  5079. else
  5080. {
  5081. this->m_writer.Reg2(Js::OpCode::Typeof, lhsLocation, sym->GetLocation());
  5082. }
  5083. if (fLabelDefined)
  5084. {
  5085. this->m_writer.MarkLabel(doneLabel);
  5086. }
  5087. }
  5088. void ByteCodeGenerator::EnsureNoRedeclarations(ParseNode *pnodeBlock, FuncInfo *funcInfo)
  5089. {
  5090. // Emit dynamic runtime checks for variable re-declarations. Only necessary for global functions (script or eval).
  5091. // In eval only var declarations can cause redeclaration, and only in non-strict mode, because let/const variables
  5092. // remain local to the eval code.
  5093. Assert(pnodeBlock->nop == knopBlock);
  5094. Assert(pnodeBlock->sxBlock.blockType == PnodeBlockType::Global || pnodeBlock->sxBlock.scope->GetScopeType() == ScopeType_GlobalEvalBlock);
  5095. if (!(this->flags & fscrEvalCode))
  5096. {
  5097. IterateBlockScopedVariables(pnodeBlock, [this](ParseNode *pnode)
  5098. {
  5099. FuncInfo *funcInfo = this->TopFuncInfo();
  5100. Symbol *sym = pnode->sxVar.sym;
  5101. Assert(sym->GetIsGlobal());
  5102. Js::PropertyId propertyId = sym->EnsurePosition(this);
  5103. this->m_writer.ElementRootU(Js::OpCode::EnsureNoRootFld, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  5104. });
  5105. }
  5106. for (ParseNode *pnode = funcInfo->root->sxFnc.pnodeVars; pnode; pnode = pnode->sxVar.pnodeNext)
  5107. {
  5108. Symbol* sym = pnode->sxVar.sym;
  5109. if (sym == nullptr || pnode->sxVar.isBlockScopeFncDeclVar)
  5110. continue;
  5111. if (sym->GetIsCatch() || (pnode->nop == knopVarDecl && sym->GetIsBlockVar()))
  5112. {
  5113. // The init node was bound to the catch object, because it's inside a catch and has the
  5114. // same name as the catch object. But we want to define a user var at function scope,
  5115. // so find the right symbol. (We'll still assign the RHS value to the catch object symbol.)
  5116. // This also applies to a var declaration in the same scope as a let declaration.
  5117. // Assert that catch cannot be at function scope and let and var at function scope is redeclaration error.
  5118. Assert(sym->GetIsCatch() || funcInfo->bodyScope != sym->GetScope());
  5119. sym = funcInfo->bodyScope->FindLocalSymbol(sym->GetName());
  5120. Assert(sym && !sym->GetIsCatch() && !sym->GetIsBlockVar());
  5121. }
  5122. Assert(sym->GetIsGlobal());
  5123. if (sym->GetSymbolType() == STVariable)
  5124. {
  5125. Js::PropertyId propertyId = sym->EnsurePosition(this);
  5126. if (this->flags & fscrEval)
  5127. {
  5128. if (!funcInfo->byteCodeFunction->GetIsStrictMode())
  5129. {
  5130. this->m_writer.ScopedProperty(Js::OpCode::ScopedEnsureNoRedeclFld, ByteCodeGenerator::RootObjectRegister,
  5131. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  5132. }
  5133. }
  5134. else
  5135. {
  5136. this->m_writer.ElementRootU(Js::OpCode::EnsureNoRootRedeclFld, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  5137. }
  5138. }
  5139. }
  5140. }
  5141. void ByteCodeGenerator::RecordAllIntConstants(FuncInfo * funcInfo)
  5142. {
  5143. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5144. funcInfo->constantToRegister.Map([byteCodeFunction](unsigned int val, Js::RegSlot location)
  5145. {
  5146. byteCodeFunction->RecordIntConstant(byteCodeFunction->MapRegSlot(location), val);
  5147. });
  5148. }
  5149. void ByteCodeGenerator::RecordAllStrConstants(FuncInfo * funcInfo)
  5150. {
  5151. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5152. funcInfo->stringToRegister.Map([byteCodeFunction](IdentPtr pid, Js::RegSlot location)
  5153. {
  5154. byteCodeFunction->RecordStrConstant(byteCodeFunction->MapRegSlot(location), pid->Psz(), pid->Cch());
  5155. });
  5156. }
  5157. void ByteCodeGenerator::RecordAllStringTemplateCallsiteConstants(FuncInfo* funcInfo)
  5158. {
  5159. Js::FunctionBody *byteCodeFunction = this->TopFuncInfo()->GetParsedFunctionBody();
  5160. funcInfo->stringTemplateCallsiteRegisterMap.Map([byteCodeFunction](ParseNodePtr pnode, Js::RegSlot location)
  5161. {
  5162. Js::ScriptContext* scriptContext = byteCodeFunction->GetScriptContext();
  5163. Js::JavascriptLibrary* library = scriptContext->GetLibrary();
  5164. Js::RecyclableObject* callsiteObject = library->TryGetStringTemplateCallsiteObject(pnode);
  5165. if (callsiteObject == nullptr)
  5166. {
  5167. Js::RecyclableObject* rawArray = ByteCodeGenerator::BuildArrayFromStringList(pnode->sxStrTemplate.pnodeStringRawLiterals, pnode->sxStrTemplate.countStringLiterals, scriptContext);
  5168. rawArray->Freeze();
  5169. callsiteObject = ByteCodeGenerator::BuildArrayFromStringList(pnode->sxStrTemplate.pnodeStringLiterals, pnode->sxStrTemplate.countStringLiterals, scriptContext);
  5170. callsiteObject->SetPropertyWithAttributes(Js::PropertyIds::raw, rawArray, PropertyNone, nullptr);
  5171. callsiteObject->Freeze();
  5172. library->AddStringTemplateCallsiteObject(callsiteObject);
  5173. }
  5174. byteCodeFunction->RecordConstant(byteCodeFunction->MapRegSlot(location), callsiteObject);
  5175. });
  5176. }
  5177. bool IsApplyArgs(ParseNode* callNode)
  5178. {
  5179. ParseNode* target = callNode->sxCall.pnodeTarget;
  5180. ParseNode* args = callNode->sxCall.pnodeArgs;
  5181. if ((target != nullptr) && (target->nop == knopDot))
  5182. {
  5183. ParseNode* lhsNode = target->sxBin.pnode1;
  5184. if ((lhsNode != nullptr) && ((lhsNode->nop == knopDot) || (lhsNode->nop == knopName)) && !IsArguments(lhsNode))
  5185. {
  5186. ParseNode* nameNode = target->sxBin.pnode2;
  5187. if (nameNode != nullptr)
  5188. {
  5189. bool nameIsApply = nameNode->sxPid.PropertyIdFromNameNode() == Js::PropertyIds::apply;
  5190. if (nameIsApply && args != nullptr && args->nop == knopList)
  5191. {
  5192. ParseNode* arg1 = args->sxBin.pnode1;
  5193. ParseNode* arg2 = args->sxBin.pnode2;
  5194. if ((arg1 != nullptr) && (arg1->nop == knopThis) && (arg2 != nullptr) && (arg2->nop == knopName) && (arg2->sxPid.sym != nullptr))
  5195. {
  5196. return arg2->sxPid.sym->GetIsArguments();
  5197. }
  5198. }
  5199. }
  5200. }
  5201. }
  5202. return false;
  5203. }
  5204. void PostCheckApplyEnclosesArgs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, ApplyCheck* applyCheck)
  5205. {
  5206. if ((pnode == nullptr) || (!applyCheck->matches))
  5207. {
  5208. return;
  5209. }
  5210. if (pnode->nop == knopCall)
  5211. {
  5212. if ((!pnode->isUsed) && IsApplyArgs(pnode))
  5213. {
  5214. if (!applyCheck->insideApplyCall)
  5215. {
  5216. applyCheck->matches = false;
  5217. }
  5218. applyCheck->insideApplyCall = false;
  5219. }
  5220. }
  5221. }
  5222. void CheckApplyEnclosesArgs(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, ApplyCheck* applyCheck)
  5223. {
  5224. if ((pnode == nullptr) || (!applyCheck->matches))
  5225. {
  5226. return;
  5227. }
  5228. switch (pnode->nop)
  5229. {
  5230. case knopName:
  5231. {
  5232. Symbol* sym = pnode->sxPid.sym;
  5233. if (sym != nullptr)
  5234. {
  5235. if (sym->GetIsArguments())
  5236. {
  5237. if (!applyCheck->insideApplyCall)
  5238. {
  5239. applyCheck->matches = false;
  5240. }
  5241. }
  5242. }
  5243. break;
  5244. }
  5245. case knopCall:
  5246. if ((!pnode->isUsed) && IsApplyArgs(pnode))
  5247. {
  5248. // no nested apply calls
  5249. if (applyCheck->insideApplyCall)
  5250. {
  5251. applyCheck->matches = false;
  5252. }
  5253. else
  5254. {
  5255. applyCheck->insideApplyCall = true;
  5256. applyCheck->sawApply = true;
  5257. pnode->sxCall.isApplyCall = true;
  5258. }
  5259. }
  5260. break;
  5261. }
  5262. }
  5263. unsigned int CountArguments(ParseNode *pnode, BOOL *pSideEffect = nullptr)
  5264. {
  5265. // If the caller passed us a pSideEffect, it wants to know whether there are potential
  5266. // side-effects in the argument list. We need to know this so that the call target
  5267. // operands can be preserved if necessary.
  5268. // For now, treat any non-leaf op as a potential side-effect. This causes no detectable slowdowns,
  5269. // but we can be more precise if we need to be.
  5270. if (pSideEffect)
  5271. {
  5272. *pSideEffect = FALSE;
  5273. }
  5274. unsigned int argCount = 1;
  5275. if (pnode != nullptr)
  5276. {
  5277. while (pnode->nop == knopList)
  5278. {
  5279. argCount++;
  5280. if (pSideEffect && !(ParseNode::Grfnop(pnode->sxBin.pnode1->nop) & fnopLeaf))
  5281. {
  5282. *pSideEffect = TRUE;
  5283. }
  5284. pnode = pnode->sxBin.pnode2;
  5285. }
  5286. argCount++;
  5287. if (pSideEffect && !(ParseNode::Grfnop(pnode->nop) & fnopLeaf))
  5288. {
  5289. *pSideEffect = TRUE;
  5290. }
  5291. }
  5292. return argCount;
  5293. }
  5294. void SaveOpndValue(ParseNode *pnode, FuncInfo *funcInfo)
  5295. {
  5296. // Save a local name to a register other than its home location.
  5297. // This guards against side-effects in cases like x.foo(x = bar()).
  5298. Symbol *sym = nullptr;
  5299. if (pnode->nop == knopName)
  5300. {
  5301. sym = pnode->sxPid.sym;
  5302. }
  5303. else if (pnode->nop == knopComputedName)
  5304. {
  5305. ParseNode *pnode1 = pnode->sxUni.pnode1;
  5306. if (pnode1->nop == knopName)
  5307. {
  5308. sym = pnode1->sxPid.sym;
  5309. }
  5310. }
  5311. if (sym == nullptr)
  5312. {
  5313. return;
  5314. }
  5315. // If the target is a local being kept in its home location,
  5316. // protect the target's value in the event the home location is overwritten.
  5317. if (pnode->location != Js::Constants::NoRegister &&
  5318. sym->GetScope()->GetFunc() == funcInfo &&
  5319. pnode->location == sym->GetLocation())
  5320. {
  5321. pnode->location = funcInfo->AcquireTmpRegister();
  5322. }
  5323. }
  5324. void ByteCodeGenerator::StartStatement(ParseNode* node)
  5325. {
  5326. Assert(TopFuncInfo() != nullptr);
  5327. m_writer.StartStatement(node, TopFuncInfo()->curTmpReg - TopFuncInfo()->firstTmpReg);
  5328. }
  5329. void ByteCodeGenerator::EndStatement(ParseNode* node)
  5330. {
  5331. m_writer.EndStatement(node);
  5332. }
  5333. void ByteCodeGenerator::StartSubexpression(ParseNode* node)
  5334. {
  5335. Assert(TopFuncInfo() != nullptr);
  5336. m_writer.StartSubexpression(node);
  5337. }
  5338. void ByteCodeGenerator::EndSubexpression(ParseNode* node)
  5339. {
  5340. m_writer.EndSubexpression(node);
  5341. }
  5342. void EmitReference(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  5343. {
  5344. // Generate code for the LHS of an assignment.
  5345. switch (pnode->nop)
  5346. {
  5347. case knopDot:
  5348. Emit(pnode->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  5349. break;
  5350. case knopIndex:
  5351. Emit(pnode->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  5352. Emit(pnode->sxBin.pnode2, byteCodeGenerator, funcInfo, false);
  5353. break;
  5354. case knopName:
  5355. break;
  5356. case knopArrayPattern:
  5357. case knopObjectPattern:
  5358. break;
  5359. case knopCall:
  5360. case knopNew:
  5361. // Emit the operands of a call that will be used as a LHS.
  5362. // These have to be emitted before the RHS, but they have to persist until
  5363. // the end of the expression.
  5364. // Emit the call target operands first.
  5365. switch (pnode->sxCall.pnodeTarget->nop)
  5366. {
  5367. case knopDot:
  5368. case knopIndex:
  5369. funcInfo->AcquireLoc(pnode->sxCall.pnodeTarget);
  5370. EmitReference(pnode->sxCall.pnodeTarget, byteCodeGenerator, funcInfo);
  5371. break;
  5372. case knopName:
  5373. {
  5374. Symbol *sym = pnode->sxCall.pnodeTarget->sxPid.sym;
  5375. if (!sym || sym->GetLocation() == Js::Constants::NoRegister)
  5376. {
  5377. funcInfo->AcquireLoc(pnode->sxCall.pnodeTarget);
  5378. }
  5379. if (sym && (sym->IsInSlot(funcInfo) || sym->GetScope()->GetFunc() != funcInfo))
  5380. {
  5381. // Can't get the value from the assigned register, so load it here.
  5382. EmitLoad(pnode->sxCall.pnodeTarget, byteCodeGenerator, funcInfo);
  5383. }
  5384. else
  5385. {
  5386. // EmitLoad will check for needsDeclaration and emit the Use Before Declaration error
  5387. // bytecode op as necessary, but EmitReference does not check this (by design). So we
  5388. // must manually check here.
  5389. EmitUseBeforeDeclaration(pnode->sxCall.pnodeTarget->sxPid.sym, byteCodeGenerator, funcInfo);
  5390. EmitReference(pnode->sxCall.pnodeTarget, byteCodeGenerator, funcInfo);
  5391. }
  5392. break;
  5393. }
  5394. default:
  5395. EmitLoad(pnode->sxCall.pnodeTarget, byteCodeGenerator, funcInfo);
  5396. break;
  5397. }
  5398. // Now the arg list. We evaluate everything now and emit the ArgOut's later.
  5399. if (pnode->sxCall.pnodeArgs)
  5400. {
  5401. ParseNode *pnodeArg = pnode->sxCall.pnodeArgs;
  5402. while (pnodeArg->nop == knopList)
  5403. {
  5404. Emit(pnodeArg->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  5405. pnodeArg = pnodeArg->sxBin.pnode2;
  5406. }
  5407. Emit(pnodeArg, byteCodeGenerator, funcInfo, false);
  5408. }
  5409. break;
  5410. default:
  5411. Emit(pnode, byteCodeGenerator, funcInfo, false);
  5412. break;
  5413. }
  5414. }
  5415. void EmitGetIterator(Js::RegSlot iteratorLocation, Js::RegSlot iterableLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5416. void EmitIteratorNext(Js::RegSlot itemLocation, Js::RegSlot iteratorLocation, Js::RegSlot nextInputLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5417. void EmitIteratorClose(Js::RegSlot iteratorLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5418. void EmitIteratorComplete(Js::RegSlot doneLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5419. void EmitIteratorValue(Js::RegSlot valueLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo);
  5420. void EmitDestructuredElement(ParseNode *elem, Js::RegSlot sourceLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo *funcInfo)
  5421. {
  5422. switch (elem->nop)
  5423. {
  5424. case knopVarDecl:
  5425. case knopLetDecl:
  5426. case knopConstDecl:
  5427. // We manually need to set NeedDeclaration since the node won't be visited.
  5428. elem->sxVar.sym->SetNeedDeclaration(false);
  5429. break;
  5430. default:
  5431. EmitReference(elem, byteCodeGenerator, funcInfo);
  5432. }
  5433. EmitAssignment(nullptr, elem, sourceLocation, byteCodeGenerator, funcInfo);
  5434. funcInfo->ReleaseReference(elem);
  5435. }
  5436. void EmitDestructuredRestArray(ParseNode *elem,
  5437. Js::RegSlot iteratorLocation,
  5438. Js::RegSlot shouldCallReturnFunctionLocation,
  5439. Js::RegSlot shouldCallReturnFunctionLocationFinally,
  5440. ByteCodeGenerator *byteCodeGenerator,
  5441. FuncInfo *funcInfo)
  5442. {
  5443. Js::RegSlot restArrayLocation = funcInfo->AcquireTmpRegister();
  5444. bool isAssignmentTarget = !(elem->sxUni.pnode1->IsPattern() || elem->sxUni.pnode1->IsVarLetOrConst());
  5445. if (isAssignmentTarget)
  5446. {
  5447. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  5448. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  5449. EmitReference(elem->sxUni.pnode1, byteCodeGenerator, funcInfo);
  5450. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5451. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5452. }
  5453. byteCodeGenerator->Writer()->Reg1Unsigned1(
  5454. Js::OpCode::NewScArray,
  5455. restArrayLocation,
  5456. ByteCodeGenerator::DefaultArraySize);
  5457. // BytecodeGen can't convey to IRBuilder that some of the temporaries used here are live. When we
  5458. // have a rest parameter, a counter is used in a loop for the array index, but there is no way to
  5459. // convey this is live on the back edge.
  5460. // As a workaround, we have a persistent var reg that is used for the loop counter
  5461. Js::RegSlot counterLocation = elem->location;
  5462. // TODO[ianhall]: Is calling EnregisterConstant() during Emit phase allowed?
  5463. Js::RegSlot zeroConstantReg = byteCodeGenerator->EnregisterConstant(0);
  5464. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, counterLocation, zeroConstantReg);
  5465. // loopTop:
  5466. Js::ByteCodeLabel loopTop = byteCodeGenerator->Writer()->DefineLabel();
  5467. byteCodeGenerator->Writer()->MarkLabel(loopTop);
  5468. Js::RegSlot itemLocation = funcInfo->AcquireTmpRegister();
  5469. EmitIteratorNext(itemLocation, iteratorLocation, Js::Constants::NoRegister, byteCodeGenerator, funcInfo);
  5470. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  5471. EmitIteratorComplete(doneLocation, itemLocation, byteCodeGenerator, funcInfo);
  5472. Js::ByteCodeLabel iteratorDone = byteCodeGenerator->Writer()->DefineLabel();
  5473. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, iteratorDone, doneLocation);
  5474. Js::RegSlot valueLocation = funcInfo->AcquireTmpRegister();
  5475. EmitIteratorValue(valueLocation, itemLocation, byteCodeGenerator, funcInfo);
  5476. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  5477. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  5478. byteCodeGenerator->Writer()->Element(
  5479. ByteCodeGenerator::GetStElemIOpCode(funcInfo),
  5480. valueLocation, restArrayLocation, counterLocation);
  5481. funcInfo->ReleaseTmpRegister(valueLocation);
  5482. funcInfo->ReleaseTmpRegister(doneLocation);
  5483. funcInfo->ReleaseTmpRegister(itemLocation);
  5484. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Incr_A, counterLocation, counterLocation);
  5485. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5486. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5487. byteCodeGenerator->Writer()->Br(loopTop);
  5488. // iteratorDone:
  5489. byteCodeGenerator->Writer()->MarkLabel(iteratorDone);
  5490. ParseNode *restElem = elem->sxUni.pnode1;
  5491. if (isAssignmentTarget)
  5492. {
  5493. EmitAssignment(nullptr, restElem, restArrayLocation, byteCodeGenerator, funcInfo);
  5494. funcInfo->ReleaseReference(restElem);
  5495. }
  5496. else
  5497. {
  5498. EmitDestructuredElement(restElem, restArrayLocation, byteCodeGenerator, funcInfo);
  5499. }
  5500. funcInfo->ReleaseTmpRegister(restArrayLocation);
  5501. }
  5502. void EmitDestructuredArray(
  5503. ParseNode *lhs,
  5504. Js::RegSlot rhsLocation,
  5505. ByteCodeGenerator *byteCodeGenerator,
  5506. FuncInfo *funcInfo);
  5507. void EmitIteratorCloseIfNotDone(Js::RegSlot iteratorLocation, Js::RegSlot doneLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  5508. {
  5509. Js::ByteCodeLabel skipCloseLabel = byteCodeGenerator->Writer()->DefineLabel();
  5510. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, skipCloseLabel, doneLocation);
  5511. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5512. byteCodeGenerator->Writer()->MarkLabel(skipCloseLabel);
  5513. }
  5514. /*
  5515. EmitDestructuredArray(lhsArray, rhs):
  5516. iterator = rhs[@@iterator]
  5517. if lhsArray empty
  5518. return
  5519. for each element in lhsArray except rest
  5520. value = iterator.next()
  5521. if element is a nested destructured array
  5522. EmitDestructuredArray(element, value)
  5523. else
  5524. if value is undefined and there is an initializer
  5525. evaluate initializer
  5526. evaluate element reference
  5527. element = initializer
  5528. else
  5529. element = value
  5530. if lhsArray has a rest element
  5531. rest = []
  5532. while iterator is not done
  5533. value = iterator.next()
  5534. rest.append(value)
  5535. */
  5536. void EmitDestructuredArrayCore(
  5537. ParseNode *list,
  5538. Js::RegSlot iteratorLocation,
  5539. Js::RegSlot shouldCallReturnFunctionLocation,
  5540. Js::RegSlot shouldCallReturnFunctionLocationFinally,
  5541. ByteCodeGenerator *byteCodeGenerator,
  5542. FuncInfo *funcInfo
  5543. )
  5544. {
  5545. Assert(list != nullptr);
  5546. ParseNode *elem = nullptr;
  5547. while (list != nullptr)
  5548. {
  5549. ParseNode *init = nullptr;
  5550. if (list->nop == knopList)
  5551. {
  5552. elem = list->sxBin.pnode1;
  5553. }
  5554. else
  5555. {
  5556. elem = list;
  5557. }
  5558. if (elem->nop == knopEllipsis)
  5559. {
  5560. break;
  5561. }
  5562. switch (elem->nop)
  5563. {
  5564. case knopAsg:
  5565. // An assignment node will always have an initializer
  5566. init = elem->sxBin.pnode2;
  5567. elem = elem->sxBin.pnode1;
  5568. break;
  5569. case knopVarDecl:
  5570. case knopLetDecl:
  5571. case knopConstDecl:
  5572. init = elem->sxVar.pnodeInit;
  5573. break;
  5574. default:
  5575. break;
  5576. }
  5577. byteCodeGenerator->StartStatement(elem);
  5578. bool isAssignmentTarget = !(elem->IsPattern() || elem->IsVarLetOrConst());
  5579. if (isAssignmentTarget)
  5580. {
  5581. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  5582. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  5583. EmitReference(elem, byteCodeGenerator, funcInfo);
  5584. }
  5585. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5586. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5587. Js::RegSlot itemLocation = funcInfo->AcquireTmpRegister();
  5588. EmitIteratorNext(itemLocation, iteratorLocation, Js::Constants::NoRegister, byteCodeGenerator, funcInfo);
  5589. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  5590. EmitIteratorComplete(doneLocation, itemLocation, byteCodeGenerator, funcInfo);
  5591. if (elem->nop == knopEmpty)
  5592. {
  5593. if (list->nop == knopList)
  5594. {
  5595. list = list->sxBin.pnode2;
  5596. funcInfo->ReleaseTmpRegister(doneLocation);
  5597. funcInfo->ReleaseTmpRegister(itemLocation);
  5598. continue;
  5599. }
  5600. else
  5601. {
  5602. Assert(list->nop == knopEmpty);
  5603. EmitIteratorCloseIfNotDone(iteratorLocation, doneLocation, byteCodeGenerator, funcInfo);
  5604. funcInfo->ReleaseTmpRegister(doneLocation);
  5605. funcInfo->ReleaseTmpRegister(itemLocation);
  5606. break;
  5607. }
  5608. }
  5609. // If the iterator hasn't completed, skip assigning undefined.
  5610. Js::ByteCodeLabel iteratorAlreadyDone = byteCodeGenerator->Writer()->DefineLabel();
  5611. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, iteratorAlreadyDone, doneLocation);
  5612. // We're not done with the iterator, so assign the .next() value.
  5613. Js::RegSlot valueLocation = funcInfo->AcquireTmpRegister();
  5614. EmitIteratorValue(valueLocation, itemLocation, byteCodeGenerator, funcInfo);
  5615. Js::ByteCodeLabel beforeDefaultAssign = byteCodeGenerator->Writer()->DefineLabel();
  5616. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  5617. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  5618. byteCodeGenerator->Writer()->Br(beforeDefaultAssign);
  5619. // iteratorAlreadyDone:
  5620. byteCodeGenerator->Writer()->MarkLabel(iteratorAlreadyDone);
  5621. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocation, funcInfo->undefinedConstantRegister);
  5622. // beforeDefaultAssign:
  5623. byteCodeGenerator->Writer()->MarkLabel(beforeDefaultAssign);
  5624. if (elem->IsPattern())
  5625. {
  5626. // If we get an undefined value and have an initializer, use it in place of undefined.
  5627. if (init != nullptr)
  5628. {
  5629. /*
  5630. the IR builder uses two symbols for a temp register in the if else path
  5631. R9 <- R3
  5632. if (...)
  5633. R9 <- R2
  5634. R10 = R9.<property> // error -> IR creates a new lifetime for the if path, and the direct path dest is not referenced
  5635. hence we have to create a new temp
  5636. TEMP REG USED TO FIX THIS PRODUCES THIS
  5637. R9 <- R3
  5638. if (BrEq_A R9, R3)
  5639. R10 <- R2 :
  5640. else
  5641. R10 <- R9 : skipdefault
  5642. ... = R10[@@iterator] : loadIter
  5643. */
  5644. // Temp Register
  5645. Js::RegSlot valueLocationTmp = funcInfo->AcquireTmpRegister();
  5646. byteCodeGenerator->StartStatement(init);
  5647. Js::ByteCodeLabel skipDefault = byteCodeGenerator->Writer()->DefineLabel();
  5648. Js::ByteCodeLabel loadIter = byteCodeGenerator->Writer()->DefineLabel();
  5649. // check value is undefined
  5650. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrNeq_A, skipDefault, valueLocation, funcInfo->undefinedConstantRegister);
  5651. // Evaluate the default expression and assign it.
  5652. Emit(init, byteCodeGenerator, funcInfo, false);
  5653. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocationTmp, init->location);
  5654. funcInfo->ReleaseLoc(init);
  5655. // jmp to loadIter
  5656. byteCodeGenerator->Writer()->Br(loadIter);
  5657. // skipDefault:
  5658. byteCodeGenerator->Writer()->MarkLabel(skipDefault);
  5659. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, valueLocationTmp, valueLocation);
  5660. // loadIter:
  5661. // @@iterator
  5662. byteCodeGenerator->Writer()->MarkLabel(loadIter);
  5663. byteCodeGenerator->EndStatement(init);
  5664. if (elem->nop == knopObjectPattern)
  5665. {
  5666. EmitDestructuredObject(elem, valueLocationTmp, byteCodeGenerator, funcInfo);
  5667. }
  5668. else
  5669. {
  5670. // Recursively emit a destructured array using the current .next() as the RHS.
  5671. EmitDestructuredArray(elem, valueLocationTmp, byteCodeGenerator, funcInfo);
  5672. }
  5673. funcInfo->ReleaseTmpRegister(valueLocationTmp);
  5674. }
  5675. else
  5676. {
  5677. if (elem->nop == knopObjectPattern)
  5678. {
  5679. EmitDestructuredObject(elem, valueLocation, byteCodeGenerator, funcInfo);
  5680. }
  5681. else
  5682. {
  5683. // Recursively emit a destructured array using the current .next() as the RHS.
  5684. EmitDestructuredArray(elem, valueLocation, byteCodeGenerator, funcInfo);
  5685. }
  5686. }
  5687. }
  5688. else
  5689. {
  5690. EmitDestructuredValueOrInitializer(elem, valueLocation, init, isAssignmentTarget, byteCodeGenerator, funcInfo);
  5691. }
  5692. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5693. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5694. if (list->nop != knopList)
  5695. {
  5696. EmitIteratorCloseIfNotDone(iteratorLocation, doneLocation, byteCodeGenerator, funcInfo);
  5697. }
  5698. funcInfo->ReleaseTmpRegister(valueLocation);
  5699. funcInfo->ReleaseTmpRegister(doneLocation);
  5700. funcInfo->ReleaseTmpRegister(itemLocation);
  5701. if (isAssignmentTarget)
  5702. {
  5703. funcInfo->ReleaseReference(elem);
  5704. }
  5705. byteCodeGenerator->EndStatement(elem);
  5706. if (list->nop == knopList)
  5707. {
  5708. list = list->sxBin.pnode2;
  5709. }
  5710. else
  5711. {
  5712. break;
  5713. }
  5714. }
  5715. // If we saw a rest element, emit the rest array.
  5716. if (elem != nullptr && elem->nop == knopEllipsis)
  5717. {
  5718. EmitDestructuredRestArray(elem,
  5719. iteratorLocation,
  5720. shouldCallReturnFunctionLocation,
  5721. shouldCallReturnFunctionLocationFinally,
  5722. byteCodeGenerator,
  5723. funcInfo);
  5724. }
  5725. }
  5726. // Generating
  5727. // try {
  5728. // CallIteratorClose
  5729. // } catch (e) {
  5730. // do nothing
  5731. // }
  5732. void EmitTryCatchAroundClose(
  5733. Js::RegSlot iteratorLocation,
  5734. Js::ByteCodeLabel endLabel,
  5735. ByteCodeGenerator *byteCodeGenerator,
  5736. FuncInfo *funcInfo)
  5737. {
  5738. Js::ByteCodeLabel catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  5739. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  5740. //
  5741. // There is no need to add TryScopeRecord here as we are going to call 'return' function and there is not yield expression here.
  5742. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5743. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5744. byteCodeGenerator->Writer()->Br(endLabel);
  5745. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  5746. Js::RegSlot catchParamLocation = funcInfo->AcquireTmpRegister();
  5747. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, catchParamLocation);
  5748. funcInfo->ReleaseTmpRegister(catchParamLocation);
  5749. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5750. }
  5751. struct ByteCodeGenerator::TryScopeRecord : public JsUtil::DoublyLinkedListElement<TryScopeRecord>
  5752. {
  5753. Js::OpCode op;
  5754. Js::ByteCodeLabel label;
  5755. Js::RegSlot reg1;
  5756. Js::RegSlot reg2;
  5757. TryScopeRecord(Js::OpCode op, Js::ByteCodeLabel label) : op(op), label(label), reg1(Js::Constants::NoRegister), reg2(Js::Constants::NoRegister) { }
  5758. TryScopeRecord(Js::OpCode op, Js::ByteCodeLabel label, Js::RegSlot r1, Js::RegSlot r2) : op(op), label(label), reg1(r1), reg2(r2) { }
  5759. };
  5760. // Generating
  5761. // catch(e) {
  5762. // if (shouldCallReturn)
  5763. // CallReturnWhichWrappedByTryCatch
  5764. // throw e;
  5765. // }
  5766. void EmitTopLevelCatch(Js::ByteCodeLabel catchLabel,
  5767. Js::RegSlot iteratorLocation,
  5768. Js::RegSlot shouldCallReturnLocation,
  5769. Js::RegSlot shouldCallReturnLocationFinally,
  5770. ByteCodeGenerator *byteCodeGenerator,
  5771. FuncInfo *funcInfo)
  5772. {
  5773. Js::ByteCodeLabel afterCatchBlockLabel = byteCodeGenerator->Writer()->DefineLabel();
  5774. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5775. byteCodeGenerator->Writer()->Br(afterCatchBlockLabel);
  5776. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  5777. Js::RegSlot catchParamLocation = funcInfo->AcquireTmpRegister();
  5778. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, catchParamLocation);
  5779. ByteCodeGenerator::TryScopeRecord tryRecForCatch(Js::OpCode::ResumeCatch, catchLabel);
  5780. if (funcInfo->byteCodeFunction->IsCoroutine())
  5781. {
  5782. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForCatch);
  5783. }
  5784. Js::ByteCodeLabel skipCallCloseLabel = byteCodeGenerator->Writer()->DefineLabel();
  5785. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, skipCallCloseLabel, shouldCallReturnLocation);
  5786. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnLocationFinally);
  5787. EmitTryCatchAroundClose(iteratorLocation, skipCallCloseLabel, byteCodeGenerator, funcInfo);
  5788. byteCodeGenerator->Writer()->MarkLabel(skipCallCloseLabel);
  5789. // Rethrow the exception.
  5790. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Throw, catchParamLocation);
  5791. funcInfo->ReleaseTmpRegister(catchParamLocation);
  5792. if (funcInfo->byteCodeFunction->IsCoroutine())
  5793. {
  5794. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  5795. }
  5796. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5797. byteCodeGenerator->Writer()->MarkLabel(afterCatchBlockLabel);
  5798. }
  5799. // Generating
  5800. // finally {
  5801. // if (shouldCallReturn)
  5802. // CallReturn
  5803. // }
  5804. void EmitTopLevelFinally(Js::ByteCodeLabel finallyLabel,
  5805. Js::RegSlot iteratorLocation,
  5806. Js::RegSlot shouldCallReturnLocation,
  5807. Js::RegSlot yieldExceptionLocation,
  5808. Js::RegSlot yieldOffsetLocation,
  5809. ByteCodeGenerator *byteCodeGenerator,
  5810. FuncInfo *funcInfo)
  5811. {
  5812. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  5813. Js::ByteCodeLabel afterFinallyBlockLabel = byteCodeGenerator->Writer()->DefineLabel();
  5814. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  5815. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  5816. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  5817. byteCodeGenerator->Writer()->Br(afterFinallyBlockLabel);
  5818. byteCodeGenerator->Writer()->MarkLabel(finallyLabel);
  5819. ByteCodeGenerator::TryScopeRecord tryRecForFinally(Js::OpCode::ResumeFinally, finallyLabel, yieldExceptionLocation, yieldOffsetLocation);
  5820. if (isCoroutine)
  5821. {
  5822. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForFinally);
  5823. }
  5824. Js::ByteCodeLabel skipCallCloseLabel = byteCodeGenerator->Writer()->DefineLabel();
  5825. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, skipCallCloseLabel, shouldCallReturnLocation);
  5826. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5827. byteCodeGenerator->Writer()->MarkLabel(skipCallCloseLabel);
  5828. if (isCoroutine)
  5829. {
  5830. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  5831. funcInfo->ReleaseTmpRegister(yieldOffsetLocation);
  5832. funcInfo->ReleaseTmpRegister(yieldExceptionLocation);
  5833. }
  5834. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  5835. byteCodeGenerator->Writer()->Empty(Js::OpCode::LeaveNull);
  5836. byteCodeGenerator->Writer()->MarkLabel(afterFinallyBlockLabel);
  5837. }
  5838. void EmitCatchAndFinallyBlocks(Js::ByteCodeLabel catchLabel,
  5839. Js::ByteCodeLabel finallyLabel,
  5840. Js::RegSlot iteratorLocation,
  5841. Js::RegSlot shouldCallReturnFunctionLocation,
  5842. Js::RegSlot shouldCallReturnFunctionLocationFinally,
  5843. Js::RegSlot yieldExceptionLocation,
  5844. Js::RegSlot yieldOffsetLocation,
  5845. ByteCodeGenerator *byteCodeGenerator,
  5846. FuncInfo *funcInfo
  5847. )
  5848. {
  5849. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  5850. if (isCoroutine)
  5851. {
  5852. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  5853. }
  5854. EmitTopLevelCatch(catchLabel,
  5855. iteratorLocation,
  5856. shouldCallReturnFunctionLocation,
  5857. shouldCallReturnFunctionLocationFinally,
  5858. byteCodeGenerator,
  5859. funcInfo);
  5860. if (isCoroutine)
  5861. {
  5862. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  5863. }
  5864. EmitTopLevelFinally(finallyLabel,
  5865. iteratorLocation,
  5866. shouldCallReturnFunctionLocationFinally,
  5867. yieldExceptionLocation,
  5868. yieldOffsetLocation,
  5869. byteCodeGenerator,
  5870. funcInfo);
  5871. funcInfo->ReleaseTmpRegister(shouldCallReturnFunctionLocationFinally);
  5872. funcInfo->ReleaseTmpRegister(shouldCallReturnFunctionLocation);
  5873. }
  5874. // Emit a wrapper try..finaly block around the destructuring elements
  5875. void EmitDestructuredArray(
  5876. ParseNode *lhs,
  5877. Js::RegSlot rhsLocation,
  5878. ByteCodeGenerator *byteCodeGenerator,
  5879. FuncInfo *funcInfo)
  5880. {
  5881. byteCodeGenerator->StartStatement(lhs);
  5882. Js::RegSlot iteratorLocation = funcInfo->AcquireTmpRegister();
  5883. EmitGetIterator(iteratorLocation, rhsLocation, byteCodeGenerator, funcInfo);
  5884. Assert(lhs->nop == knopArrayPattern);
  5885. ParseNode *list = lhs->sxArrLit.pnode1;
  5886. if (list == nullptr)
  5887. { // Handline this case ([] = obj);
  5888. EmitIteratorClose(iteratorLocation, byteCodeGenerator, funcInfo);
  5889. // No elements to bind or assign.
  5890. funcInfo->ReleaseTmpRegister(iteratorLocation);
  5891. byteCodeGenerator->EndStatement(lhs);
  5892. return;
  5893. }
  5894. // This variable facilitates on when to call the return function (which is Iterator close). When we are emitting bytecode for destructuring element
  5895. // this variable will be set to true.
  5896. Js::RegSlot shouldCallReturnFunctionLocation = funcInfo->AcquireTmpRegister();
  5897. Js::RegSlot shouldCallReturnFunctionLocationFinally = funcInfo->AcquireTmpRegister();
  5898. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  5899. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  5900. byteCodeGenerator->SetHasFinally(true);
  5901. byteCodeGenerator->SetHasTry(true);
  5902. byteCodeGenerator->TopFuncInfo()->byteCodeFunction->SetDontInline(true);
  5903. Js::RegSlot regException = Js::Constants::NoRegister;
  5904. Js::RegSlot regOffset = Js::Constants::NoRegister;
  5905. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  5906. if (isCoroutine)
  5907. {
  5908. regException = funcInfo->AcquireTmpRegister();
  5909. regOffset = funcInfo->AcquireTmpRegister();
  5910. }
  5911. // Insert try node here
  5912. Js::ByteCodeLabel finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  5913. Js::ByteCodeLabel catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  5914. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  5915. ByteCodeGenerator::TryScopeRecord tryRecForTryFinally(Js::OpCode::TryFinallyWithYield, finallyLabel);
  5916. if (isCoroutine)
  5917. {
  5918. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  5919. tryRecForTryFinally.reg1 = regException;
  5920. tryRecForTryFinally.reg2 = regOffset;
  5921. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTryFinally);
  5922. }
  5923. else
  5924. {
  5925. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  5926. }
  5927. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  5928. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryCatch, catchLabel);
  5929. if (isCoroutine)
  5930. {
  5931. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  5932. }
  5933. EmitDestructuredArrayCore(list,
  5934. iteratorLocation,
  5935. shouldCallReturnFunctionLocation,
  5936. shouldCallReturnFunctionLocationFinally,
  5937. byteCodeGenerator,
  5938. funcInfo);
  5939. EmitCatchAndFinallyBlocks(catchLabel,
  5940. finallyLabel,
  5941. iteratorLocation,
  5942. shouldCallReturnFunctionLocation,
  5943. shouldCallReturnFunctionLocationFinally,
  5944. regException,
  5945. regOffset,
  5946. byteCodeGenerator,
  5947. funcInfo);
  5948. funcInfo->ReleaseTmpRegister(iteratorLocation);
  5949. byteCodeGenerator->EndStatement(lhs);
  5950. }
  5951. void EmitNameInvoke(Js::RegSlot lhsLocation,
  5952. Js::RegSlot objectLocation,
  5953. ParseNodePtr nameNode,
  5954. ByteCodeGenerator* byteCodeGenerator,
  5955. FuncInfo* funcInfo)
  5956. {
  5957. Assert(nameNode != nullptr);
  5958. if (nameNode->nop == knopComputedName)
  5959. {
  5960. ParseNodePtr pnode1 = nameNode->sxUni.pnode1;
  5961. Emit(pnode1, byteCodeGenerator, funcInfo, false/*isConstructorCall*/);
  5962. byteCodeGenerator->Writer()->Element(Js::OpCode::LdElemI_A, lhsLocation, objectLocation, pnode1->location);
  5963. funcInfo->ReleaseLoc(pnode1);
  5964. }
  5965. else
  5966. {
  5967. Assert(nameNode->nop == knopName || nameNode->nop == knopStr);
  5968. Symbol *sym = nameNode->sxPid.sym;
  5969. Js::PropertyId propertyId = sym ? sym->EnsurePosition(byteCodeGenerator) : nameNode->sxPid.pid->GetPropertyId();
  5970. uint cacheId = funcInfo->FindOrAddInlineCacheId(objectLocation, propertyId, false/*isLoadMethod*/, false/*isStore*/);
  5971. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, lhsLocation, objectLocation, cacheId);
  5972. }
  5973. }
  5974. void EmitDestructuredValueOrInitializer(ParseNodePtr lhsElementNode,
  5975. Js::RegSlot rhsLocation,
  5976. ParseNodePtr initializer,
  5977. bool isNonPatternAssignmentTarget,
  5978. ByteCodeGenerator *byteCodeGenerator,
  5979. FuncInfo *funcInfo)
  5980. {
  5981. // 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
  5982. Js::ByteCodeLabel useDefault = -1;
  5983. Js::ByteCodeLabel end = -1;
  5984. Js::RegSlot rhsLocationTmp = rhsLocation;
  5985. if (initializer != nullptr)
  5986. {
  5987. rhsLocationTmp = funcInfo->AcquireTmpRegister();
  5988. useDefault = byteCodeGenerator->Writer()->DefineLabel();
  5989. end = byteCodeGenerator->Writer()->DefineLabel();
  5990. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, useDefault, rhsLocation, funcInfo->undefinedConstantRegister);
  5991. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocationTmp, rhsLocation);
  5992. byteCodeGenerator->Writer()->Br(end);
  5993. byteCodeGenerator->Writer()->MarkLabel(useDefault);
  5994. Emit(initializer, byteCodeGenerator, funcInfo, false/*isConstructorCall*/);
  5995. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocationTmp, initializer->location);
  5996. funcInfo->ReleaseLoc(initializer);
  5997. byteCodeGenerator->Writer()->MarkLabel(end);
  5998. }
  5999. if (lhsElementNode->nop == knopArrayPattern)
  6000. {
  6001. EmitDestructuredArray(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  6002. }
  6003. else if (lhsElementNode->nop == knopObjectPattern)
  6004. {
  6005. EmitDestructuredObject(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  6006. }
  6007. else if (isNonPatternAssignmentTarget)
  6008. {
  6009. EmitAssignment(nullptr, lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  6010. }
  6011. else
  6012. {
  6013. EmitDestructuredElement(lhsElementNode, rhsLocationTmp, byteCodeGenerator, funcInfo);
  6014. }
  6015. if (initializer != nullptr)
  6016. {
  6017. funcInfo->ReleaseTmpRegister(rhsLocationTmp);
  6018. }
  6019. }
  6020. void EmitDestructuredObjectMember(ParseNodePtr memberNode,
  6021. Js::RegSlot rhsLocation,
  6022. ByteCodeGenerator *byteCodeGenerator,
  6023. FuncInfo *funcInfo)
  6024. {
  6025. Assert(memberNode->nop == knopObjectPatternMember);
  6026. Js::RegSlot nameLocation = funcInfo->AcquireTmpRegister();
  6027. EmitNameInvoke(nameLocation, rhsLocation, memberNode->sxBin.pnode1, byteCodeGenerator, funcInfo);
  6028. // Imagine we are transforming
  6029. // {x:x1} = {} to x1 = {}.x (here x1 is the second node of the member but that is our lhsnode)
  6030. ParseNodePtr lhsElementNode = memberNode->sxBin.pnode2;
  6031. ParseNodePtr init = nullptr;
  6032. if (lhsElementNode->IsVarLetOrConst())
  6033. {
  6034. init = lhsElementNode->sxVar.pnodeInit;
  6035. }
  6036. else if (lhsElementNode->nop == knopAsg)
  6037. {
  6038. init = lhsElementNode->sxBin.pnode2;
  6039. lhsElementNode = lhsElementNode->sxBin.pnode1;
  6040. }
  6041. EmitDestructuredValueOrInitializer(lhsElementNode, nameLocation, init, false /*isNonPatternAssignmentTarget*/, byteCodeGenerator, funcInfo);
  6042. funcInfo->ReleaseTmpRegister(nameLocation);
  6043. }
  6044. void EmitDestructuredObject(ParseNode *lhs,
  6045. Js::RegSlot rhsLocationOrig,
  6046. ByteCodeGenerator *byteCodeGenerator,
  6047. FuncInfo *funcInfo)
  6048. {
  6049. Assert(lhs->nop == knopObjectPattern);
  6050. ParseNodePtr pnode1 = lhs->sxUni.pnode1;
  6051. byteCodeGenerator->StartStatement(lhs);
  6052. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  6053. Js::RegSlot rhsLocation = funcInfo->AcquireTmpRegister();
  6054. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, rhsLocation, rhsLocationOrig);
  6055. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrNeq_A, skipThrow, rhsLocation, funcInfo->undefinedConstantRegister);
  6056. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ObjectCoercible));
  6057. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  6058. if (pnode1 != nullptr)
  6059. {
  6060. Assert(pnode1->nop == knopList || pnode1->nop == knopObjectPatternMember);
  6061. ParseNodePtr current = pnode1;
  6062. while (current->nop == knopList)
  6063. {
  6064. ParseNodePtr memberNode = current->sxBin.pnode1;
  6065. EmitDestructuredObjectMember(memberNode, rhsLocation, byteCodeGenerator, funcInfo);
  6066. current = current->sxBin.pnode2;
  6067. }
  6068. EmitDestructuredObjectMember(current, rhsLocation, byteCodeGenerator, funcInfo);
  6069. }
  6070. funcInfo->ReleaseTmpRegister(rhsLocation);
  6071. byteCodeGenerator->EndStatement(lhs);
  6072. }
  6073. void EmitAssignment(
  6074. ParseNode *asgnNode,
  6075. ParseNode *lhs,
  6076. Js::RegSlot rhsLocation,
  6077. ByteCodeGenerator *byteCodeGenerator,
  6078. FuncInfo *funcInfo)
  6079. {
  6080. switch (lhs->nop)
  6081. {
  6082. // assignment to a local or global variable
  6083. case knopVarDecl:
  6084. case knopLetDecl:
  6085. case knopConstDecl:
  6086. {
  6087. Symbol *sym = lhs->sxVar.sym;
  6088. Assert(sym != nullptr);
  6089. byteCodeGenerator->EmitPropStore(rhsLocation, sym, nullptr, funcInfo, lhs->nop == knopLetDecl, lhs->nop == knopConstDecl);
  6090. break;
  6091. }
  6092. case knopName:
  6093. {
  6094. byteCodeGenerator->EmitPropStore(rhsLocation, lhs->sxPid.sym, lhs->sxPid.pid, funcInfo);
  6095. break;
  6096. }
  6097. // x.y =
  6098. case knopDot:
  6099. {
  6100. // PutValue(x, "y", rhs)
  6101. Js::PropertyId propertyId = lhs->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  6102. uint cacheId = funcInfo->FindOrAddInlineCacheId(lhs->sxBin.pnode1->location, propertyId, false, true);
  6103. if (lhs->sxBin.pnode1->nop == knopSuper)
  6104. {
  6105. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, funcInfo->superRegister, funcInfo);
  6106. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(Js::OpCode::StSuperFld, rhsLocation, tmpReg, funcInfo->thisPointerRegister, cacheId);
  6107. }
  6108. else
  6109. {
  6110. byteCodeGenerator->Writer()->PatchableProperty(
  6111. ByteCodeGenerator::GetStFldOpCode(funcInfo, false, false, false, false), rhsLocation, lhs->sxBin.pnode1->location, cacheId);
  6112. }
  6113. break;
  6114. }
  6115. case knopIndex:
  6116. {
  6117. byteCodeGenerator->Writer()->Element(
  6118. ByteCodeGenerator::GetStElemIOpCode(funcInfo),
  6119. rhsLocation, lhs->sxBin.pnode1->location, lhs->sxBin.pnode2->location);
  6120. break;
  6121. }
  6122. case knopObjectPattern:
  6123. {
  6124. Assert(byteCodeGenerator->IsES6DestructuringEnabled());
  6125. // Copy the rhs value to be the result of the assignment if needed.
  6126. if (asgnNode != nullptr)
  6127. {
  6128. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  6129. }
  6130. return EmitDestructuredObject(lhs, rhsLocation, byteCodeGenerator, funcInfo);
  6131. }
  6132. case knopArrayPattern:
  6133. {
  6134. Assert(byteCodeGenerator->IsES6DestructuringEnabled());
  6135. // Copy the rhs value to be the result of the assignment if needed.
  6136. if (asgnNode != nullptr)
  6137. {
  6138. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  6139. }
  6140. return EmitDestructuredArray(lhs, rhsLocation, byteCodeGenerator, funcInfo);
  6141. }
  6142. case knopArray:
  6143. case knopObject:
  6144. // Assignment to array/object can get through to byte code gen when the parser fails to convert destructuring
  6145. // assignment to pattern (because of structural mismatch between LHS & RHS?). Revisit when we nail
  6146. // down early vs. runtime errors for destructuring.
  6147. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  6148. break;
  6149. default:
  6150. Assert(!PHASE_ON1(Js::EarlyReferenceErrorsPhase));
  6151. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAssignTo));
  6152. break;
  6153. }
  6154. if (asgnNode != nullptr)
  6155. {
  6156. // We leave it up to the caller to pass this node only if the assignment expression is used.
  6157. if (asgnNode->location != rhsLocation)
  6158. {
  6159. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, asgnNode->location, rhsLocation);
  6160. }
  6161. }
  6162. }
  6163. void EmitLoad(
  6164. ParseNode *lhs,
  6165. ByteCodeGenerator *byteCodeGenerator,
  6166. FuncInfo *funcInfo)
  6167. {
  6168. // Emit the instructions to load the value into the LHS location. Do not assign/free any temps
  6169. // in the process.
  6170. // We usually get here as part of an op-equiv expression: x.y += z;
  6171. // In such a case, x has to be emitted first, then the value of x.y loaded (by this function), then z emitted.
  6172. switch (lhs->nop)
  6173. {
  6174. // load of a local or global variable
  6175. case knopName:
  6176. {
  6177. funcInfo->AcquireLoc(lhs);
  6178. byteCodeGenerator->EmitPropLoad(lhs->location, lhs->sxPid.sym, lhs->sxPid.pid, funcInfo);
  6179. break;
  6180. }
  6181. // = x.y
  6182. case knopDot:
  6183. {
  6184. // get field id for "y"
  6185. Js::PropertyId propertyId = lhs->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  6186. funcInfo->AcquireLoc(lhs);
  6187. EmitReference(lhs, byteCodeGenerator, funcInfo);
  6188. uint cacheId = funcInfo->FindOrAddInlineCacheId(lhs->sxBin.pnode1->location, propertyId, false, false);
  6189. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, lhs->location, lhs->sxBin.pnode1->location, cacheId);
  6190. break;
  6191. }
  6192. case knopIndex:
  6193. funcInfo->AcquireLoc(lhs);
  6194. EmitReference(lhs, byteCodeGenerator, funcInfo);
  6195. byteCodeGenerator->Writer()->Element(
  6196. Js::OpCode::LdElemI_A, lhs->location, lhs->sxBin.pnode1->location, lhs->sxBin.pnode2->location);
  6197. break;
  6198. // f(x) +=
  6199. case knopCall:
  6200. funcInfo->AcquireLoc(lhs);
  6201. EmitReference(lhs, byteCodeGenerator, funcInfo);
  6202. EmitCall(lhs, /*rhs=*/ Js::Constants::NoRegister, byteCodeGenerator, funcInfo, /*fReturnValue=*/ false, /*fEvaluateComponents=*/ false, /*fHasNewTarget=*/ false);
  6203. break;
  6204. default:
  6205. funcInfo->AcquireLoc(lhs);
  6206. Emit(lhs, byteCodeGenerator, funcInfo, false);
  6207. break;
  6208. }
  6209. }
  6210. void EmitList(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  6211. {
  6212. if (pnode != nullptr)
  6213. {
  6214. while (pnode->nop == knopList)
  6215. {
  6216. byteCodeGenerator->EmitTopLevelStatement(pnode->sxBin.pnode1, funcInfo, false);
  6217. pnode = pnode->sxBin.pnode2;
  6218. }
  6219. byteCodeGenerator->EmitTopLevelStatement(pnode, funcInfo, false);
  6220. }
  6221. }
  6222. void EmitSpreadArgToListBytecodeInstr(ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, Js::RegSlot argLoc, Js::ProfileId callSiteId, Js::ArgSlot &argIndex)
  6223. {
  6224. Js::RegSlot regVal = funcInfo->AcquireTmpRegister();
  6225. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, argLoc);
  6226. byteCodeGenerator->Writer()->ArgOut<true>(++argIndex, regVal, callSiteId);
  6227. funcInfo->ReleaseTmpRegister(regVal);
  6228. }
  6229. size_t EmitArgs(
  6230. ParseNode *pnode,
  6231. BOOL fAssignRegs,
  6232. ByteCodeGenerator *byteCodeGenerator,
  6233. FuncInfo *funcInfo,
  6234. Js::ProfileId callSiteId,
  6235. Js::AuxArray<uint32> *spreadIndices = nullptr
  6236. )
  6237. {
  6238. Js::ArgSlot argIndex = 0;
  6239. Js::ArgSlot spreadIndex = 0;
  6240. if (pnode != nullptr)
  6241. {
  6242. while (pnode->nop == knopList)
  6243. {
  6244. // If this is a put, the arguments have already been evaluated (see EmitReference).
  6245. // We just need to emit the ArgOut instructions.
  6246. if (fAssignRegs)
  6247. {
  6248. Emit(pnode->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  6249. }
  6250. if (pnode->sxBin.pnode1->nop == knopEllipsis)
  6251. {
  6252. Assert(spreadIndices != nullptr);
  6253. spreadIndices->elements[spreadIndex++] = argIndex + 1; // account for 'this'
  6254. EmitSpreadArgToListBytecodeInstr(byteCodeGenerator, funcInfo, pnode->sxBin.pnode1->location, callSiteId, argIndex);
  6255. }
  6256. else
  6257. {
  6258. byteCodeGenerator->Writer()->ArgOut<true>(++argIndex, pnode->sxBin.pnode1->location, callSiteId);
  6259. }
  6260. if (fAssignRegs)
  6261. {
  6262. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  6263. }
  6264. pnode = pnode->sxBin.pnode2;
  6265. }
  6266. // If this is a put, the call target has already been evaluated (see EmitReference).
  6267. if (fAssignRegs)
  6268. {
  6269. Emit(pnode, byteCodeGenerator, funcInfo, false);
  6270. }
  6271. if (pnode->nop == knopEllipsis)
  6272. {
  6273. Assert(spreadIndices != nullptr);
  6274. spreadIndices->elements[spreadIndex++] = argIndex + 1; // account for 'this'
  6275. EmitSpreadArgToListBytecodeInstr(byteCodeGenerator, funcInfo, pnode->location, callSiteId, argIndex);
  6276. }
  6277. else
  6278. {
  6279. byteCodeGenerator->Writer()->ArgOut<true>(++argIndex, pnode->location, callSiteId);
  6280. }
  6281. if (fAssignRegs)
  6282. {
  6283. funcInfo->ReleaseLoc(pnode);
  6284. }
  6285. }
  6286. return argIndex;
  6287. }
  6288. void EmitArgListStart(
  6289. Js::RegSlot thisLocation,
  6290. ByteCodeGenerator *byteCodeGenerator,
  6291. FuncInfo *funcInfo,
  6292. Js::ProfileId callSiteId)
  6293. {
  6294. if (thisLocation != Js::Constants::NoRegister)
  6295. {
  6296. // Emit the "this" object.
  6297. byteCodeGenerator->Writer()->ArgOut<true>(0, thisLocation, callSiteId);
  6298. }
  6299. }
  6300. Js::ArgSlot EmitArgListEnd(
  6301. ParseNode *pnode,
  6302. Js::RegSlot rhsLocation,
  6303. Js::RegSlot thisLocation,
  6304. Js::RegSlot evalLocation,
  6305. Js::RegSlot newTargetLocation,
  6306. ByteCodeGenerator *byteCodeGenerator,
  6307. FuncInfo *funcInfo,
  6308. size_t argIndex,
  6309. Js::ProfileId callSiteId)
  6310. {
  6311. BOOL fEvalInModule = false;
  6312. BOOL fIsPut = (rhsLocation != Js::Constants::NoRegister);
  6313. BOOL fIsEval = (evalLocation != Js::Constants::NoRegister);
  6314. BOOL fHasNewTarget = (newTargetLocation != Js::Constants::NoRegister);
  6315. Js::ArgSlot argSlotIndex = (Js::ArgSlot) argIndex;
  6316. static const Js::ArgSlot maxExtraArgSlot = 4; // max(extraEvalArg, extraArg), where extraEvalArg==2 (moduleRoot,env), extraArg==4 (this, eval, evalInModule, newTarget)
  6317. // check for integer overflow with margin for increments below to calculate argument count
  6318. if ((size_t)argSlotIndex != argIndex || argSlotIndex + maxExtraArgSlot < argSlotIndex)
  6319. {
  6320. Js::Throw::OutOfMemory();
  6321. }
  6322. Js::ArgSlot evalIndex;
  6323. if (fIsPut)
  6324. {
  6325. // Emit the assigned value as an additional operand. Note that the value has already been evaluated.
  6326. // We just need to emit the ArgOut instruction.
  6327. argSlotIndex++;
  6328. byteCodeGenerator->Writer()->ArgOut<true>(argSlotIndex, rhsLocation, callSiteId);
  6329. }
  6330. if (fIsEval && argSlotIndex > 0)
  6331. {
  6332. Assert(!fHasNewTarget);
  6333. // Pass the frame display as an extra argument to "eval".
  6334. // Do this only if eval is called with some args
  6335. Js::RegSlot evalEnv;
  6336. if (funcInfo->IsGlobalFunction() && !(funcInfo->GetIsStrictMode() && byteCodeGenerator->GetFlags() & fscrEval))
  6337. {
  6338. // Use current environment as the environment for the function being called when:
  6339. // - this is the root global function (not an eval's global function)
  6340. // - this is an eval's global function that is not in strict mode (see else block)
  6341. evalEnv = funcInfo->GetEnvRegister();
  6342. }
  6343. else
  6344. {
  6345. // Use the frame display as the environment for the function being called when:
  6346. // - this is not a global function and thus it will have its own scope
  6347. // - this is an eval's global function that is in strict mode, since in strict mode the eval's global function
  6348. // has its own scope
  6349. evalEnv = funcInfo->frameDisplayRegister;
  6350. }
  6351. evalEnv = byteCodeGenerator->PrependLocalScopes(evalEnv, evalLocation, funcInfo);
  6352. Js::ModuleID moduleID = byteCodeGenerator->GetModuleID();
  6353. if (moduleID != kmodGlobal)
  6354. {
  6355. // Pass both the module root and the environment.
  6356. fEvalInModule = true;
  6357. byteCodeGenerator->Writer()->ArgOut<true>(argSlotIndex + 1, ByteCodeGenerator::RootObjectRegister, callSiteId);
  6358. evalIndex = argSlotIndex + 2;
  6359. }
  6360. else
  6361. {
  6362. // Just pass the environment.
  6363. evalIndex = argSlotIndex + 1;
  6364. }
  6365. if (evalEnv == funcInfo->GetEnvRegister() || evalEnv == funcInfo->frameDisplayRegister)
  6366. {
  6367. byteCodeGenerator->Writer()->ArgOutEnv(evalIndex);
  6368. }
  6369. else
  6370. {
  6371. byteCodeGenerator->Writer()->ArgOut<false>(evalIndex, evalEnv, callSiteId);
  6372. }
  6373. }
  6374. if (fHasNewTarget)
  6375. {
  6376. Assert(!fIsEval);
  6377. byteCodeGenerator->Writer()->ArgOut<true>(argSlotIndex + 1, newTargetLocation, callSiteId);
  6378. }
  6379. Js::ArgSlot argIntCount = argSlotIndex + 1 + (Js::ArgSlot)fIsEval + (Js::ArgSlot)fEvalInModule + (Js::ArgSlot)fHasNewTarget;
  6380. // eval and no args passed, return 1 as argument count
  6381. if (fIsEval && pnode == nullptr)
  6382. {
  6383. return 1;
  6384. }
  6385. return argIntCount;
  6386. }
  6387. Js::ArgSlot EmitArgList(
  6388. ParseNode *pnode,
  6389. Js::RegSlot rhsLocation,
  6390. Js::RegSlot thisLocation,
  6391. Js::RegSlot newTargetLocation,
  6392. BOOL fIsEval,
  6393. BOOL fAssignRegs,
  6394. ByteCodeGenerator *byteCodeGenerator,
  6395. FuncInfo *funcInfo,
  6396. Js::ProfileId callSiteId,
  6397. uint16 spreadArgCount = 0,
  6398. Js::AuxArray<uint32> **spreadIndices = nullptr)
  6399. {
  6400. // This function emits the arguments for a call.
  6401. // ArgOut's with uses immediately following defs.
  6402. EmitArgListStart(thisLocation, byteCodeGenerator, funcInfo, callSiteId);
  6403. Js::RegSlot evalLocation = Js::Constants::NoRegister;
  6404. //
  6405. // If Emitting arguments for eval and assigning registers, get a tmpLocation for eval.
  6406. // This would be used while generating frameDisplay in EmitArgListEnd.
  6407. //
  6408. if (fIsEval)
  6409. {
  6410. evalLocation = funcInfo->AcquireTmpRegister();
  6411. }
  6412. if (spreadArgCount > 0)
  6413. {
  6414. const size_t extraAlloc = spreadArgCount * sizeof(uint32);
  6415. Assert(spreadIndices != nullptr);
  6416. *spreadIndices = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<uint32>, spreadArgCount);
  6417. }
  6418. size_t argIndex = EmitArgs(pnode, fAssignRegs, byteCodeGenerator, funcInfo, callSiteId, spreadIndices == nullptr ? nullptr : *spreadIndices);
  6419. Js::ArgSlot argumentsCount = EmitArgListEnd(pnode, rhsLocation, thisLocation, evalLocation, newTargetLocation, byteCodeGenerator, funcInfo, argIndex, callSiteId);
  6420. if (fIsEval)
  6421. {
  6422. funcInfo->ReleaseTmpRegister(evalLocation);
  6423. }
  6424. return argumentsCount;
  6425. }
  6426. void EmitConstantArgsToVarArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) Js::Var *vars, ParseNode *args, uint argCount)
  6427. {
  6428. uint index = 0;
  6429. while (args->nop == knopList && index < argCount)
  6430. {
  6431. if (args->sxBin.pnode1->nop == knopInt)
  6432. {
  6433. int value = args->sxBin.pnode1->sxInt.lw;
  6434. vars[index++] = Js::TaggedInt::ToVarUnchecked(value);
  6435. }
  6436. else if (args->sxBin.pnode1->nop == knopFlt)
  6437. {
  6438. Js::Var number = Js::JavascriptNumber::New(args->sxBin.pnode1->sxFlt.dbl, byteCodeGenerator->GetScriptContext());
  6439. #if ! FLOATVAR
  6440. byteCodeGenerator->GetScriptContext()->BindReference(number);
  6441. #endif
  6442. vars[index++] = number;
  6443. }
  6444. else
  6445. {
  6446. AnalysisAssert(false);
  6447. }
  6448. args = args->sxBin.pnode2;
  6449. }
  6450. if (index == argCount)
  6451. {
  6452. Assert(false);
  6453. Js::Throw::InternalError();
  6454. return;
  6455. }
  6456. if (args->nop == knopInt)
  6457. {
  6458. int value = args->sxInt.lw;
  6459. vars[index++] = Js::TaggedInt::ToVarUnchecked(value);
  6460. }
  6461. else if (args->nop == knopFlt)
  6462. {
  6463. Js::Var number = Js::JavascriptNumber::New(args->sxFlt.dbl, byteCodeGenerator->GetScriptContext());
  6464. #if ! FLOATVAR
  6465. byteCodeGenerator->GetScriptContext()->BindReference(number);
  6466. #endif
  6467. vars[index++] = number;
  6468. }
  6469. else
  6470. {
  6471. AnalysisAssert(false);
  6472. }
  6473. }
  6474. void EmitConstantArgsToIntArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) int32 *vars, ParseNode *args, uint argCount)
  6475. {
  6476. uint index = 0;
  6477. while (args->nop == knopList && index < argCount)
  6478. {
  6479. Assert(args->sxBin.pnode1->nop == knopInt);
  6480. vars[index++] = args->sxBin.pnode1->sxInt.lw;
  6481. args = args->sxBin.pnode2;
  6482. }
  6483. if (index == argCount)
  6484. {
  6485. Assert(false);
  6486. Js::Throw::InternalError();
  6487. return;
  6488. }
  6489. Assert(args->nop == knopInt);
  6490. vars[index++] = args->sxInt.lw;
  6491. Assert(index == argCount);
  6492. }
  6493. void EmitConstantArgsToFltArray(ByteCodeGenerator *byteCodeGenerator, __out_ecount(argCount) double *vars, ParseNode *args, uint argCount)
  6494. {
  6495. uint index = 0;
  6496. while (args->nop == knopList && index < argCount)
  6497. {
  6498. OpCode nop = args->sxBin.pnode1->nop;
  6499. if (nop == knopInt)
  6500. {
  6501. vars[index++] = (double)args->sxBin.pnode1->sxInt.lw;
  6502. }
  6503. else
  6504. {
  6505. Assert(nop == knopFlt);
  6506. vars[index++] = args->sxBin.pnode1->sxFlt.dbl;
  6507. }
  6508. args = args->sxBin.pnode2;
  6509. }
  6510. if (index == argCount)
  6511. {
  6512. Assert(false);
  6513. Js::Throw::InternalError();
  6514. return;
  6515. }
  6516. if (args->nop == knopInt)
  6517. {
  6518. vars[index++] = (double)args->sxInt.lw;
  6519. }
  6520. else
  6521. {
  6522. Assert(args->nop == knopFlt);
  6523. vars[index++] = args->sxFlt.dbl;
  6524. }
  6525. Assert(index == argCount);
  6526. }
  6527. //
  6528. // Called when we have new Ctr(constant, constant...)
  6529. //
  6530. Js::ArgSlot EmitNewObjectOfConstants(
  6531. ParseNode *pnode,
  6532. ByteCodeGenerator *byteCodeGenerator,
  6533. FuncInfo *funcInfo,
  6534. unsigned int argCount)
  6535. {
  6536. EmitArgListStart(Js::Constants::NoRegister, byteCodeGenerator, funcInfo, Js::Constants::NoProfileId);
  6537. // Create the vars array
  6538. Js::VarArrayVarCount *vars = AnewPlus(byteCodeGenerator->GetAllocator(), (argCount - 1) * sizeof(Js::Var), Js::VarArrayVarCount, Js::TaggedInt::ToVarUnchecked(argCount - 1));
  6539. // Emit all constants to the vars array
  6540. EmitConstantArgsToVarArray(byteCodeGenerator, vars->elements, pnode->sxCall.pnodeArgs, argCount - 1);
  6541. // Finish the arg list
  6542. Js::ArgSlot actualArgCount = EmitArgListEnd(
  6543. pnode->sxCall.pnodeArgs,
  6544. Js::Constants::NoRegister,
  6545. Js::Constants::NoRegister,
  6546. Js::Constants::NoRegister,
  6547. Js::Constants::NoRegister,
  6548. byteCodeGenerator,
  6549. funcInfo,
  6550. argCount - 1,
  6551. Js::Constants::NoProfileId);
  6552. // Make sure the cacheId to regSlot map in the ByteCodeWriter is left in a consistent state after writing NewScObject_A
  6553. byteCodeGenerator->Writer()->RemoveEntryForRegSlotFromCacheIdMap(pnode->sxCall.pnodeTarget->location);
  6554. // Generate the opcode with vars
  6555. byteCodeGenerator->Writer()->AuxiliaryContext(
  6556. Js::OpCode::NewScObject_A,
  6557. funcInfo->AcquireLoc(pnode),
  6558. vars,
  6559. sizeof(Js::VarArray) + (argCount - 1) * sizeof(Js::Var),
  6560. pnode->sxCall.pnodeTarget->location);
  6561. AdeletePlus(byteCodeGenerator->GetAllocator(), (argCount - 1) * sizeof(Js::VarArrayVarCount), vars);
  6562. return actualArgCount;
  6563. }
  6564. void EmitMethodFld(bool isRoot, bool isScoped, Js::RegSlot location, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, bool registerCacheIdForCall = true)
  6565. {
  6566. Js::OpCode opcode;
  6567. if (!isRoot)
  6568. {
  6569. if (callObjLocation == funcInfo->frameObjRegister)
  6570. {
  6571. opcode = Js::OpCode::LdLocalMethodFld;
  6572. }
  6573. else
  6574. {
  6575. opcode = Js::OpCode::LdMethodFld;
  6576. }
  6577. }
  6578. else if (isScoped)
  6579. {
  6580. opcode = Js::OpCode::ScopedLdMethodFld;
  6581. }
  6582. else
  6583. {
  6584. opcode = Js::OpCode::LdRootMethodFld;
  6585. }
  6586. if (isScoped || !isRoot)
  6587. {
  6588. Assert(isScoped || !isRoot || callObjLocation == ByteCodeGenerator::RootObjectRegister);
  6589. uint cacheId = funcInfo->FindOrAddInlineCacheId(callObjLocation, propertyId, true, false);
  6590. if (callObjLocation == funcInfo->frameObjRegister)
  6591. {
  6592. byteCodeGenerator->Writer()->ElementP(opcode, location, cacheId, false /*isCtor*/, registerCacheIdForCall);
  6593. }
  6594. else
  6595. {
  6596. byteCodeGenerator->Writer()->PatchableProperty(opcode, location, callObjLocation, cacheId, false /*isCtor*/, registerCacheIdForCall);
  6597. }
  6598. }
  6599. else
  6600. {
  6601. uint cacheId = funcInfo->FindOrAddRootObjectInlineCacheId(propertyId, true, false);
  6602. byteCodeGenerator->Writer()->PatchableRootProperty(opcode, location, cacheId, true, false, registerCacheIdForCall);
  6603. }
  6604. }
  6605. void EmitMethodFld(ParseNode *pnode, Js::RegSlot callObjLocation, Js::PropertyId propertyId, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, bool registerCacheIdForCall = true)
  6606. {
  6607. // Load a call target of the form x.y(). (Call target may be a plain knopName if we're getting it from
  6608. // the global object, etc.)
  6609. bool isRoot = pnode->nop == knopName && (pnode->sxPid.sym == nullptr || pnode->sxPid.sym->GetIsGlobal());
  6610. bool isScoped = (byteCodeGenerator->GetFlags() & fscrEval) != 0 ||
  6611. (isRoot && callObjLocation != ByteCodeGenerator::RootObjectRegister);
  6612. EmitMethodFld(isRoot, isScoped, pnode->location, callObjLocation, propertyId, byteCodeGenerator, funcInfo, registerCacheIdForCall);
  6613. }
  6614. // lhs.apply(this, arguments);
  6615. void EmitApplyCall(ParseNode* pnode, Js::RegSlot rhsLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo, BOOL fReturnValue)
  6616. {
  6617. ParseNode* applyNode = pnode->sxCall.pnodeTarget;
  6618. ParseNode* thisNode = pnode->sxCall.pnodeArgs->sxBin.pnode1;
  6619. Assert(applyNode->nop == knopDot);
  6620. ParseNode* funcNode = applyNode->sxBin.pnode1;
  6621. Js::ByteCodeLabel slowPath = byteCodeGenerator->Writer()->DefineLabel();
  6622. Js::ByteCodeLabel afterSlowPath = byteCodeGenerator->Writer()->DefineLabel();
  6623. Js::ByteCodeLabel argsAlreadyCreated = byteCodeGenerator->Writer()->DefineLabel();
  6624. Assert(applyNode->nop == knopDot);
  6625. Emit(funcNode, byteCodeGenerator, funcInfo, false);
  6626. funcInfo->AcquireLoc(applyNode);
  6627. Js::PropertyId propertyId = applyNode->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  6628. // As we won't be emitting a call instruction for apply, no need to register the cacheId for apply
  6629. // load to be associated with the call. This is also required, as in the absence of a corresponding
  6630. // call for apply, we won't remove the entry for "apply" cacheId from
  6631. // ByteCodeWriter::callRegToLdFldCacheIndexMap, which is contrary to our assumption that we would
  6632. // have removed an entry from a map upon seeing its corresponding call.
  6633. EmitMethodFld(applyNode, funcNode->location, propertyId, byteCodeGenerator, funcInfo, false /*registerCacheIdForCall*/);
  6634. Symbol *argSym = funcInfo->GetArgumentsSymbol();
  6635. Assert(argSym && argSym->GetIsArguments());
  6636. Js::RegSlot argumentsLoc = argSym->GetLocation();
  6637. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdArgumentsFromFrame, argumentsLoc);
  6638. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrNotNull_A, argsAlreadyCreated, argumentsLoc);
  6639. // If apply is overridden, bail to slow path.
  6640. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFncNeqApply, slowPath, applyNode->location);
  6641. // Note: acquire and release a temp register for this stack arg pointer instead of trying to stash it
  6642. // in funcInfo->stackArgReg. Otherwise, we'll needlessly load and store it in jitted loop bodies and
  6643. // may crash if we try to unbox it on the store.
  6644. Js::RegSlot stackArgReg = funcInfo->AcquireTmpRegister();
  6645. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdStackArgPtr, stackArgReg);
  6646. Js::RegSlot argCountLocation = funcInfo->AcquireTmpRegister();
  6647. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdArgCnt, argCountLocation);
  6648. byteCodeGenerator->Writer()->Reg5(Js::OpCode::ApplyArgs, funcNode->location, funcNode->location, thisNode->location, stackArgReg, argCountLocation);
  6649. funcInfo->ReleaseTmpRegister(argCountLocation);
  6650. funcInfo->ReleaseTmpRegister(stackArgReg);
  6651. funcInfo->ReleaseLoc(applyNode);
  6652. funcInfo->ReleaseLoc(funcNode);
  6653. // Clear these nodes as they are going to be used to re-generate the slow path.
  6654. VisitClearTmpRegs(applyNode, byteCodeGenerator, funcInfo);
  6655. VisitClearTmpRegs(funcNode, byteCodeGenerator, funcInfo);
  6656. byteCodeGenerator->Writer()->Br(afterSlowPath);
  6657. // slow path
  6658. byteCodeGenerator->Writer()->MarkLabel(slowPath);
  6659. if (funcInfo->frameObjRegister != Js::Constants::NoRegister)
  6660. {
  6661. byteCodeGenerator->EmitScopeObjectInit(funcInfo);
  6662. }
  6663. byteCodeGenerator->LoadHeapArguments(funcInfo);
  6664. byteCodeGenerator->Writer()->MarkLabel(argsAlreadyCreated);
  6665. EmitCall(pnode, rhsLocation, byteCodeGenerator, funcInfo, fReturnValue, /*fEvaluateComponents*/true, /*fHasNewTarget*/false);
  6666. byteCodeGenerator->Writer()->MarkLabel(afterSlowPath);
  6667. }
  6668. void EmitMethodElem(ParseNode *pnode, Js::RegSlot callObjLocation, Js::RegSlot indexLocation, ByteCodeGenerator *byteCodeGenerator)
  6669. {
  6670. // Load a call target of the form x[y]().
  6671. byteCodeGenerator->Writer()->Element(Js::OpCode::LdMethodElem, pnode->location, callObjLocation, indexLocation);
  6672. }
  6673. void EmitCallTargetNoEvalComponents(
  6674. ParseNode *pnodeTarget,
  6675. BOOL fSideEffectArgs,
  6676. Js::RegSlot *thisLocation,
  6677. Js::RegSlot *callObjLocation,
  6678. ByteCodeGenerator *byteCodeGenerator,
  6679. FuncInfo *funcInfo)
  6680. {
  6681. // We first get a reference to the call target, then evaluate the arguments, then
  6682. // evaluate the call target.
  6683. // - emit reference to target
  6684. // - copy instance to scratch reg if necessary.
  6685. // - assign this
  6686. // - assign instance for dynamic/global name
  6687. // - emit args
  6688. // - do call (CallFld/Elem/I)
  6689. switch (pnodeTarget->nop)
  6690. {
  6691. case knopDot:
  6692. *thisLocation = pnodeTarget->sxBin.pnode1->location;
  6693. *callObjLocation = pnodeTarget->sxBin.pnode1->location;
  6694. break;
  6695. case knopIndex:
  6696. *thisLocation = pnodeTarget->sxBin.pnode1->location;
  6697. *callObjLocation = pnodeTarget->sxBin.pnode1->location;
  6698. break;
  6699. case knopName:
  6700. // If the call target is a name, do some extra work to get its instance and the "this" pointer.
  6701. byteCodeGenerator->EmitLoadInstance(pnodeTarget->sxPid.sym, pnodeTarget->sxPid.pid, thisLocation, callObjLocation, funcInfo);
  6702. if (*thisLocation == Js::Constants::NoRegister)
  6703. {
  6704. *thisLocation = funcInfo->undefinedConstantRegister;
  6705. }
  6706. break;
  6707. default:
  6708. *thisLocation = funcInfo->undefinedConstantRegister;
  6709. break;
  6710. }
  6711. }
  6712. void EmitSuperMethodBegin(
  6713. ParseNode *pnodeTarget,
  6714. ByteCodeGenerator *byteCodeGenerator,
  6715. FuncInfo *funcInfo)
  6716. {
  6717. FuncInfo *parentFuncInfo = funcInfo;
  6718. if (parentFuncInfo->IsLambda())
  6719. {
  6720. parentFuncInfo = byteCodeGenerator->FindEnclosingNonLambda();
  6721. }
  6722. if (pnodeTarget->sxBin.pnode1->nop == knopSuper && parentFuncInfo->IsClassConstructor() && !parentFuncInfo->IsBaseClassConstructor())
  6723. {
  6724. byteCodeGenerator->EmitScopeSlotLoadThis(funcInfo, funcInfo->thisPointerRegister, /*chkUndecl*/ true);
  6725. }
  6726. }
  6727. void EmitCallTarget(
  6728. ParseNode *pnodeTarget,
  6729. BOOL fSideEffectArgs,
  6730. Js::RegSlot *thisLocation,
  6731. Js::RegSlot *callObjLocation,
  6732. ByteCodeGenerator *byteCodeGenerator,
  6733. FuncInfo *funcInfo)
  6734. {
  6735. // - emit target
  6736. // - assign this
  6737. // - emit args
  6738. // - do call
  6739. // The call target is fully evaluated before the argument list. Note that we're not handling
  6740. // put-call cases here currently, as such cases only apply to host objects
  6741. // and are very unlikely to behave differently depending on the order of evaluation.
  6742. switch (pnodeTarget->nop)
  6743. {
  6744. case knopDot:
  6745. {
  6746. funcInfo->AcquireLoc(pnodeTarget);
  6747. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6748. // them from side-effects.
  6749. if (fSideEffectArgs)
  6750. {
  6751. // Though we're done with target evaluation after this point, still protect opnd1 from
  6752. // arg side-effects as it's the "this" pointer.
  6753. SaveOpndValue(pnodeTarget->sxBin.pnode1, funcInfo);
  6754. }
  6755. if ((pnodeTarget->sxBin.pnode2->nop == knopName) && ((pnodeTarget->sxBin.pnode2->sxPid.PropertyIdFromNameNode() == Js::PropertyIds::apply) || (pnodeTarget->sxBin.pnode2->sxPid.PropertyIdFromNameNode() == Js::PropertyIds::call)))
  6756. {
  6757. pnodeTarget->sxBin.pnode1->SetIsCallApplyTargetLoad();
  6758. }
  6759. Emit(pnodeTarget->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  6760. Js::PropertyId propertyId = pnodeTarget->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  6761. Js::RegSlot protoLocation =
  6762. (pnodeTarget->sxBin.pnode1->nop == knopSuper) ?
  6763. byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, funcInfo->superRegister, funcInfo) :
  6764. pnodeTarget->sxBin.pnode1->location;
  6765. EmitSuperMethodBegin(pnodeTarget, byteCodeGenerator, funcInfo);
  6766. EmitMethodFld(pnodeTarget, protoLocation, propertyId, byteCodeGenerator, funcInfo);
  6767. // Function calls on the 'super' object should maintain current 'this' pointer
  6768. *thisLocation = (pnodeTarget->sxBin.pnode1->nop == knopSuper) ? funcInfo->thisPointerRegister : pnodeTarget->sxBin.pnode1->location;
  6769. break;
  6770. }
  6771. case knopIndex:
  6772. {
  6773. funcInfo->AcquireLoc(pnodeTarget);
  6774. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6775. // them from side-effects.
  6776. if (fSideEffectArgs || !(ParseNode::Grfnop(pnodeTarget->sxBin.pnode2->nop) & fnopLeaf))
  6777. {
  6778. // Though we're done with target evaluation after this point, still protect opnd1 from
  6779. // arg or opnd2 side-effects as it's the "this" pointer.
  6780. SaveOpndValue(pnodeTarget->sxBin.pnode1, funcInfo);
  6781. }
  6782. Emit(pnodeTarget->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  6783. Emit(pnodeTarget->sxBin.pnode2, byteCodeGenerator, funcInfo, false);
  6784. Js::RegSlot indexLocation = pnodeTarget->sxBin.pnode2->location;
  6785. Js::RegSlot protoLocation =
  6786. (pnodeTarget->sxBin.pnode1->nop == knopSuper) ?
  6787. byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, funcInfo->superRegister, funcInfo) :
  6788. pnodeTarget->sxBin.pnode1->location;
  6789. EmitSuperMethodBegin(pnodeTarget, byteCodeGenerator, funcInfo);
  6790. EmitMethodElem(pnodeTarget, protoLocation, indexLocation, byteCodeGenerator);
  6791. funcInfo->ReleaseLoc(pnodeTarget->sxBin.pnode2); // don't release indexLocation until after we use it.
  6792. // Function calls on the 'super' object should maintain current 'this' pointer
  6793. *thisLocation = (pnodeTarget->sxBin.pnode1->nop == knopSuper) ? funcInfo->thisPointerRegister : pnodeTarget->sxBin.pnode1->location;
  6794. break;
  6795. }
  6796. case knopClassDecl:
  6797. {
  6798. Emit(pnodeTarget, byteCodeGenerator, funcInfo, false);
  6799. // We won't always have an assigned this register (e.g. class expression calls.) We need undefined in this case.
  6800. *thisLocation = funcInfo->thisPointerRegister == Js::Constants::NoRegister ? funcInfo->undefinedConstantRegister : funcInfo->thisPointerRegister;
  6801. break;
  6802. }
  6803. case knopSuper:
  6804. {
  6805. Emit(pnodeTarget, byteCodeGenerator, funcInfo, false, /*isConstructorCall*/ true); // reuse isConstructorCall ("new super()" is illegal)
  6806. // Super calls should always use the new.target register unless we don't have one.
  6807. // That could happen if we have an eval('super()') outside of a class constructor.
  6808. if (funcInfo->newTargetRegister != Js::Constants::NoRegister)
  6809. {
  6810. *thisLocation = funcInfo->newTargetRegister;
  6811. }
  6812. else
  6813. {
  6814. *thisLocation = funcInfo->thisPointerRegister;
  6815. }
  6816. break;
  6817. }
  6818. case knopName:
  6819. {
  6820. funcInfo->AcquireLoc(pnodeTarget);
  6821. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6822. // them from side-effects.
  6823. if (fSideEffectArgs)
  6824. {
  6825. SaveOpndValue(pnodeTarget, funcInfo);
  6826. }
  6827. byteCodeGenerator->EmitLoadInstance(pnodeTarget->sxPid.sym, pnodeTarget->sxPid.pid, thisLocation, callObjLocation, funcInfo);
  6828. if (*callObjLocation != Js::Constants::NoRegister)
  6829. {
  6830. // Load the call target as a property of the instance.
  6831. Js::PropertyId propertyId = pnodeTarget->sxPid.PropertyIdFromNameNode();
  6832. EmitMethodFld(pnodeTarget, *callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6833. break;
  6834. }
  6835. // FALL THROUGH to evaluate call target.
  6836. }
  6837. default:
  6838. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  6839. // them from side-effects.
  6840. Emit(pnodeTarget, byteCodeGenerator, funcInfo, false);
  6841. *thisLocation = funcInfo->undefinedConstantRegister;
  6842. break;
  6843. }
  6844. // "This" pointer should have been assigned by the above.
  6845. Assert(*thisLocation != Js::Constants::NoRegister);
  6846. }
  6847. void EmitCallI(
  6848. ParseNode *pnode,
  6849. BOOL fEvaluateComponents,
  6850. BOOL fIsPut,
  6851. BOOL fIsEval,
  6852. BOOL fHasNewTarget,
  6853. uint32 actualArgCount,
  6854. ByteCodeGenerator *byteCodeGenerator,
  6855. FuncInfo *funcInfo,
  6856. Js::ProfileId callSiteId,
  6857. Js::AuxArray<uint32> *spreadIndices = nullptr)
  6858. {
  6859. // Emit a call where the target is in a register, because it's either a local name or an expression we've
  6860. // already evaluated.
  6861. ParseNode *pnodeTarget = pnode->sxBin.pnode1;
  6862. Js::OpCode op;
  6863. Js::CallFlags callFlags = Js::CallFlags::CallFlags_None;
  6864. uint spreadExtraAlloc = 0;
  6865. Js::ArgSlot actualArgSlotCount = (Js::ArgSlot) actualArgCount;
  6866. // check for integer overflow
  6867. if ((size_t)actualArgSlotCount != actualArgCount)
  6868. {
  6869. Js::Throw::OutOfMemory();
  6870. }
  6871. if (fIsPut)
  6872. {
  6873. if (pnode->sxCall.spreadArgCount > 0)
  6874. {
  6875. // TODO(tcare): We are disallowing spread with CallIPut for the moment. See DEVDIV2: 876387
  6876. // When CallIPut is migrated to the CallIExtended layout, this can be removed.
  6877. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_CantAsgCall));
  6878. }
  6879. // Grab a tmp register for the call result.
  6880. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  6881. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallIFlags, tmpReg, pnodeTarget->location, actualArgSlotCount, callSiteId, Js::CallFlags::CallFlags_NewTarget);
  6882. funcInfo->ReleaseTmpRegister(tmpReg);
  6883. }
  6884. else
  6885. {
  6886. if (fEvaluateComponents)
  6887. {
  6888. // Release the call target operands we assigned above. If we didn't assign them here,
  6889. // we'll need them later, so we can't re-use them for the result of the call.
  6890. funcInfo->ReleaseLoc(pnodeTarget);
  6891. }
  6892. // Grab a register for the call result.
  6893. if (pnode->isUsed)
  6894. {
  6895. funcInfo->AcquireLoc(pnode);
  6896. }
  6897. if (fIsEval)
  6898. {
  6899. op = Js::OpCode::CallIExtendedFlags;
  6900. callFlags = Js::CallFlags::CallFlags_ExtraArg;
  6901. }
  6902. else
  6903. {
  6904. bool isSuperCall = pnodeTarget->nop == knopSuper;
  6905. if (isSuperCall)
  6906. {
  6907. callFlags = Js::CallFlags_New;
  6908. }
  6909. if (fHasNewTarget)
  6910. {
  6911. callFlags = (Js::CallFlags) (callFlags | Js::CallFlags::CallFlags_ExtraArg | Js::CallFlags::CallFlags_NewTarget);
  6912. }
  6913. if (pnode->sxCall.spreadArgCount > 0)
  6914. {
  6915. op = (isSuperCall || fHasNewTarget) ? Js::OpCode::CallIExtendedFlags : Js::OpCode::CallIExtended;
  6916. }
  6917. else
  6918. {
  6919. op = (isSuperCall || fHasNewTarget) ? Js::OpCode::CallIFlags : Js::OpCode::CallI;
  6920. }
  6921. }
  6922. if (op == Js::OpCode::CallI || op == Js::OpCode::CallIFlags)
  6923. {
  6924. if (pnodeTarget->nop == knopSuper)
  6925. {
  6926. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdFuncObjProto, pnodeTarget->location, funcInfo);
  6927. byteCodeGenerator->Writer()->CallI(op, pnode->location, tmpReg, actualArgSlotCount, callSiteId, callFlags);
  6928. }
  6929. else
  6930. {
  6931. byteCodeGenerator->Writer()->CallI(op, pnode->location, pnodeTarget->location, actualArgSlotCount, callSiteId, callFlags);
  6932. }
  6933. }
  6934. else
  6935. {
  6936. uint spreadIndicesSize = 0;
  6937. Js::CallIExtendedOptions options = Js::CallIExtended_None;
  6938. if (pnode->sxCall.spreadArgCount > 0)
  6939. {
  6940. Assert(spreadIndices != nullptr);
  6941. spreadExtraAlloc = spreadIndices->count * sizeof(uint32);
  6942. spreadIndicesSize = sizeof(*spreadIndices) + spreadExtraAlloc;
  6943. options = Js::CallIExtended_SpreadArgs;
  6944. }
  6945. if (pnodeTarget->nop == knopSuper)
  6946. {
  6947. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdFuncObjProto, pnodeTarget->location, funcInfo);
  6948. byteCodeGenerator->Writer()->CallIExtended(op, pnode->location, tmpReg, actualArgSlotCount, options, spreadIndices, spreadIndicesSize, callSiteId, callFlags);
  6949. }
  6950. else
  6951. {
  6952. byteCodeGenerator->Writer()->CallIExtended(op, pnode->location, pnodeTarget->location, actualArgSlotCount, options, spreadIndices, spreadIndicesSize, callSiteId, callFlags);
  6953. }
  6954. }
  6955. if (pnode->sxCall.spreadArgCount > 0)
  6956. {
  6957. Assert(spreadExtraAlloc != 0);
  6958. AdeletePlus(byteCodeGenerator->GetAllocator(), spreadExtraAlloc, spreadIndices);
  6959. }
  6960. }
  6961. }
  6962. void EmitCallInstrNoEvalComponents(
  6963. ParseNode *pnode,
  6964. BOOL fIsPut,
  6965. BOOL fIsEval,
  6966. Js::RegSlot thisLocation,
  6967. Js::RegSlot callObjLocation,
  6968. uint32 actualArgCount,
  6969. ByteCodeGenerator *byteCodeGenerator,
  6970. FuncInfo *funcInfo,
  6971. Js::ProfileId callSiteId,
  6972. Js::AuxArray<uint32> *spreadIndices = nullptr)
  6973. {
  6974. // Emit the call instruction. The call target is a reference at this point, and we evaluate
  6975. // it as part of doing the actual call.
  6976. // Note that we don't handle the (fEvaluateComponents == TRUE) case in this function.
  6977. // (This function is only called on the !fEvaluateComponents branch in EmitCall.)
  6978. ParseNode *pnodeTarget = pnode->sxBin.pnode1;
  6979. switch (pnodeTarget->nop)
  6980. {
  6981. case knopDot:
  6982. {
  6983. Assert(pnodeTarget->sxBin.pnode2->nop == knopName);
  6984. Js::PropertyId propertyId = pnodeTarget->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  6985. EmitMethodFld(pnodeTarget, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  6986. EmitCallI(pnode, /*fEvaluateComponents*/ FALSE, fIsPut, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6987. }
  6988. break;
  6989. case knopIndex:
  6990. {
  6991. EmitMethodElem(pnodeTarget, pnodeTarget->sxBin.pnode1->location, pnodeTarget->sxBin.pnode2->location, byteCodeGenerator);
  6992. EmitCallI(pnode, /*fEvaluateComponents*/ FALSE, fIsPut, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  6993. }
  6994. break;
  6995. case knopName:
  6996. {
  6997. if (callObjLocation != Js::Constants::NoRegister)
  6998. {
  6999. // We still have to get the property from its instance, so emit CallFld.
  7000. if (thisLocation != callObjLocation)
  7001. {
  7002. funcInfo->ReleaseTmpRegister(thisLocation);
  7003. }
  7004. funcInfo->ReleaseTmpRegister(callObjLocation);
  7005. Js::PropertyId propertyId = pnodeTarget->sxPid.PropertyIdFromNameNode();
  7006. EmitMethodFld(pnodeTarget, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7007. EmitCallI(pnode, /*fEvaluateComponents*/ FALSE, fIsPut, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7008. break;
  7009. }
  7010. }
  7011. // FALL THROUGH
  7012. default:
  7013. EmitCallI(pnode, /*fEvaluateComponents*/ FALSE, fIsPut, fIsEval, /*fHasNewTarget*/ FALSE, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7014. break;
  7015. }
  7016. }
  7017. void EmitCallInstr(
  7018. ParseNode *pnode,
  7019. BOOL fIsPut,
  7020. BOOL fIsEval,
  7021. BOOL fHasNewTarget,
  7022. Js::RegSlot thisLocation,
  7023. Js::RegSlot callObjLocation,
  7024. uint32 actualArgCount,
  7025. ByteCodeGenerator *byteCodeGenerator,
  7026. FuncInfo *funcInfo,
  7027. Js::ProfileId callSiteId,
  7028. Js::AuxArray<uint32> *spreadIndices = nullptr)
  7029. {
  7030. // Emit a call instruction. The call target has been fully evaluated already, so we always
  7031. // emit a CallI through the register that holds the target value.
  7032. // Note that we don't handle !fEvaluateComponents cases at this point.
  7033. // (This function is only called on the fEvaluateComponents branch in EmitCall.)
  7034. if (thisLocation != Js::Constants::NoRegister)
  7035. {
  7036. funcInfo->ReleaseTmpRegister(thisLocation);
  7037. }
  7038. if (callObjLocation != Js::Constants::NoRegister &&
  7039. callObjLocation != thisLocation)
  7040. {
  7041. funcInfo->ReleaseTmpRegister(callObjLocation);
  7042. }
  7043. EmitCallI(pnode, /*fEvaluateComponents*/ TRUE, fIsPut, fIsEval, fHasNewTarget, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7044. }
  7045. void EmitNew(ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  7046. {
  7047. Js::ArgSlot argCount = pnode->sxCall.argCount;
  7048. argCount++; // include "this"
  7049. BOOL fSideEffectArgs = FALSE;
  7050. unsigned int tmpCount = CountArguments(pnode->sxCall.pnodeArgs, &fSideEffectArgs);
  7051. Assert(argCount == tmpCount);
  7052. if (argCount != (Js::ArgSlot)argCount)
  7053. {
  7054. Js::Throw::OutOfMemory();
  7055. }
  7056. byteCodeGenerator->StartStatement(pnode);
  7057. // Start call, allocate out param space
  7058. funcInfo->StartRecordingOutArgs(argCount);
  7059. // Assign the call target operand(s), putting them into expression temps if necessary to protect
  7060. // them from side-effects.
  7061. if (fSideEffectArgs)
  7062. {
  7063. SaveOpndValue(pnode->sxCall.pnodeTarget, funcInfo);
  7064. }
  7065. if (pnode->sxCall.pnodeTarget->nop == knopSuper)
  7066. {
  7067. EmitSuperFieldPatch(funcInfo, pnode, byteCodeGenerator);
  7068. }
  7069. Emit(pnode->sxCall.pnodeTarget, byteCodeGenerator, funcInfo, false, true);
  7070. if (pnode->sxCall.pnodeArgs == nullptr)
  7071. {
  7072. funcInfo->ReleaseLoc(pnode->sxCall.pnodeTarget);
  7073. Js::OpCode op = (CreateNativeArrays(byteCodeGenerator, funcInfo)
  7074. && CallTargetIsArray(pnode->sxCall.pnodeTarget))
  7075. ? Js::OpCode::NewScObjArray : Js::OpCode::NewScObject;
  7076. Assert(argCount == 1);
  7077. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(op);
  7078. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argCount);
  7079. byteCodeGenerator->Writer()->CallI(op, funcInfo->AcquireLoc(pnode),
  7080. pnode->sxCall.pnodeTarget->location, argCount, callSiteId);
  7081. }
  7082. else
  7083. {
  7084. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argCount);
  7085. uint32 actualArgCount = 0;
  7086. if (IsCallOfConstants(pnode))
  7087. {
  7088. funcInfo->ReleaseLoc(pnode->sxCall.pnodeTarget);
  7089. actualArgCount = EmitNewObjectOfConstants(pnode, byteCodeGenerator, funcInfo, argCount);
  7090. }
  7091. else
  7092. {
  7093. Js::OpCode op;
  7094. if ((CreateNativeArrays(byteCodeGenerator, funcInfo) && CallTargetIsArray(pnode->sxCall.pnodeTarget)))
  7095. {
  7096. op = pnode->sxCall.spreadArgCount > 0 ? Js::OpCode::NewScObjArraySpread : Js::OpCode::NewScObjArray;
  7097. }
  7098. else
  7099. {
  7100. op = pnode->sxCall.spreadArgCount > 0 ? Js::OpCode::NewScObjectSpread : Js::OpCode::NewScObject;
  7101. }
  7102. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(op);
  7103. Js::AuxArray<uint32> *spreadIndices = nullptr;
  7104. actualArgCount = EmitArgList(pnode->sxCall.pnodeArgs, Js::Constants::NoRegister, Js::Constants::NoRegister, Js::Constants::NoRegister,
  7105. false, true, byteCodeGenerator, funcInfo, callSiteId, pnode->sxCall.spreadArgCount, &spreadIndices);
  7106. funcInfo->ReleaseLoc(pnode->sxCall.pnodeTarget);
  7107. if (pnode->sxCall.spreadArgCount > 0)
  7108. {
  7109. Assert(spreadIndices != nullptr);
  7110. uint spreadExtraAlloc = spreadIndices->count * sizeof(uint32);
  7111. uint spreadIndicesSize = sizeof(*spreadIndices) + spreadExtraAlloc;
  7112. byteCodeGenerator->Writer()->CallIExtended(op, funcInfo->AcquireLoc(pnode), pnode->sxCall.pnodeTarget->location,
  7113. (uint16)actualArgCount, Js::CallIExtended_SpreadArgs,
  7114. spreadIndices, spreadIndicesSize, callSiteId);
  7115. }
  7116. else
  7117. {
  7118. byteCodeGenerator->Writer()->CallI(op, funcInfo->AcquireLoc(pnode), pnode->sxCall.pnodeTarget->location,
  7119. (uint16)actualArgCount, callSiteId);
  7120. }
  7121. }
  7122. Assert(argCount == actualArgCount);
  7123. }
  7124. // End call, pop param space
  7125. funcInfo->EndRecordingOutArgs(argCount);
  7126. return;
  7127. }
  7128. void EmitCall(
  7129. ParseNode* pnode,
  7130. Js::RegSlot rhsLocation,
  7131. ByteCodeGenerator* byteCodeGenerator,
  7132. FuncInfo* funcInfo,
  7133. BOOL fReturnValue,
  7134. BOOL fEvaluateComponents,
  7135. BOOL fHasNewTarget,
  7136. Js::RegSlot overrideThisLocation)
  7137. {
  7138. BOOL fIsPut = (rhsLocation != Js::Constants::NoRegister);
  7139. // If the call returns a float, we'll note this in the byte code.
  7140. Js::RegSlot thisLocation = Js::Constants::NoRegister;
  7141. Js::RegSlot callObjLocation = Js::Constants::NoRegister;
  7142. Js::RegSlot newTargetLocation = Js::Constants::NoRegister;
  7143. BOOL fSideEffectArgs = FALSE;
  7144. ParseNode *pnodeTarget = pnode->sxCall.pnodeTarget;
  7145. ParseNode *pnodeArgs = pnode->sxCall.pnodeArgs;
  7146. uint16 spreadArgCount = pnode->sxCall.spreadArgCount;
  7147. if (CreateNativeArrays(byteCodeGenerator, funcInfo) && CallTargetIsArray(pnode->sxCall.pnodeTarget)) {
  7148. // some minifiers (potentially incorrectly) assume that "v = new Array()" and "v = Array()" are equivalent,
  7149. // and replace the former with the latter to save 4 characters. What that means for us is that it, at least
  7150. // initially, uses the "Call" path. We want to guess that it _is_ just "new Array()" and change over to the
  7151. // "new" path, since then our native array handling can kick in.
  7152. /*EmitNew(pnode, byteCodeGenerator, funcInfo);
  7153. return;*/
  7154. }
  7155. unsigned int argCount = CountArguments(pnode->sxCall.pnodeArgs, &fSideEffectArgs) + (unsigned int)fIsPut;
  7156. BOOL fIsEval = !fIsPut && pnode->sxCall.isEvalCall;
  7157. if (fIsEval)
  7158. {
  7159. Assert(!fHasNewTarget);
  7160. //
  7161. // "eval" takes the closure environment as an extra argument
  7162. // Pass the closure env only if some argument is passed
  7163. // For just eval(), don't pass the closure environment
  7164. //
  7165. if (argCount > 1)
  7166. {
  7167. // Check the module ID as well. If it's not the global (default) module,
  7168. // we need to pass the root to eval so it can do the right global lookups.
  7169. // (Passing the module root is the least disruptive way to get the module ID
  7170. // to the helper, given the current set of byte codes. Once we have a full set
  7171. // of byte code ops taking immediate opnds, passing the ID is more intuitive.)
  7172. Js::ModuleID moduleID = byteCodeGenerator->GetModuleID();
  7173. if (moduleID == kmodGlobal)
  7174. {
  7175. argCount++;
  7176. }
  7177. else
  7178. {
  7179. // Module ID must be passed
  7180. argCount += 2;
  7181. }
  7182. }
  7183. }
  7184. if (fHasNewTarget)
  7185. {
  7186. Assert(!fIsEval);
  7187. // When we need to pass new.target explicitly, it is passed as an extra argument.
  7188. // This is similar to how eval passes an extra argument for the frame display and is
  7189. // used to support cases where we need to pass both 'this' and new.target as part of
  7190. // a function call.
  7191. // OpCode::LdNewTarget knows how to look at the call flags and fetch this argument.
  7192. argCount++;
  7193. newTargetLocation = funcInfo->newTargetRegister;
  7194. Assert(newTargetLocation != Js::Constants::NoRegister);
  7195. }
  7196. Js::ArgSlot argSlotCount = (Js::ArgSlot)argCount;
  7197. if (argCount != (unsigned int)argSlotCount)
  7198. {
  7199. Js::Throw::OutOfMemory();
  7200. }
  7201. if (fReturnValue)
  7202. {
  7203. pnode->isUsed = true;
  7204. }
  7205. //
  7206. // Set up the call.
  7207. //
  7208. if (!fEvaluateComponents)
  7209. {
  7210. EmitCallTargetNoEvalComponents(pnodeTarget, fSideEffectArgs, &thisLocation, &callObjLocation, byteCodeGenerator, funcInfo);
  7211. }
  7212. else
  7213. {
  7214. EmitCallTarget(pnodeTarget, fSideEffectArgs, &thisLocation, &callObjLocation, byteCodeGenerator, funcInfo);
  7215. }
  7216. bool releaseThisLocation = true;
  7217. // If we are strictly overriding the this location, ignore what the call target set this location to.
  7218. if (overrideThisLocation != Js::Constants::NoRegister)
  7219. {
  7220. thisLocation = overrideThisLocation;
  7221. releaseThisLocation = false;
  7222. }
  7223. // Evaluate the arguments (nothing mode-specific here).
  7224. // Start call, allocate out param space
  7225. funcInfo->StartRecordingOutArgs(argSlotCount);
  7226. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  7227. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, argSlotCount);
  7228. Js::AuxArray<uint32> *spreadIndices;
  7229. Js::ArgSlot actualArgCount = EmitArgList(pnodeArgs, rhsLocation, thisLocation, newTargetLocation, fIsEval, fEvaluateComponents, byteCodeGenerator, funcInfo, callSiteId, spreadArgCount, &spreadIndices);
  7230. Assert(argSlotCount == actualArgCount);
  7231. if (!fEvaluateComponents)
  7232. {
  7233. EmitCallInstrNoEvalComponents(pnode, fIsPut, fIsEval, thisLocation, callObjLocation, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7234. }
  7235. else
  7236. {
  7237. EmitCallInstr(pnode, fIsPut, fIsEval, fHasNewTarget, releaseThisLocation ? thisLocation : Js::Constants::NoRegister, callObjLocation, actualArgCount, byteCodeGenerator, funcInfo, callSiteId, spreadIndices);
  7238. }
  7239. // End call, pop param space
  7240. funcInfo->EndRecordingOutArgs(argSlotCount);
  7241. }
  7242. void EmitInvoke(
  7243. Js::RegSlot location,
  7244. Js::RegSlot callObjLocation,
  7245. Js::PropertyId propertyId,
  7246. ByteCodeGenerator* byteCodeGenerator,
  7247. FuncInfo* funcInfo)
  7248. {
  7249. EmitMethodFld(false, false, location, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7250. funcInfo->StartRecordingOutArgs(1);
  7251. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  7252. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, 1);
  7253. EmitArgListStart(callObjLocation, byteCodeGenerator, funcInfo, callSiteId);
  7254. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallI, location, location, 1, callSiteId);
  7255. }
  7256. void EmitInvoke(
  7257. Js::RegSlot location,
  7258. Js::RegSlot callObjLocation,
  7259. Js::PropertyId propertyId,
  7260. ByteCodeGenerator* byteCodeGenerator,
  7261. FuncInfo* funcInfo,
  7262. Js::RegSlot arg1Location)
  7263. {
  7264. EmitMethodFld(false, false, location, callObjLocation, propertyId, byteCodeGenerator, funcInfo);
  7265. funcInfo->StartRecordingOutArgs(2);
  7266. Js::ProfileId callSiteId = byteCodeGenerator->GetNextCallSiteId(Js::OpCode::CallI);
  7267. byteCodeGenerator->Writer()->StartCall(Js::OpCode::StartCall, 2);
  7268. EmitArgListStart(callObjLocation, byteCodeGenerator, funcInfo, callSiteId);
  7269. byteCodeGenerator->Writer()->ArgOut<true>(1, arg1Location, callSiteId);
  7270. byteCodeGenerator->Writer()->CallI(Js::OpCode::CallI, location, location, 2, callSiteId);
  7271. }
  7272. void EmitComputedFunctionNameVar(ParseNode *nameNode, ParseNode *exprNode, ByteCodeGenerator *byteCodeGenerator)
  7273. {
  7274. AssertMsg(exprNode != nullptr, "callers of this function should pass in a valid expression Node");
  7275. if (nameNode == nullptr)
  7276. {
  7277. return;
  7278. }
  7279. if ((exprNode->nop == knopFncDecl && (exprNode->sxFnc.pnodeName == nullptr || exprNode->sxFnc.pnodeName->nop != knopVarDecl)))
  7280. {
  7281. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SetComputedNameVar, exprNode->location, nameNode->location);
  7282. }
  7283. }
  7284. void EmitMemberNode(ParseNode *memberNode, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, ParseNode* parentNode, bool useStore, bool* isObjectEmpty = nullptr)
  7285. {
  7286. ParseNode *nameNode = memberNode->sxBin.pnode1;
  7287. ParseNode *exprNode = memberNode->sxBin.pnode2;
  7288. bool isFncDecl = exprNode->nop == knopFncDecl;
  7289. bool isClassMember = isFncDecl && exprNode->sxFnc.IsClassMember();
  7290. // Moved SetComputedNameVar before LdFld of prototype because loading the prototype undefers the function TypeHandler
  7291. // which makes this bytecode too late to influence the function.name.
  7292. if (nameNode->nop == knopComputedName)
  7293. {
  7294. // Computed property name
  7295. // Transparently pass the name expr
  7296. // The Emit will replace this with a temp register if necessary to preserve the value.
  7297. nameNode->location = nameNode->sxUni.pnode1->location;
  7298. EmitBinaryOpnds(nameNode, exprNode, byteCodeGenerator, funcInfo);
  7299. if (isFncDecl && !exprNode->sxFnc.IsClassConstructor())
  7300. {
  7301. EmitComputedFunctionNameVar(nameNode, exprNode, byteCodeGenerator);
  7302. }
  7303. }
  7304. // Classes allocates a RegSlot as part of Instance Methods EmitClassInitializers,
  7305. // but if we don't have any members then we don't need to load the prototype.
  7306. Assert(isClassMember == (isObjectEmpty != nullptr));
  7307. if (isClassMember && *isObjectEmpty)
  7308. {
  7309. *isObjectEmpty = false;
  7310. int cacheId = funcInfo->FindOrAddInlineCacheId(parentNode->location, Js::PropertyIds::prototype, false, false);
  7311. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, objectLocation, parentNode->location, cacheId);
  7312. }
  7313. if (nameNode->nop == knopComputedName)
  7314. {
  7315. Assert(memberNode->nop == knopGetMember || memberNode->nop == knopSetMember || memberNode->nop == knopMember);
  7316. Js::OpCode setOp = memberNode->nop == knopGetMember ?
  7317. (isClassMember ? Js::OpCode::InitClassMemberGetComputedName : Js::OpCode::InitGetElemI) :
  7318. memberNode->nop == knopSetMember ?
  7319. (isClassMember ? Js::OpCode::InitClassMemberSetComputedName : Js::OpCode::InitSetElemI) :
  7320. (isClassMember ? Js::OpCode::InitClassMemberComputedName : Js::OpCode::InitComputedProperty);
  7321. byteCodeGenerator->Writer()->Element(setOp, exprNode->location, objectLocation, nameNode->location, true);
  7322. // Class and object members need a reference back to the class.
  7323. if (isFncDecl)
  7324. {
  7325. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SetHomeObj, exprNode->location, objectLocation);
  7326. }
  7327. funcInfo->ReleaseLoc(exprNode);
  7328. funcInfo->ReleaseLoc(nameNode);
  7329. return;
  7330. }
  7331. Js::OpCode stFldOpCode = (Js::OpCode)0;
  7332. if (useStore)
  7333. {
  7334. stFldOpCode = ByteCodeGenerator::GetStFldOpCode(funcInfo, false, false, false, isClassMember);
  7335. }
  7336. Emit(exprNode, byteCodeGenerator, funcInfo, false);
  7337. Js::PropertyId propertyId = nameNode->sxPid.PropertyIdFromNameNode();
  7338. if (Js::PropertyIds::name == propertyId
  7339. && exprNode->nop == knopFncDecl
  7340. && exprNode->sxFnc.IsStaticMember()
  7341. && parentNode != nullptr && parentNode->nop == knopClassDecl
  7342. && parentNode->sxClass.pnodeConstructor != nullptr)
  7343. {
  7344. Js::ParseableFunctionInfo* nameFunc = parentNode->sxClass.pnodeConstructor->sxFnc.funcInfo->byteCodeFunction->GetParseableFunctionInfo();
  7345. nameFunc->SetIsStaticNameFunction(true);
  7346. }
  7347. if (memberNode->nop == knopMember || memberNode->nop == knopMemberShort)
  7348. {
  7349. // The internal prototype should be set only if the production is of the form PropertyDefinition : PropertyName : AssignmentExpression
  7350. if (propertyId == Js::PropertyIds::__proto__ && memberNode->nop != knopMemberShort && (exprNode->nop != knopFncDecl || !exprNode->sxFnc.IsMethod()))
  7351. {
  7352. byteCodeGenerator->Writer()->Property(Js::OpCode::InitProto, exprNode->location, objectLocation,
  7353. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  7354. }
  7355. else
  7356. {
  7357. uint cacheId = funcInfo->FindOrAddInlineCacheId(objectLocation, propertyId, false, true);
  7358. Js::OpCode patchablePropertyOpCode;
  7359. if (useStore)
  7360. {
  7361. patchablePropertyOpCode = stFldOpCode;
  7362. }
  7363. else if (isClassMember)
  7364. {
  7365. patchablePropertyOpCode = Js::OpCode::InitClassMember;
  7366. }
  7367. else
  7368. {
  7369. patchablePropertyOpCode = Js::OpCode::InitFld;
  7370. }
  7371. byteCodeGenerator->Writer()->PatchableProperty(patchablePropertyOpCode, exprNode->location, objectLocation, cacheId);
  7372. }
  7373. }
  7374. else
  7375. {
  7376. Assert(memberNode->nop == knopGetMember || memberNode->nop == knopSetMember);
  7377. Js::OpCode setOp = memberNode->nop == knopGetMember ?
  7378. (isClassMember ? Js::OpCode::InitClassMemberGet : Js::OpCode::InitGetFld) :
  7379. (isClassMember ? Js::OpCode::InitClassMemberSet : Js::OpCode::InitSetFld);
  7380. byteCodeGenerator->Writer()->Property(setOp, exprNode->location, objectLocation, funcInfo->FindOrAddReferencedPropertyId(propertyId));
  7381. }
  7382. // Class and object members need a reference back to the class.
  7383. if (isFncDecl)
  7384. {
  7385. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SetHomeObj, exprNode->location, objectLocation);
  7386. }
  7387. funcInfo->ReleaseLoc(exprNode);
  7388. if (propertyId == Js::PropertyIds::valueOf)
  7389. {
  7390. byteCodeGenerator->GetScriptContext()->optimizationOverrides.SetSideEffects(Js::SideEffects_ValueOf);
  7391. }
  7392. else if (propertyId == Js::PropertyIds::toString)
  7393. {
  7394. byteCodeGenerator->GetScriptContext()->optimizationOverrides.SetSideEffects(Js::SideEffects_ToString);
  7395. }
  7396. }
  7397. void EmitClassInitializers(ParseNode *memberList, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, ParseNode* parentNode, bool isObjectEmpty)
  7398. {
  7399. if (memberList != nullptr)
  7400. {
  7401. while (memberList->nop == knopList)
  7402. {
  7403. ParseNode *memberNode = memberList->sxBin.pnode1;
  7404. EmitMemberNode(memberNode, objectLocation, byteCodeGenerator, funcInfo, parentNode, /*useStore*/ false, &isObjectEmpty);
  7405. memberList = memberList->sxBin.pnode2;
  7406. }
  7407. EmitMemberNode(memberList, objectLocation, byteCodeGenerator, funcInfo, parentNode, /*useStore*/ false, &isObjectEmpty);
  7408. }
  7409. }
  7410. void EmitObjectInitializers(ParseNode *memberList, Js::RegSlot objectLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7411. {
  7412. ParseNode *pmemberList = memberList;
  7413. unsigned int argCount = 0;
  7414. uint32 value;
  7415. Js::PropertyId propertyId;
  7416. //
  7417. // 1. Add all non-int property ids to a dictionary propertyIds with value true
  7418. // 2. Get the count of propertyIds
  7419. // 3. Create a propertyId array of size count
  7420. // 4. Put the propIds in the auxiliary area
  7421. // 5. Get the objectLiteralCacheId
  7422. // 6. Generate propId inits with values
  7423. //
  7424. // Handle propertyId collision
  7425. typedef JsUtil::BaseHashSet<Js::PropertyId, ArenaAllocator, PowerOf2SizePolicy> PropertyIdSet;
  7426. PropertyIdSet* propertyIds = Anew(byteCodeGenerator->GetAllocator(), PropertyIdSet, byteCodeGenerator->GetAllocator(), 17);
  7427. bool hasComputedName = false;
  7428. if (memberList != nullptr)
  7429. {
  7430. while (memberList->nop == knopList)
  7431. {
  7432. if (memberList->sxBin.pnode1->sxBin.pnode1->nop == knopComputedName)
  7433. {
  7434. hasComputedName = true;
  7435. break;
  7436. }
  7437. propertyId = memberList->sxBin.pnode1->sxBin.pnode1->sxPid.PropertyIdFromNameNode();
  7438. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value))
  7439. {
  7440. propertyIds->Item(propertyId);
  7441. }
  7442. memberList = memberList->sxBin.pnode2;
  7443. }
  7444. if (memberList->sxBin.pnode1->nop != knopComputedName && !hasComputedName)
  7445. {
  7446. propertyId = memberList->sxBin.pnode1->sxPid.PropertyIdFromNameNode();
  7447. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value))
  7448. {
  7449. propertyIds->Item(propertyId);
  7450. }
  7451. }
  7452. }
  7453. argCount = propertyIds->Count();
  7454. memberList = pmemberList;
  7455. if ((memberList == nullptr) || (argCount == 0))
  7456. {
  7457. // Empty literal or numeric property only object literal
  7458. byteCodeGenerator->Writer()->Reg1(Js::OpCode::NewScObjectSimple, objectLocation);
  7459. }
  7460. else
  7461. {
  7462. Js::PropertyIdArray *propIds = AnewPlus(byteCodeGenerator->GetAllocator(), argCount * sizeof(Js::PropertyId), Js::PropertyIdArray, argCount, 0);
  7463. if (propertyIds->ContainsKey(Js::PropertyIds::__proto__))
  7464. {
  7465. // Always record whether the initializer contains __proto__ no matter if current environment has it enabled
  7466. // or not, in case the bytecode is later run with __proto__ enabled.
  7467. propIds->has__proto__ = true;
  7468. }
  7469. unsigned int argIndex = 0;
  7470. while (memberList->nop == knopList)
  7471. {
  7472. if (memberList->sxBin.pnode1->sxBin.pnode1->nop == knopComputedName)
  7473. {
  7474. break;
  7475. }
  7476. propertyId = memberList->sxBin.pnode1->sxBin.pnode1->sxPid.PropertyIdFromNameNode();
  7477. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value) && propertyIds->Remove(propertyId))
  7478. {
  7479. propIds->elements[argIndex] = propertyId;
  7480. argIndex++;
  7481. }
  7482. memberList = memberList->sxBin.pnode2;
  7483. }
  7484. if (memberList->sxBin.pnode1->nop != knopComputedName && !hasComputedName)
  7485. {
  7486. propertyId = memberList->sxBin.pnode1->sxPid.PropertyIdFromNameNode();
  7487. if (!byteCodeGenerator->GetScriptContext()->IsNumericPropertyId(propertyId, &value) && propertyIds->Remove(propertyId))
  7488. {
  7489. propIds->elements[argIndex] = propertyId;
  7490. argIndex++;
  7491. }
  7492. }
  7493. uint32 literalObjectId = funcInfo->GetParsedFunctionBody()->NewObjectLiteral();
  7494. // Generate the opcode with propIds and cacheId
  7495. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::NewScObjectLiteral, objectLocation, propIds, sizeof(Js::PropertyIdArray) + argCount * sizeof(Js::PropertyId), literalObjectId);
  7496. Adelete(byteCodeGenerator->GetAllocator(), propertyIds);
  7497. AdeletePlus(byteCodeGenerator->GetAllocator(), argCount * sizeof(Js::PropertyId), propIds);
  7498. }
  7499. memberList = pmemberList;
  7500. bool useStore = false;
  7501. // Generate the actual assignment to those properties
  7502. if (memberList != nullptr)
  7503. {
  7504. while (memberList->nop == knopList)
  7505. {
  7506. ParseNode *memberNode = memberList->sxBin.pnode1;
  7507. if (memberNode->sxBin.pnode1->nop == knopComputedName)
  7508. {
  7509. useStore = true;
  7510. }
  7511. byteCodeGenerator->StartSubexpression(memberNode);
  7512. EmitMemberNode(memberNode, objectLocation, byteCodeGenerator, funcInfo, nullptr, useStore);
  7513. byteCodeGenerator->EndSubexpression(memberNode);
  7514. memberList = memberList->sxBin.pnode2;
  7515. }
  7516. byteCodeGenerator->StartSubexpression(memberList);
  7517. EmitMemberNode(memberList, objectLocation, byteCodeGenerator, funcInfo, nullptr, useStore);
  7518. byteCodeGenerator->EndSubexpression(memberList);
  7519. }
  7520. }
  7521. void EmitStringTemplate(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7522. {
  7523. Assert(pnode->sxStrTemplate.pnodeStringLiterals);
  7524. // For a tagged string template, we will create the callsite constant object as part of the FunctionBody constants table.
  7525. // We only need to emit code for non-tagged string templates here.
  7526. if (!pnode->sxStrTemplate.isTaggedTemplate)
  7527. {
  7528. // If we have no substitutions and this is not a tagged template, we can emit just the single cooked string.
  7529. if (pnode->sxStrTemplate.pnodeSubstitutionExpressions == nullptr)
  7530. {
  7531. Assert(pnode->sxStrTemplate.pnodeStringLiterals->nop != knopList);
  7532. funcInfo->AcquireLoc(pnode);
  7533. Emit(pnode->sxStrTemplate.pnodeStringLiterals, byteCodeGenerator, funcInfo, false);
  7534. Assert(pnode->location != pnode->sxStrTemplate.pnodeStringLiterals->location);
  7535. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxStrTemplate.pnodeStringLiterals->location);
  7536. funcInfo->ReleaseLoc(pnode->sxStrTemplate.pnodeStringLiterals);
  7537. }
  7538. else
  7539. {
  7540. // If we have substitutions but no tag function, we can skip the callSite object construction (and also ignore raw strings).
  7541. funcInfo->AcquireLoc(pnode);
  7542. // First string must be a list node since we have substitutions.
  7543. AssertMsg(pnode->sxStrTemplate.pnodeStringLiterals->nop == knopList, "First string in the list must be a knopList node.");
  7544. ParseNode* stringNodeList = pnode->sxStrTemplate.pnodeStringLiterals;
  7545. // Emit the first string and load that into the pnode location.
  7546. Emit(stringNodeList->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  7547. Assert(pnode->location != stringNodeList->sxBin.pnode1->location);
  7548. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, stringNodeList->sxBin.pnode1->location);
  7549. funcInfo->ReleaseLoc(stringNodeList->sxBin.pnode1);
  7550. ParseNode* expressionNodeList = pnode->sxStrTemplate.pnodeSubstitutionExpressions;
  7551. ParseNode* stringNode;
  7552. ParseNode* expressionNode;
  7553. // Now append the substitution expressions and remaining string constants via normal add operator
  7554. // We will always have one more string constant than substitution expression
  7555. // `strcon1 ${expr1} strcon2 ${expr2} strcon3` = strcon1 + expr1 + strcon2 + expr2 + strcon3
  7556. //
  7557. // strcon1 --- step 1 (above)
  7558. // expr1 \__ step 2
  7559. // strcon2 /
  7560. // expr2 \__ step 3
  7561. // strcon3 /
  7562. while (stringNodeList->nop == knopList)
  7563. {
  7564. // If the current head of the expression list is a list, fetch the node and walk the list.
  7565. if (expressionNodeList->nop == knopList)
  7566. {
  7567. expressionNode = expressionNodeList->sxBin.pnode1;
  7568. expressionNodeList = expressionNodeList->sxBin.pnode2;
  7569. }
  7570. else
  7571. {
  7572. // This is the last element of the expression list.
  7573. expressionNode = expressionNodeList;
  7574. }
  7575. // Emit the expression and append it to the string we're building.
  7576. Emit(expressionNode, byteCodeGenerator, funcInfo, false);
  7577. Js::RegSlot toStringLocation = funcInfo->AcquireTmpRegister();
  7578. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Str, toStringLocation, expressionNode->location);
  7579. byteCodeGenerator->Writer()->Reg3(Js::OpCode::Add_A, pnode->location, pnode->location, toStringLocation);
  7580. funcInfo->ReleaseTmpRegister(toStringLocation);
  7581. funcInfo->ReleaseLoc(expressionNode);
  7582. // Move to the next string in the list - we already got ahead of the expressions in the first string literal above.
  7583. stringNodeList = stringNodeList->sxBin.pnode2;
  7584. // If the current head of the string literal list is also a list node, need to fetch the actual string literal node.
  7585. if (stringNodeList->nop == knopList)
  7586. {
  7587. stringNode = stringNodeList->sxBin.pnode1;
  7588. }
  7589. else
  7590. {
  7591. // This is the last element of the string literal list.
  7592. stringNode = stringNodeList;
  7593. }
  7594. // Emit the string node following the previous expression and append it to the string.
  7595. // This is either just some string in the list or it is the last string.
  7596. Emit(stringNode, byteCodeGenerator, funcInfo, false);
  7597. byteCodeGenerator->Writer()->Reg3(Js::OpCode::Add_A, pnode->location, pnode->location, stringNode->location);
  7598. funcInfo->ReleaseLoc(stringNode);
  7599. }
  7600. }
  7601. }
  7602. }
  7603. void SetNewArrayElements(ParseNode *pnode, Js::RegSlot arrayLocation, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7604. {
  7605. ParseNode *args = pnode->sxUni.pnode1;
  7606. uint argCount = pnode->sxArrLit.count;
  7607. uint spreadCount = pnode->sxArrLit.spreadCount;
  7608. bool nativeArrays = CreateNativeArrays(byteCodeGenerator, funcInfo);
  7609. bool arrayIntOpt = nativeArrays && pnode->sxArrLit.arrayOfInts;
  7610. if (arrayIntOpt)
  7611. {
  7612. int extraAlloc = argCount * sizeof(int32);
  7613. Js::AuxArray<int> *ints = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<int32>, argCount);
  7614. EmitConstantArgsToIntArray(byteCodeGenerator, ints->elements, args, argCount);
  7615. Assert(!pnode->sxArrLit.hasMissingValues);
  7616. byteCodeGenerator->Writer()->Auxiliary(
  7617. Js::OpCode::NewScIntArray,
  7618. pnode->location,
  7619. ints,
  7620. sizeof(Js::AuxArray<int>) + extraAlloc,
  7621. argCount);
  7622. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, ints);
  7623. return;
  7624. }
  7625. bool arrayNumOpt = nativeArrays && pnode->sxArrLit.arrayOfNumbers;
  7626. if (arrayNumOpt)
  7627. {
  7628. int extraAlloc = argCount * sizeof(double);
  7629. Js::AuxArray<double> *doubles = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<double>, argCount);
  7630. EmitConstantArgsToFltArray(byteCodeGenerator, doubles->elements, args, argCount);
  7631. Assert(!pnode->sxArrLit.hasMissingValues);
  7632. byteCodeGenerator->Writer()->Auxiliary(
  7633. Js::OpCode::NewScFltArray,
  7634. pnode->location,
  7635. doubles,
  7636. sizeof(Js::AuxArray<double>) + extraAlloc,
  7637. argCount);
  7638. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, doubles);
  7639. return;
  7640. }
  7641. bool arrayLitOpt = pnode->sxArrLit.arrayOfTaggedInts && pnode->sxArrLit.count > 1;
  7642. Assert(!arrayLitOpt || !nativeArrays);
  7643. Js::RegSlot spreadArrLoc = arrayLocation;
  7644. Js::AuxArray<uint32> *spreadIndices = nullptr;
  7645. const uint extraAlloc = spreadCount * sizeof(uint32);
  7646. if (pnode->sxArrLit.spreadCount > 0)
  7647. {
  7648. arrayLocation = funcInfo->AcquireTmpRegister();
  7649. spreadIndices = AnewPlus(byteCodeGenerator->GetAllocator(), extraAlloc, Js::AuxArray<uint32>, spreadCount);
  7650. }
  7651. byteCodeGenerator->Writer()->Reg1Unsigned1(
  7652. pnode->sxArrLit.hasMissingValues ? Js::OpCode::NewScArrayWithMissingValues : Js::OpCode::NewScArray,
  7653. arrayLocation,
  7654. argCount);
  7655. if (args != nullptr)
  7656. {
  7657. Js::OpCode opcode;
  7658. Js::RegSlot arrLoc;
  7659. if (argCount == 1 && !byteCodeGenerator->Writer()->DoProfileNewScArrayOp(Js::OpCode::NewScArray))
  7660. {
  7661. opcode = Js::OpCode::StArrItemC_CI4;
  7662. arrLoc = arrayLocation;
  7663. }
  7664. else if (arrayLitOpt)
  7665. {
  7666. opcode = Js::OpCode::StArrSegItem_A;
  7667. arrLoc = funcInfo->AcquireTmpRegister();
  7668. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdArrHead, arrLoc, arrayLocation);
  7669. }
  7670. else if (Js::JavascriptArray::HasInlineHeadSegment(argCount))
  7671. {
  7672. // The head segment will be allocated inline as an interior pointer. To keep the array alive, the set operation
  7673. // should be done relative to the array header to keep it alive (instead of the array segment).
  7674. opcode = Js::OpCode::StArrInlineItem_CI4;
  7675. arrLoc = arrayLocation;
  7676. }
  7677. else if (argCount <= Js::JavascriptArray::MaxInitialDenseLength)
  7678. {
  7679. opcode = Js::OpCode::StArrSegItem_CI4;
  7680. arrLoc = funcInfo->AcquireTmpRegister();
  7681. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdArrHead, arrLoc, arrayLocation);
  7682. }
  7683. else
  7684. {
  7685. opcode = Js::OpCode::StArrItemI_CI4;
  7686. arrLoc = arrayLocation;
  7687. }
  7688. if (arrayLitOpt)
  7689. {
  7690. Js::VarArray *vars = AnewPlus(byteCodeGenerator->GetAllocator(), argCount * sizeof(Js::Var), Js::VarArray, argCount);
  7691. EmitConstantArgsToVarArray(byteCodeGenerator, vars->elements, args, argCount);
  7692. // Generate the opcode with vars
  7693. byteCodeGenerator->Writer()->Auxiliary(Js::OpCode::StArrSegItem_A, arrLoc, vars, sizeof(Js::VarArray) + argCount * sizeof(Js::Var), argCount);
  7694. AdeletePlus(byteCodeGenerator->GetAllocator(), argCount * sizeof(Js::Var), vars);
  7695. }
  7696. else
  7697. {
  7698. uint i = 0;
  7699. unsigned spreadIndex = 0;
  7700. Js::RegSlot rhsLocation;
  7701. while (args->nop == knopList)
  7702. {
  7703. if (args->sxBin.pnode1->nop != knopEmpty)
  7704. {
  7705. Emit(args->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  7706. rhsLocation = args->sxBin.pnode1->location;
  7707. Js::RegSlot regVal = rhsLocation;
  7708. if (args->sxBin.pnode1->nop == knopEllipsis)
  7709. {
  7710. AnalysisAssert(spreadIndices);
  7711. regVal = funcInfo->AcquireTmpRegister();
  7712. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, rhsLocation);
  7713. spreadIndices->elements[spreadIndex++] = i;
  7714. }
  7715. byteCodeGenerator->Writer()->ElementUnsigned1(opcode, regVal, arrLoc, i);
  7716. if (args->sxBin.pnode1->nop == knopEllipsis)
  7717. {
  7718. funcInfo->ReleaseTmpRegister(regVal);
  7719. }
  7720. funcInfo->ReleaseLoc(args->sxBin.pnode1);
  7721. }
  7722. args = args->sxBin.pnode2;
  7723. i++;
  7724. }
  7725. if (args->nop != knopEmpty)
  7726. {
  7727. Emit(args, byteCodeGenerator, funcInfo, false);
  7728. rhsLocation = args->location;
  7729. Js::RegSlot regVal = rhsLocation;
  7730. if (args->nop == knopEllipsis)
  7731. {
  7732. regVal = funcInfo->AcquireTmpRegister();
  7733. byteCodeGenerator->Writer()->Reg2(Js::OpCode::LdCustomSpreadIteratorList, regVal, rhsLocation);
  7734. AnalysisAssert(spreadIndices);
  7735. spreadIndices->elements[spreadIndex] = i;
  7736. }
  7737. byteCodeGenerator->Writer()->ElementUnsigned1(opcode, regVal, arrLoc, i);
  7738. if (args->nop == knopEllipsis)
  7739. {
  7740. funcInfo->ReleaseTmpRegister(regVal);
  7741. }
  7742. funcInfo->ReleaseLoc(args);
  7743. i++;
  7744. }
  7745. Assert(i <= argCount);
  7746. }
  7747. if (arrLoc != arrayLocation)
  7748. {
  7749. funcInfo->ReleaseTmpRegister(arrLoc);
  7750. }
  7751. }
  7752. if (pnode->sxArrLit.spreadCount > 0)
  7753. {
  7754. byteCodeGenerator->Writer()->Reg2Aux(Js::OpCode::SpreadArrayLiteral, spreadArrLoc, arrayLocation, spreadIndices, sizeof(Js::AuxArray<uint32>) + extraAlloc, extraAlloc);
  7755. AdeletePlus(byteCodeGenerator->GetAllocator(), extraAlloc, spreadIndices);
  7756. funcInfo->ReleaseTmpRegister(arrayLocation);
  7757. }
  7758. }
  7759. // FIX: TODO: mixed-mode expressions (arithmetic expressions mixed with boolean expressions); current solution
  7760. // will not short-circuit in some cases and is not complete (for example: var i=(x==y))
  7761. // This uses Aho and Ullman style double-branch generation (p. 494 ASU); we will need to peephole optimize or replace
  7762. // with special case for single-branch style.
  7763. void EmitBooleanExpression(ParseNode *expr, Js::ByteCodeLabel trueLabel, Js::ByteCodeLabel falseLabel, ByteCodeGenerator *byteCodeGenerator,
  7764. FuncInfo *funcInfo)
  7765. {
  7766. byteCodeGenerator->StartStatement(expr);
  7767. switch (expr->nop)
  7768. {
  7769. case knopLogOr:
  7770. {
  7771. Js::ByteCodeLabel leftFalse = byteCodeGenerator->Writer()->DefineLabel();
  7772. EmitBooleanExpression(expr->sxBin.pnode1, trueLabel, leftFalse, byteCodeGenerator, funcInfo);
  7773. funcInfo->ReleaseLoc(expr->sxBin.pnode1);
  7774. byteCodeGenerator->Writer()->MarkLabel(leftFalse);
  7775. EmitBooleanExpression(expr->sxBin.pnode2, trueLabel, falseLabel, byteCodeGenerator, funcInfo);
  7776. funcInfo->ReleaseLoc(expr->sxBin.pnode2);
  7777. break;
  7778. }
  7779. case knopLogAnd:
  7780. {
  7781. Js::ByteCodeLabel leftTrue = byteCodeGenerator->Writer()->DefineLabel();
  7782. EmitBooleanExpression(expr->sxBin.pnode1, leftTrue, falseLabel, byteCodeGenerator, funcInfo);
  7783. funcInfo->ReleaseLoc(expr->sxBin.pnode1);
  7784. byteCodeGenerator->Writer()->MarkLabel(leftTrue);
  7785. EmitBooleanExpression(expr->sxBin.pnode2, trueLabel, falseLabel, byteCodeGenerator, funcInfo);
  7786. funcInfo->ReleaseLoc(expr->sxBin.pnode2);
  7787. break;
  7788. }
  7789. case knopLogNot:
  7790. EmitBooleanExpression(expr->sxUni.pnode1, falseLabel, trueLabel, byteCodeGenerator, funcInfo);
  7791. funcInfo->ReleaseLoc(expr->sxUni.pnode1);
  7792. break;
  7793. case knopEq:
  7794. case knopEqv:
  7795. case knopNEqv:
  7796. case knopNe:
  7797. case knopLt:
  7798. case knopLe:
  7799. case knopGe:
  7800. case knopGt:
  7801. EmitBinaryOpnds(expr->sxBin.pnode1, expr->sxBin.pnode2, byteCodeGenerator, funcInfo);
  7802. funcInfo->ReleaseLoc(expr->sxBin.pnode2);
  7803. funcInfo->ReleaseLoc(expr->sxBin.pnode1);
  7804. byteCodeGenerator->Writer()->BrReg2(nopToOp[expr->nop], trueLabel, expr->sxBin.pnode1->location,
  7805. expr->sxBin.pnode2->location);
  7806. byteCodeGenerator->Writer()->Br(falseLabel);
  7807. break;
  7808. case knopTrue:
  7809. byteCodeGenerator->Writer()->Br(trueLabel);
  7810. break;
  7811. case knopFalse:
  7812. byteCodeGenerator->Writer()->Br(falseLabel);
  7813. break;
  7814. default:
  7815. // Note: we usually release the temp assigned to a node after we Emit it.
  7816. // But in this case, EmitBooleanExpression is just a wrapper around a normal Emit call,
  7817. // and the caller of EmitBooleanExpression expects to be able to release this register.
  7818. Emit(expr, byteCodeGenerator, funcInfo, false);
  7819. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7820. byteCodeGenerator->Writer()->Br(falseLabel);
  7821. break;
  7822. }
  7823. byteCodeGenerator->EndStatement(expr);
  7824. }
  7825. void EmitGeneratingBooleanExpression(ParseNode *expr, Js::ByteCodeLabel trueLabel, bool truefallthrough, Js::ByteCodeLabel falseLabel, bool falsefallthrough, Js::RegSlot writeto,
  7826. ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  7827. {
  7828. switch (expr->nop)
  7829. {
  7830. case knopLogOr:
  7831. {
  7832. byteCodeGenerator->StartStatement(expr);
  7833. Js::ByteCodeLabel leftFalse = byteCodeGenerator->Writer()->DefineLabel();
  7834. EmitGeneratingBooleanExpression(expr->sxBin.pnode1, trueLabel, false, leftFalse, true, writeto, byteCodeGenerator, funcInfo);
  7835. funcInfo->ReleaseLoc(expr->sxBin.pnode1);
  7836. byteCodeGenerator->Writer()->MarkLabel(leftFalse);
  7837. EmitGeneratingBooleanExpression(expr->sxBin.pnode2, trueLabel, truefallthrough, falseLabel, falsefallthrough, writeto, byteCodeGenerator, funcInfo);
  7838. funcInfo->ReleaseLoc(expr->sxBin.pnode2);
  7839. byteCodeGenerator->EndStatement(expr);
  7840. break;
  7841. }
  7842. case knopLogAnd:
  7843. {
  7844. byteCodeGenerator->StartStatement(expr);
  7845. Js::ByteCodeLabel leftTrue = byteCodeGenerator->Writer()->DefineLabel();
  7846. EmitGeneratingBooleanExpression(expr->sxBin.pnode1, leftTrue, true, falseLabel, false, writeto, byteCodeGenerator, funcInfo);
  7847. funcInfo->ReleaseLoc(expr->sxBin.pnode1);
  7848. byteCodeGenerator->Writer()->MarkLabel(leftTrue);
  7849. EmitGeneratingBooleanExpression(expr->sxBin.pnode2, trueLabel, truefallthrough, falseLabel, falsefallthrough, writeto, byteCodeGenerator, funcInfo);
  7850. funcInfo->ReleaseLoc(expr->sxBin.pnode2);
  7851. byteCodeGenerator->EndStatement(expr);
  7852. break;
  7853. }
  7854. case knopLogNot:
  7855. {
  7856. byteCodeGenerator->StartStatement(expr);
  7857. // this time we want a boolean expression, since Logical Not is nice and only returns true or false
  7858. Js::ByteCodeLabel emitTrue = byteCodeGenerator->Writer()->DefineLabel();
  7859. Js::ByteCodeLabel emitFalse = byteCodeGenerator->Writer()->DefineLabel();
  7860. EmitBooleanExpression(expr->sxUni.pnode1, emitFalse, emitTrue, byteCodeGenerator, funcInfo);
  7861. byteCodeGenerator->Writer()->MarkLabel(emitTrue);
  7862. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, writeto);
  7863. byteCodeGenerator->Writer()->Br(trueLabel);
  7864. byteCodeGenerator->Writer()->MarkLabel(emitFalse);
  7865. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, writeto);
  7866. if (!falsefallthrough)
  7867. {
  7868. byteCodeGenerator->Writer()->Br(falseLabel);
  7869. }
  7870. funcInfo->ReleaseLoc(expr->sxUni.pnode1);
  7871. byteCodeGenerator->EndStatement(expr);
  7872. break;
  7873. }
  7874. case knopEq:
  7875. case knopEqv:
  7876. case knopNEqv:
  7877. case knopNe:
  7878. case knopLt:
  7879. case knopLe:
  7880. case knopGe:
  7881. case knopGt:
  7882. byteCodeGenerator->StartStatement(expr);
  7883. EmitBinaryOpnds(expr->sxBin.pnode1, expr->sxBin.pnode2, byteCodeGenerator, funcInfo);
  7884. funcInfo->ReleaseLoc(expr->sxBin.pnode2);
  7885. funcInfo->ReleaseLoc(expr->sxBin.pnode1);
  7886. funcInfo->AcquireLoc(expr);
  7887. byteCodeGenerator->Writer()->Reg3(nopToCMOp[expr->nop], expr->location, expr->sxBin.pnode1->location,
  7888. expr->sxBin.pnode2->location);
  7889. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, writeto, expr->location);
  7890. // The inliner likes small bytecode
  7891. if (!(truefallthrough || falsefallthrough))
  7892. {
  7893. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7894. byteCodeGenerator->Writer()->Br(falseLabel);
  7895. }
  7896. else if (truefallthrough && !falsefallthrough) {
  7897. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  7898. }
  7899. else if (falsefallthrough && !truefallthrough) {
  7900. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7901. }
  7902. byteCodeGenerator->EndStatement(expr);
  7903. break;
  7904. case knopTrue:
  7905. byteCodeGenerator->StartStatement(expr);
  7906. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, writeto);
  7907. if (!truefallthrough)
  7908. {
  7909. byteCodeGenerator->Writer()->Br(trueLabel);
  7910. }
  7911. byteCodeGenerator->EndStatement(expr);
  7912. break;
  7913. case knopFalse:
  7914. byteCodeGenerator->StartStatement(expr);
  7915. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, writeto);
  7916. if (!falsefallthrough)
  7917. {
  7918. byteCodeGenerator->Writer()->Br(falseLabel);
  7919. }
  7920. byteCodeGenerator->EndStatement(expr);
  7921. break;
  7922. default:
  7923. // Note: we usually release the temp assigned to a node after we Emit it.
  7924. // But in this case, EmitBooleanExpression is just a wrapper around a normal Emit call,
  7925. // and the caller of EmitBooleanExpression expects to be able to release this register.
  7926. // For diagnostics purposes, register the name and dot to the statement list.
  7927. if (expr->nop == knopName || expr->nop == knopDot)
  7928. {
  7929. byteCodeGenerator->StartStatement(expr);
  7930. Emit(expr, byteCodeGenerator, funcInfo, false);
  7931. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, writeto, expr->location);
  7932. // The inliner likes small bytecode
  7933. if (!(truefallthrough || falsefallthrough))
  7934. {
  7935. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7936. byteCodeGenerator->Writer()->Br(falseLabel);
  7937. }
  7938. else if (truefallthrough && !falsefallthrough) {
  7939. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  7940. }
  7941. else if (falsefallthrough && !truefallthrough) {
  7942. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7943. }
  7944. byteCodeGenerator->EndStatement(expr);
  7945. }
  7946. else
  7947. {
  7948. Emit(expr, byteCodeGenerator, funcInfo, false);
  7949. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, writeto, expr->location);
  7950. // The inliner likes small bytecode
  7951. if (!(truefallthrough || falsefallthrough))
  7952. {
  7953. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7954. byteCodeGenerator->Writer()->Br(falseLabel);
  7955. }
  7956. else if (truefallthrough && !falsefallthrough) {
  7957. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrFalse_A, falseLabel, expr->location);
  7958. }
  7959. else if (falsefallthrough && !truefallthrough) {
  7960. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, trueLabel, expr->location);
  7961. }
  7962. }
  7963. break;
  7964. }
  7965. }
  7966. // used by while and for loops
  7967. void EmitLoop(
  7968. ParseNode *loopNode,
  7969. ParseNode *cond,
  7970. ParseNode *body,
  7971. ParseNode *incr,
  7972. ByteCodeGenerator *byteCodeGenerator,
  7973. FuncInfo *funcInfo,
  7974. BOOL fReturnValue,
  7975. BOOL doWhile = FALSE,
  7976. ParseNode *forLoopBlock = nullptr)
  7977. {
  7978. // Need to increment loop count whether we are going to profile or not for HasLoop()
  7979. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  7980. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  7981. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  7982. loopNode->sxLoop.loopId = loopId;
  7983. if (doWhile)
  7984. {
  7985. Emit(body, byteCodeGenerator, funcInfo, fReturnValue);
  7986. funcInfo->ReleaseLoc(body);
  7987. if (loopNode->emitLabels)
  7988. {
  7989. byteCodeGenerator->Writer()->MarkLabel(loopNode->sxStmt.continueLabel);
  7990. }
  7991. if (!ByteCodeGenerator::IsFalse(cond) ||
  7992. byteCodeGenerator->IsInDebugMode())
  7993. {
  7994. EmitBooleanExpression(cond, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo);
  7995. }
  7996. funcInfo->ReleaseLoc(cond);
  7997. }
  7998. else
  7999. {
  8000. if (cond)
  8001. {
  8002. if (!(cond->nop == knopInt &&
  8003. cond->sxInt.lw != 0))
  8004. {
  8005. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  8006. EmitBooleanExpression(cond, trueLabel, continuePastLoop, byteCodeGenerator, funcInfo);
  8007. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  8008. }
  8009. funcInfo->ReleaseLoc(cond);
  8010. }
  8011. Emit(body, byteCodeGenerator, funcInfo, fReturnValue);
  8012. funcInfo->ReleaseLoc(body);
  8013. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled() &&
  8014. forLoopBlock != nullptr)
  8015. {
  8016. CloneEmitBlock(forLoopBlock, byteCodeGenerator, funcInfo);
  8017. }
  8018. if (loopNode->emitLabels)
  8019. {
  8020. byteCodeGenerator->Writer()->MarkLabel(loopNode->sxStmt.continueLabel);
  8021. }
  8022. if (incr != nullptr)
  8023. {
  8024. Emit(incr, byteCodeGenerator, funcInfo, false);
  8025. funcInfo->ReleaseLoc(incr);
  8026. }
  8027. byteCodeGenerator->Writer()->Br(loopEntrance);
  8028. }
  8029. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  8030. if (loopNode->emitLabels)
  8031. {
  8032. byteCodeGenerator->Writer()->MarkLabel(loopNode->sxStmt.breakLabel);
  8033. }
  8034. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8035. }
  8036. void ByteCodeGenerator::EmitInvertedLoop(ParseNode* outerLoop, ParseNode* invertedLoop, FuncInfo* funcInfo)
  8037. {
  8038. Js::ByteCodeLabel invertedLoopLabel = this->m_writer.DefineLabel();
  8039. Js::ByteCodeLabel afterInvertedLoop = this->m_writer.DefineLabel();
  8040. // emit branch around original
  8041. Emit(outerLoop->sxFor.pnodeInit, this, funcInfo, false);
  8042. funcInfo->ReleaseLoc(outerLoop->sxFor.pnodeInit);
  8043. this->m_writer.BrS(Js::OpCode::BrNotHasSideEffects, invertedLoopLabel, Js::SideEffects_Any);
  8044. // emit original
  8045. EmitLoop(outerLoop, outerLoop->sxFor.pnodeCond, outerLoop->sxFor.pnodeBody,
  8046. outerLoop->sxFor.pnodeIncr, this, funcInfo, false);
  8047. // clear temporary registers since inverted loop may share nodes with
  8048. // emitted original loop
  8049. VisitClearTmpRegs(outerLoop, this, funcInfo);
  8050. // emit branch around inverted
  8051. this->m_writer.Br(afterInvertedLoop);
  8052. this->m_writer.MarkLabel(invertedLoopLabel);
  8053. // Emit a zero trip test for the original outer-loop
  8054. Js::ByteCodeLabel zeroTrip = this->m_writer.DefineLabel();
  8055. ParseNode* testNode = this->GetParser()->CopyPnode(outerLoop->sxFor.pnodeCond);
  8056. EmitBooleanExpression(testNode, zeroTrip, afterInvertedLoop, this, funcInfo);
  8057. this->m_writer.MarkLabel(zeroTrip);
  8058. funcInfo->ReleaseLoc(testNode);
  8059. // emit inverted
  8060. Emit(invertedLoop->sxFor.pnodeInit, this, funcInfo, false);
  8061. funcInfo->ReleaseLoc(invertedLoop->sxFor.pnodeInit);
  8062. EmitLoop(invertedLoop, invertedLoop->sxFor.pnodeCond, invertedLoop->sxFor.pnodeBody,
  8063. invertedLoop->sxFor.pnodeIncr, this, funcInfo, false);
  8064. this->m_writer.MarkLabel(afterInvertedLoop);
  8065. }
  8066. void EmitGetIterator(Js::RegSlot iteratorLocation, Js::RegSlot iterableLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8067. {
  8068. // get iterator object from the iterable
  8069. EmitInvoke(iteratorLocation, iterableLocation, Js::PropertyIds::_symbolIterator, byteCodeGenerator, funcInfo);
  8070. // throw TypeError if the result is not an object
  8071. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  8072. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, skipThrow, iteratorLocation);
  8073. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_NeedObject));
  8074. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  8075. }
  8076. void EmitIteratorNext(Js::RegSlot itemLocation, Js::RegSlot iteratorLocation, Js::RegSlot nextInputLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8077. {
  8078. // invoke next() on the iterator
  8079. if (nextInputLocation == Js::Constants::NoRegister)
  8080. {
  8081. EmitInvoke(itemLocation, iteratorLocation, Js::PropertyIds::next, byteCodeGenerator, funcInfo);
  8082. }
  8083. else
  8084. {
  8085. EmitInvoke(itemLocation, iteratorLocation, Js::PropertyIds::next, byteCodeGenerator, funcInfo, nextInputLocation);
  8086. }
  8087. // throw TypeError if the result is not an object
  8088. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  8089. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, skipThrow, itemLocation);
  8090. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_NeedObject));
  8091. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  8092. }
  8093. // Generating
  8094. // if (hasReturnFunction) {
  8095. // value = Call Retrun;
  8096. // if (value != Object)
  8097. // throw TypeError;
  8098. // }
  8099. void EmitIteratorClose(Js::RegSlot iteratorLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8100. {
  8101. Js::RegSlot returnLocation = funcInfo->AcquireTmpRegister();
  8102. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  8103. Js::ByteCodeLabel noReturn = byteCodeGenerator->Writer()->DefineLabel();
  8104. uint cacheId = funcInfo->FindOrAddInlineCacheId(iteratorLocation, Js::PropertyIds::return_, false, false);
  8105. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, returnLocation, iteratorLocation, cacheId);
  8106. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrEq_A, noReturn, returnLocation, funcInfo->undefinedConstantRegister);
  8107. EmitInvoke(returnLocation, iteratorLocation, Js::PropertyIds::return_, byteCodeGenerator, funcInfo);
  8108. // throw TypeError if the result is not an Object
  8109. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, skipThrow, returnLocation);
  8110. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_NeedObject));
  8111. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  8112. byteCodeGenerator->Writer()->MarkLabel(noReturn);
  8113. funcInfo->ReleaseTmpRegister(returnLocation);
  8114. }
  8115. void EmitIteratorComplete(Js::RegSlot doneLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8116. {
  8117. // get the iterator result's "done" property
  8118. uint cacheId = funcInfo->FindOrAddInlineCacheId(iteratorResultLocation, Js::PropertyIds::done, false, false);
  8119. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, doneLocation, iteratorResultLocation, cacheId);
  8120. // Do not need to do ToBoolean explicitly with current uses of EmitIteratorComplete since BrTrue_A does this.
  8121. // Add a ToBoolean controlled by template flag if needed for new uses later on.
  8122. }
  8123. void EmitIteratorValue(Js::RegSlot valueLocation, Js::RegSlot iteratorResultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8124. {
  8125. // get the iterator result's "value" property
  8126. uint cacheId = funcInfo->FindOrAddInlineCacheId(iteratorResultLocation, Js::PropertyIds::value, false, false);
  8127. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, valueLocation, iteratorResultLocation, cacheId);
  8128. }
  8129. void EmitForInOfLoopBody(ParseNode *loopNode,
  8130. Js::ByteCodeLabel loopEntrance,
  8131. Js::ByteCodeLabel continuePastLoop,
  8132. ByteCodeGenerator *byteCodeGenerator,
  8133. FuncInfo *funcInfo,
  8134. BOOL fReturnValue)
  8135. {
  8136. if (loopNode->sxForInOrForOf.pnodeLval->nop != knopVarDecl &&
  8137. loopNode->sxForInOrForOf.pnodeLval->nop != knopLetDecl &&
  8138. loopNode->sxForInOrForOf.pnodeLval->nop != knopConstDecl)
  8139. {
  8140. EmitReference(loopNode->sxForInOrForOf.pnodeLval, byteCodeGenerator, funcInfo);
  8141. }
  8142. else
  8143. {
  8144. Symbol * sym = loopNode->sxForInOrForOf.pnodeLval->sxVar.sym;
  8145. sym->SetNeedDeclaration(false);
  8146. }
  8147. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8148. {
  8149. BeginEmitBlock(loopNode->sxForInOrForOf.pnodeBlock, byteCodeGenerator, funcInfo);
  8150. }
  8151. EmitAssignment(nullptr, loopNode->sxForInOrForOf.pnodeLval, loopNode->sxForInOrForOf.itemLocation, byteCodeGenerator, funcInfo);
  8152. // The StartStatement is already done in the caller of this function.
  8153. byteCodeGenerator->EndStatement(loopNode->sxForInOrForOf.pnodeLval);
  8154. funcInfo->ReleaseReference(loopNode->sxForInOrForOf.pnodeLval);
  8155. Emit(loopNode->sxForInOrForOf.pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  8156. funcInfo->ReleaseLoc(loopNode->sxForInOrForOf.pnodeBody);
  8157. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8158. {
  8159. EndEmitBlock(loopNode->sxForInOrForOf.pnodeBlock, byteCodeGenerator, funcInfo);
  8160. }
  8161. funcInfo->ReleaseTmpRegister(loopNode->sxForInOrForOf.itemLocation);
  8162. if (loopNode->emitLabels)
  8163. {
  8164. byteCodeGenerator->Writer()->MarkLabel(loopNode->sxForInOrForOf.continueLabel);
  8165. }
  8166. byteCodeGenerator->Writer()->Br(loopEntrance);
  8167. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  8168. if (loopNode->emitLabels)
  8169. {
  8170. byteCodeGenerator->Writer()->MarkLabel(loopNode->sxForInOrForOf.breakLabel);
  8171. }
  8172. }
  8173. void EmitForIn(ParseNode *loopNode,
  8174. Js::ByteCodeLabel loopEntrance,
  8175. Js::ByteCodeLabel continuePastLoop,
  8176. ByteCodeGenerator *byteCodeGenerator,
  8177. FuncInfo *funcInfo,
  8178. BOOL fReturnValue)
  8179. {
  8180. Assert(loopNode->nop == knopForIn);
  8181. Assert(loopNode->location == Js::Constants::NoRegister);
  8182. // Grab registers for the enumerator and for the current enumerated item.
  8183. // The enumerator register will be released after this call returns.
  8184. loopNode->sxForInOrForOf.itemLocation = funcInfo->AcquireTmpRegister();
  8185. uint forInLoopLevel = funcInfo->AcquireForInLoopLevel();
  8186. // get enumerator from the collection
  8187. byteCodeGenerator->Writer()->Reg1Unsigned1(Js::OpCode::InitForInEnumerator, loopNode->sxForInOrForOf.pnodeObj->location, forInLoopLevel);
  8188. // The StartStatement is already done in the caller of the current function, which is EmitForInOrForOf
  8189. byteCodeGenerator->EndStatement(loopNode);
  8190. // Need to increment loop count whether we are going into profile or not for HasLoop()
  8191. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8192. loopNode->sxForInOrForOf.loopId = loopId;
  8193. // The EndStatement will happen in the EmitForInOfLoopBody function
  8194. byteCodeGenerator->StartStatement(loopNode->sxForInOrForOf.pnodeLval);
  8195. // branch past loop when MoveAndGetNext returns nullptr
  8196. byteCodeGenerator->Writer()->BrReg1Unsigned1(Js::OpCode::BrOnEmpty, continuePastLoop, loopNode->sxForInOrForOf.itemLocation, forInLoopLevel);
  8197. EmitForInOfLoopBody(loopNode, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, fReturnValue);
  8198. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8199. funcInfo->ReleaseForInLoopLevel(forInLoopLevel);
  8200. if (!byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8201. {
  8202. EndEmitBlock(loopNode->sxForInOrForOf.pnodeBlock, byteCodeGenerator, funcInfo);
  8203. }
  8204. }
  8205. void EmitForInOrForOf(ParseNode *loopNode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue)
  8206. {
  8207. bool isForIn = (loopNode->nop == knopForIn);
  8208. Assert(isForIn || loopNode->nop == knopForOf);
  8209. BeginEmitBlock(loopNode->sxForInOrForOf.pnodeBlock, byteCodeGenerator, funcInfo);
  8210. byteCodeGenerator->StartStatement(loopNode);
  8211. if (!isForIn)
  8212. {
  8213. funcInfo->AcquireLoc(loopNode);
  8214. }
  8215. // Record the branch bytecode offset.
  8216. // This is used for "ignore exception" and "set next stmt" scenarios. See ProbeContainer::GetNextUserStatementOffsetForAdvance:
  8217. // If there is a branch recorded between current offset and next stmt offset, we'll use offset of the branch recorded,
  8218. // otherwise use offset of next stmt.
  8219. // The idea here is that when we bail out after ignore exception, we need to bail out to the beginning of the ForIn,
  8220. // but currently ForIn stmt starts at the condition part, which is needed for correct handling of break point on ForIn
  8221. // (break every time on the loop back edge) and correct display of current statement under debugger.
  8222. // See WinBlue 231880 for details.
  8223. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_All);
  8224. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled() &&
  8225. loopNode->sxForInOrForOf.pnodeBlock->sxBlock.HasBlockScopedContent())
  8226. {
  8227. byteCodeGenerator->Writer()->RecordForInOrOfCollectionScope();
  8228. }
  8229. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  8230. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  8231. if (loopNode->sxForInOrForOf.pnodeLval->nop == knopVarDecl)
  8232. {
  8233. EmitReference(loopNode->sxForInOrForOf.pnodeLval, byteCodeGenerator, funcInfo);
  8234. }
  8235. Emit(loopNode->sxForInOrForOf.pnodeObj, byteCodeGenerator, funcInfo, false); // evaluate collection expression
  8236. funcInfo->ReleaseLoc(loopNode->sxForInOrForOf.pnodeObj);
  8237. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8238. {
  8239. EndEmitBlock(loopNode->sxForInOrForOf.pnodeBlock, byteCodeGenerator, funcInfo);
  8240. if (loopNode->sxForInOrForOf.pnodeBlock->sxBlock.scope != nullptr)
  8241. {
  8242. loopNode->sxForInOrForOf.pnodeBlock->sxBlock.scope->ForEachSymbol([](Symbol *sym) {
  8243. sym->SetIsTrackedForDebugger(false);
  8244. });
  8245. }
  8246. }
  8247. if (isForIn)
  8248. {
  8249. EmitForIn(loopNode, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, fReturnValue);
  8250. if (!byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8251. {
  8252. EndEmitBlock(loopNode->sxForInOrForOf.pnodeBlock, byteCodeGenerator, funcInfo);
  8253. }
  8254. return;
  8255. }
  8256. Js::ByteCodeLabel skipThrow = byteCodeGenerator->Writer()->DefineLabel();
  8257. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrNeq_A, skipThrow, loopNode->sxForInOrForOf.pnodeObj->location, funcInfo->undefinedConstantRegister);
  8258. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ObjectCoercible));
  8259. byteCodeGenerator->Writer()->MarkLabel(skipThrow);
  8260. Js::RegSlot regException = Js::Constants::NoRegister;
  8261. Js::RegSlot regOffset = Js::Constants::NoRegister;
  8262. // These two temp variables store the information of return function to be called or not.
  8263. // 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
  8264. // to be called on abrupt loop break.
  8265. // Why two variables? since these are temps and JIT does like not flow if single variable is used in multiple blocks.
  8266. Js::RegSlot shouldCallReturnFunctionLocation = funcInfo->AcquireTmpRegister();
  8267. Js::RegSlot shouldCallReturnFunctionLocationFinally = funcInfo->AcquireTmpRegister();
  8268. bool isCoroutine = funcInfo->byteCodeFunction->IsCoroutine();
  8269. if (isCoroutine)
  8270. {
  8271. regException = funcInfo->AcquireTmpRegister();
  8272. regOffset = funcInfo->AcquireTmpRegister();
  8273. }
  8274. // Grab registers for the enumerator and for the current enumerated item.
  8275. // The enumerator register will be released after this call returns.
  8276. loopNode->sxForInOrForOf.itemLocation = funcInfo->AcquireTmpRegister();
  8277. // We want call profile information on the @@iterator call, so instead of adding a GetForOfIterator bytecode op
  8278. // to do all the following work in a helper do it explicitly in bytecode so that the @@iterator call is exposed
  8279. // to the profiler and JIT.
  8280. byteCodeGenerator->SetHasFinally(true);
  8281. byteCodeGenerator->SetHasTry(true);
  8282. byteCodeGenerator->TopFuncInfo()->byteCodeFunction->SetDontInline(true);
  8283. // do a ToObject on the collection
  8284. Js::RegSlot tmpObj = funcInfo->AcquireTmpRegister();
  8285. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Obj, tmpObj, loopNode->sxForInOrForOf.pnodeObj->location);
  8286. EmitGetIterator(loopNode->location, tmpObj, byteCodeGenerator, funcInfo);
  8287. funcInfo->ReleaseTmpRegister(tmpObj);
  8288. // The whole loop is surrounded with try..catch..finally - in order to capture the abrupt completion.
  8289. Js::ByteCodeLabel finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  8290. Js::ByteCodeLabel catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  8291. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  8292. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  8293. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  8294. ByteCodeGenerator::TryScopeRecord tryRecForTryFinally(Js::OpCode::TryFinallyWithYield, finallyLabel);
  8295. if (isCoroutine)
  8296. {
  8297. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  8298. tryRecForTryFinally.reg1 = regException;
  8299. tryRecForTryFinally.reg2 = regOffset;
  8300. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTryFinally);
  8301. }
  8302. else
  8303. {
  8304. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  8305. }
  8306. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  8307. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryCatch, catchLabel);
  8308. if (isCoroutine)
  8309. {
  8310. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  8311. }
  8312. byteCodeGenerator->EndStatement(loopNode);
  8313. // Need to increment loop count whether we are going into profile or not for HasLoop()
  8314. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8315. loopNode->sxForInOrForOf.loopId = loopId;
  8316. byteCodeGenerator->StartStatement(loopNode->sxForInOrForOf.pnodeLval);
  8317. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocation);
  8318. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, shouldCallReturnFunctionLocationFinally);
  8319. EmitIteratorNext(loopNode->sxForInOrForOf.itemLocation, loopNode->location, Js::Constants::NoRegister, byteCodeGenerator, funcInfo);
  8320. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  8321. EmitIteratorComplete(doneLocation, loopNode->sxForInOrForOf.itemLocation, byteCodeGenerator, funcInfo);
  8322. // branch past loop if the result's done property is truthy
  8323. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, continuePastLoop, doneLocation);
  8324. funcInfo->ReleaseTmpRegister(doneLocation);
  8325. // otherwise put result's value property in itemLocation
  8326. EmitIteratorValue(loopNode->sxForInOrForOf.itemLocation, loopNode->sxForInOrForOf.itemLocation, byteCodeGenerator, funcInfo);
  8327. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocation);
  8328. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, shouldCallReturnFunctionLocationFinally);
  8329. EmitForInOfLoopBody(loopNode, loopEntrance, continuePastLoop, byteCodeGenerator, funcInfo, fReturnValue);
  8330. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8331. EmitCatchAndFinallyBlocks(catchLabel,
  8332. finallyLabel,
  8333. loopNode->location,
  8334. shouldCallReturnFunctionLocation,
  8335. shouldCallReturnFunctionLocationFinally,
  8336. regException,
  8337. regOffset,
  8338. byteCodeGenerator,
  8339. funcInfo);
  8340. if (!byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  8341. {
  8342. EndEmitBlock(loopNode->sxForInOrForOf.pnodeBlock, byteCodeGenerator, funcInfo);
  8343. }
  8344. }
  8345. void EmitArrayLiteral(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8346. {
  8347. funcInfo->AcquireLoc(pnode);
  8348. ParseNode *args = pnode->sxUni.pnode1;
  8349. if (args == nullptr)
  8350. {
  8351. byteCodeGenerator->Writer()->Reg1Unsigned1(
  8352. pnode->sxArrLit.hasMissingValues ? Js::OpCode::NewScArrayWithMissingValues : Js::OpCode::NewScArray,
  8353. pnode->location,
  8354. ByteCodeGenerator::DefaultArraySize);
  8355. }
  8356. else
  8357. {
  8358. SetNewArrayElements(pnode, pnode->location, byteCodeGenerator, funcInfo);
  8359. }
  8360. }
  8361. void EmitJumpCleanup(ParseNode *pnode, ParseNode *pnodeTarget, ByteCodeGenerator *byteCodeGenerator, FuncInfo * funcInfo)
  8362. {
  8363. for (; pnode != pnodeTarget; pnode = pnode->sxStmt.pnodeOuter)
  8364. {
  8365. switch (pnode->nop)
  8366. {
  8367. case knopTry:
  8368. case knopCatch:
  8369. case knopFinally:
  8370. // We insert OpCode::Leave when there is a 'return' inside try/catch/finally.
  8371. // This is for flow control and does not participate in identifying boundaries of try/catch blocks,
  8372. // thus we shouldn't call RecordCrossFrameEntryExitRecord() here.
  8373. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  8374. break;
  8375. case knopForOf:
  8376. #if ENABLE_PROFILE_INFO
  8377. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(funcInfo->GetParsedFunctionBody()))
  8378. {
  8379. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::ProfiledLoopEnd, pnode->sxLoop.loopId);
  8380. }
  8381. #endif
  8382. // The ForOf loop code is wrapped around try..catch..finally - Forcing couple Leave bytecode over here
  8383. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  8384. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  8385. break;
  8386. #if ENABLE_PROFILE_INFO
  8387. case knopWhile:
  8388. case knopDoWhile:
  8389. case knopFor:
  8390. case knopForIn:
  8391. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(funcInfo->GetParsedFunctionBody()))
  8392. {
  8393. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::ProfiledLoopEnd, pnode->sxLoop.loopId);
  8394. }
  8395. break;
  8396. #endif
  8397. }
  8398. }
  8399. }
  8400. void EmitBinaryOpnds(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8401. {
  8402. // If opnd2 can overwrite opnd1, make sure the value of opnd1 is stashed away.
  8403. if (MayHaveSideEffectOnNode(pnode1, pnode2))
  8404. {
  8405. SaveOpndValue(pnode1, funcInfo);
  8406. }
  8407. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  8408. if (pnode1->nop == knopComputedName && pnode2->nop == knopClassDecl &&
  8409. (pnode2->sxClass.pnodeConstructor == nullptr || pnode2->sxClass.pnodeConstructor->nop != knopVarDecl))
  8410. {
  8411. Emit(pnode2, byteCodeGenerator, funcInfo, false, false, pnode1);
  8412. }
  8413. else
  8414. {
  8415. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  8416. }
  8417. }
  8418. void EmitBinaryReference(ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fLoadLhs)
  8419. {
  8420. // Make sure that the RHS of an assignment doesn't kill the opnd's of the expression on the LHS.
  8421. switch (pnode1->nop)
  8422. {
  8423. case knopName:
  8424. if (fLoadLhs && MayHaveSideEffectOnNode(pnode1, pnode2))
  8425. {
  8426. // Given x op y, y may kill x, so stash x.
  8427. // Note that this only matters if we're loading x prior to the op.
  8428. SaveOpndValue(pnode1, funcInfo);
  8429. }
  8430. break;
  8431. case knopDot:
  8432. if (fLoadLhs)
  8433. {
  8434. // We're loading the value of the LHS before the RHS, so make sure the LHS gets a register first.
  8435. funcInfo->AcquireLoc(pnode1);
  8436. }
  8437. if (MayHaveSideEffectOnNode(pnode1->sxBin.pnode1, pnode2))
  8438. {
  8439. // Given x.y op z, z may kill x, so stash x away.
  8440. SaveOpndValue(pnode1->sxBin.pnode1, funcInfo);
  8441. }
  8442. break;
  8443. case knopIndex:
  8444. if (fLoadLhs)
  8445. {
  8446. // We're loading the value of the LHS before the RHS, so make sure the LHS gets a register first.
  8447. funcInfo->AcquireLoc(pnode1);
  8448. }
  8449. if (MayHaveSideEffectOnNode(pnode1->sxBin.pnode1, pnode2) ||
  8450. MayHaveSideEffectOnNode(pnode1->sxBin.pnode1, pnode1->sxBin.pnode2))
  8451. {
  8452. // Given x[y] op z, y or z may kill x, so stash x away.
  8453. SaveOpndValue(pnode1->sxBin.pnode1, funcInfo);
  8454. }
  8455. if (MayHaveSideEffectOnNode(pnode1->sxBin.pnode2, pnode2))
  8456. {
  8457. // Given x[y] op z, z may kill y, so stash y away.
  8458. // But make sure that x gets a register before y.
  8459. funcInfo->AcquireLoc(pnode1->sxBin.pnode1);
  8460. SaveOpndValue(pnode1->sxBin.pnode2, funcInfo);
  8461. }
  8462. break;
  8463. }
  8464. if (fLoadLhs)
  8465. {
  8466. // Emit code to load the value of the LHS.
  8467. EmitLoad(pnode1, byteCodeGenerator, funcInfo);
  8468. }
  8469. else
  8470. {
  8471. // Emit code to evaluate the LHS opnds, but don't load the LHS's value.
  8472. EmitReference(pnode1, byteCodeGenerator, funcInfo);
  8473. }
  8474. // Evaluate the RHS.
  8475. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  8476. }
  8477. void EmitUseBeforeDeclarationRuntimeError(ByteCodeGenerator * byteCodeGenerator, Js::RegSlot location)
  8478. {
  8479. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_UseBeforeDeclaration));
  8480. if (location != Js::Constants::NoRegister)
  8481. {
  8482. // Optionally load something into register in order to do not confuse IRBuilder. This value will never be used.
  8483. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, location);
  8484. }
  8485. }
  8486. void EmitUseBeforeDeclaration(Symbol *sym, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8487. {
  8488. // Don't emit static use-before-declaration error in a closure or dynamic scope case. We detect such cases with dynamic checks,
  8489. // if necessary.
  8490. if (sym != nullptr &&
  8491. !sym->GetIsModuleExportStorage() &&
  8492. sym->GetNeedDeclaration() &&
  8493. byteCodeGenerator->GetCurrentScope()->HasStaticPathToAncestor(sym->GetScope()) &&
  8494. sym->GetScope()->GetFunc() == funcInfo)
  8495. {
  8496. EmitUseBeforeDeclarationRuntimeError(byteCodeGenerator, Js::Constants::NoRegister);
  8497. }
  8498. }
  8499. void EmitBinary(Js::OpCode opcode, ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8500. {
  8501. byteCodeGenerator->StartStatement(pnode);
  8502. EmitBinaryOpnds(pnode->sxBin.pnode1, pnode->sxBin.pnode2, byteCodeGenerator, funcInfo);
  8503. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  8504. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  8505. funcInfo->AcquireLoc(pnode);
  8506. byteCodeGenerator->Writer()->Reg3(opcode,
  8507. pnode->location,
  8508. pnode->sxBin.pnode1->location,
  8509. pnode->sxBin.pnode2->location);
  8510. byteCodeGenerator->EndStatement(pnode);
  8511. }
  8512. bool CollectConcat(ParseNode *pnodeAdd, DListCounted<ParseNode *, ArenaAllocator>& concatOpnds, ArenaAllocator *arenaAllocator)
  8513. {
  8514. Assert(pnodeAdd->nop == knopAdd);
  8515. Assert(pnodeAdd->CanFlattenConcatExpr());
  8516. bool doConcatString = false;
  8517. DList<ParseNode*, ArenaAllocator> pnodeStack(arenaAllocator);
  8518. pnodeStack.Prepend(pnodeAdd->sxBin.pnode2);
  8519. ParseNode * pnode = pnodeAdd->sxBin.pnode1;
  8520. while (true)
  8521. {
  8522. if (!pnode->CanFlattenConcatExpr())
  8523. {
  8524. concatOpnds.Append(pnode);
  8525. }
  8526. else if (pnode->nop == knopStr)
  8527. {
  8528. concatOpnds.Append(pnode);
  8529. // Detect if there are any string larger then the append size limit.
  8530. // If there are, we can do concat; otherwise, still use add so we will not lose the AddLeftDead opportunities.
  8531. doConcatString = doConcatString || !Js::CompoundString::ShouldAppendChars(pnode->sxPid.pid->Cch());
  8532. }
  8533. else
  8534. {
  8535. Assert(pnode->nop == knopAdd);
  8536. pnodeStack.Prepend(pnode->sxBin.pnode2);
  8537. pnode = pnode->sxBin.pnode1;
  8538. continue;
  8539. }
  8540. if (pnodeStack.Empty())
  8541. {
  8542. break;
  8543. }
  8544. pnode = pnodeStack.Head();
  8545. pnodeStack.RemoveHead();
  8546. }
  8547. return doConcatString;
  8548. }
  8549. void EmitConcat3(ParseNode *pnode, ParseNode *pnode1, ParseNode *pnode2, ParseNode *pnode3, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8550. {
  8551. byteCodeGenerator->StartStatement(pnode);
  8552. if (MayHaveSideEffectOnNode(pnode1, pnode2) || MayHaveSideEffectOnNode(pnode1, pnode3))
  8553. {
  8554. SaveOpndValue(pnode1, funcInfo);
  8555. }
  8556. if (MayHaveSideEffectOnNode(pnode2, pnode3))
  8557. {
  8558. SaveOpndValue(pnode2, funcInfo);
  8559. }
  8560. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  8561. Emit(pnode2, byteCodeGenerator, funcInfo, false);
  8562. Emit(pnode3, byteCodeGenerator, funcInfo, false);
  8563. funcInfo->ReleaseLoc(pnode3);
  8564. funcInfo->ReleaseLoc(pnode2);
  8565. funcInfo->ReleaseLoc(pnode1);
  8566. funcInfo->AcquireLoc(pnode);
  8567. byteCodeGenerator->Writer()->Reg4(Js::OpCode::Concat3,
  8568. pnode->location,
  8569. pnode1->location,
  8570. pnode2->location,
  8571. pnode3->location);
  8572. byteCodeGenerator->EndStatement(pnode);
  8573. }
  8574. void EmitNewConcatStrMulti(ParseNode *pnode, uint8 count, ParseNode *pnode1, ParseNode *pnode2, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8575. {
  8576. EmitBinaryOpnds(pnode1, pnode2, byteCodeGenerator, funcInfo);
  8577. funcInfo->ReleaseLoc(pnode2);
  8578. funcInfo->ReleaseLoc(pnode1);
  8579. funcInfo->AcquireLoc(pnode);
  8580. byteCodeGenerator->Writer()->Reg3B1(Js::OpCode::NewConcatStrMulti,
  8581. pnode->location,
  8582. pnode1->location,
  8583. pnode2->location,
  8584. count);
  8585. }
  8586. void EmitAdd(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo)
  8587. {
  8588. Assert(pnode->nop == knopAdd);
  8589. if (pnode->CanFlattenConcatExpr())
  8590. {
  8591. // We should only have a string concat if the feature is on.
  8592. Assert(!PHASE_OFF1(Js::ByteCodeConcatExprOptPhase));
  8593. DListCounted<ParseNode*, ArenaAllocator> concatOpnds(byteCodeGenerator->GetAllocator());
  8594. bool doConcatString = CollectConcat(pnode, concatOpnds, byteCodeGenerator->GetAllocator());
  8595. if (doConcatString)
  8596. {
  8597. uint concatCount = concatOpnds.Count();
  8598. Assert(concatCount >= 2);
  8599. // Don't do concatN if the number is too high
  8600. // CONSIDER: although we could have done multiple ConcatNs
  8601. if (concatCount > 2 && concatCount <= UINT8_MAX)
  8602. {
  8603. #if DBG
  8604. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  8605. #endif
  8606. ParseNode * pnode1 = concatOpnds.Head();
  8607. concatOpnds.RemoveHead();
  8608. ParseNode * pnode2 = concatOpnds.Head();
  8609. concatOpnds.RemoveHead();
  8610. if (concatCount == 3)
  8611. {
  8612. OUTPUT_TRACE_DEBUGONLY(Js::ByteCodeConcatExprOptPhase, _u("%s(%s) offset:#%d : Concat3\n"),
  8613. funcInfo->GetParsedFunctionBody()->GetDisplayName(),
  8614. funcInfo->GetParsedFunctionBody()->GetDebugNumberSet(debugStringBuffer),
  8615. byteCodeGenerator->Writer()->ByteCodeDataSize());
  8616. EmitConcat3(pnode, pnode1, pnode2, concatOpnds.Head(), byteCodeGenerator, funcInfo);
  8617. return;
  8618. }
  8619. OUTPUT_TRACE_DEBUGONLY(Js::ByteCodeConcatExprOptPhase, _u("%s(%s) offset:#%d: ConcatMulti %d\n"),
  8620. funcInfo->GetParsedFunctionBody()->GetDisplayName(),
  8621. funcInfo->GetParsedFunctionBody()->GetDebugNumberSet(debugStringBuffer),
  8622. byteCodeGenerator->Writer()->ByteCodeDataSize(), concatCount);
  8623. byteCodeGenerator->StartStatement(pnode);
  8624. funcInfo->AcquireLoc(pnode);
  8625. // CONSIDER: this may cause the backend not able CSE repeating pattern within the concat.
  8626. EmitNewConcatStrMulti(pnode, (uint8)concatCount, pnode1, pnode2, byteCodeGenerator, funcInfo);
  8627. uint i = 2;
  8628. do
  8629. {
  8630. ParseNode * currNode = concatOpnds.Head();
  8631. concatOpnds.RemoveHead();
  8632. ParseNode * currNode2 = concatOpnds.Head();
  8633. concatOpnds.RemoveHead();
  8634. EmitBinaryOpnds(currNode, currNode2, byteCodeGenerator, funcInfo);
  8635. funcInfo->ReleaseLoc(currNode2);
  8636. funcInfo->ReleaseLoc(currNode);
  8637. byteCodeGenerator->Writer()->Reg3B1(
  8638. Js::OpCode::SetConcatStrMultiItem2, pnode->location, currNode->location, currNode2->location, (uint8)i);
  8639. i += 2;
  8640. } while (concatOpnds.Count() > 1);
  8641. if (!concatOpnds.Empty())
  8642. {
  8643. ParseNode * currNode = concatOpnds.Head();
  8644. Emit(currNode, byteCodeGenerator, funcInfo, false);
  8645. funcInfo->ReleaseLoc(currNode);
  8646. byteCodeGenerator->Writer()->Reg2B1(
  8647. Js::OpCode::SetConcatStrMultiItem, pnode->location, currNode->location, (uint8)i);
  8648. i++;
  8649. }
  8650. Assert(concatCount == i);
  8651. byteCodeGenerator->EndStatement(pnode);
  8652. return;
  8653. }
  8654. }
  8655. // Since we collected all the node already, let's just emit them instead of doing it recursively.
  8656. byteCodeGenerator->StartStatement(pnode);
  8657. ParseNode * currNode = concatOpnds.Head();
  8658. concatOpnds.RemoveHead();
  8659. ParseNode * currNode2 = concatOpnds.Head();
  8660. concatOpnds.RemoveHead();
  8661. EmitBinaryOpnds(currNode, currNode2, byteCodeGenerator, funcInfo);
  8662. funcInfo->ReleaseLoc(currNode2);
  8663. funcInfo->ReleaseLoc(currNode);
  8664. Js::RegSlot dstReg = funcInfo->AcquireLoc(pnode);
  8665. byteCodeGenerator->Writer()->Reg3(
  8666. Js::OpCode::Add_A, dstReg, currNode->location, currNode2->location);
  8667. while (!concatOpnds.Empty())
  8668. {
  8669. currNode = concatOpnds.Head();
  8670. concatOpnds.RemoveHead();
  8671. Emit(currNode, byteCodeGenerator, funcInfo, false);
  8672. funcInfo->ReleaseLoc(currNode);
  8673. byteCodeGenerator->Writer()->Reg3(
  8674. Js::OpCode::Add_A, dstReg, dstReg, currNode->location);
  8675. }
  8676. byteCodeGenerator->EndStatement(pnode);
  8677. }
  8678. else
  8679. {
  8680. EmitBinary(Js::OpCode::Add_A, pnode, byteCodeGenerator, funcInfo);
  8681. }
  8682. }
  8683. void EmitSuperFieldPatch(FuncInfo* funcInfo, ParseNode* pnode, ByteCodeGenerator* byteCodeGenerator)
  8684. {
  8685. ParseNodePtr propFuncNode = funcInfo->root;
  8686. if (byteCodeGenerator->GetFlags() & fscrEval)
  8687. {
  8688. // If we are inside an eval, ScopedLdHomeObj will take care of the patch.
  8689. return;
  8690. }
  8691. if (funcInfo->IsLambda())
  8692. {
  8693. FuncInfo *parent = byteCodeGenerator->FindEnclosingNonLambda();
  8694. propFuncNode = parent->root;
  8695. }
  8696. // No need to emit a LdFld for the constructor.
  8697. if (propFuncNode->sxFnc.IsClassConstructor())
  8698. {
  8699. return;
  8700. }
  8701. if (!propFuncNode->sxFnc.IsClassMember() || propFuncNode->sxFnc.pid == nullptr)
  8702. {
  8703. // Non-methods will fail lookup.
  8704. return;
  8705. }
  8706. if (propFuncNode->sxFnc.pid->GetPropertyId() == Js::Constants::NoProperty)
  8707. {
  8708. byteCodeGenerator->AssignPropertyId(propFuncNode->sxFnc.pid);
  8709. }
  8710. // Load the current method's property ID from super instead of using super directly.
  8711. Js::RegSlot superLoc = funcInfo->superRegister;
  8712. pnode->sxCall.pnodeTarget->location = Js::Constants::NoRegister;
  8713. Js::RegSlot superPropLoc = funcInfo->AcquireLoc(pnode->sxCall.pnodeTarget);
  8714. Js::PropertyId propertyId = propFuncNode->sxFnc.pid->GetPropertyId();
  8715. uint cacheId = funcInfo->FindOrAddInlineCacheId(superLoc, propertyId, true, false);
  8716. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdMethodFld, superPropLoc, superLoc, cacheId);
  8717. propFuncNode->sxFnc.pnodeName = nullptr;
  8718. }
  8719. void ByteCodeGenerator::EmitLeaveOpCodesBeforeYield()
  8720. {
  8721. for (TryScopeRecord* node = this->tryScopeRecordsList.Tail(); node != nullptr; node = node->Previous())
  8722. {
  8723. switch (node->op)
  8724. {
  8725. case Js::OpCode::TryFinallyWithYield:
  8726. this->Writer()->Empty(Js::OpCode::LeaveNull);
  8727. break;
  8728. case Js::OpCode::TryCatch:
  8729. case Js::OpCode::ResumeFinally:
  8730. case Js::OpCode::ResumeCatch:
  8731. this->Writer()->Empty(Js::OpCode::Leave);
  8732. break;
  8733. default:
  8734. AssertMsg(false, "Unexpected OpCode before Yield in the Try-Catch-Finally cache for generator!");
  8735. break;
  8736. }
  8737. }
  8738. }
  8739. void ByteCodeGenerator::EmitTryBlockHeadersAfterYield()
  8740. {
  8741. for (TryScopeRecord* node = this->tryScopeRecordsList.Head(); node != nullptr; node = node->Next())
  8742. {
  8743. switch (node->op)
  8744. {
  8745. case Js::OpCode::TryCatch:
  8746. this->Writer()->Br(node->op, node->label);
  8747. break;
  8748. case Js::OpCode::TryFinallyWithYield:
  8749. case Js::OpCode::ResumeFinally:
  8750. this->Writer()->BrReg2(node->op, node->label, node->reg1, node->reg2);
  8751. break;
  8752. case Js::OpCode::ResumeCatch:
  8753. this->Writer()->Empty(node->op);
  8754. break;
  8755. default:
  8756. AssertMsg(false, "Unexpected OpCode after yield in the Try-Catch-Finally cache for generator!");
  8757. break;
  8758. }
  8759. }
  8760. }
  8761. void EmitYield(Js::RegSlot inputLocation, Js::RegSlot resultLocation, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo,
  8762. Js::RegSlot yieldStarIterator = Js::Constants::NoRegister)
  8763. {
  8764. // If the bytecode emitted by this function is part of 'yield*', inputLocation is the object
  8765. // returned by the iterable's next/return/throw method. Otherwise, it is the yielded value.
  8766. if (yieldStarIterator == Js::Constants::NoRegister)
  8767. {
  8768. byteCodeGenerator->Writer()->Reg1(Js::OpCode::NewScObjectSimple, funcInfo->yieldRegister);
  8769. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->yieldRegister, Js::PropertyIds::value, false, true);
  8770. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::StFld, inputLocation, funcInfo->yieldRegister, cacheId);
  8771. cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->yieldRegister, Js::PropertyIds::done, false, true);
  8772. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::StFld, funcInfo->falseConstantRegister, funcInfo->yieldRegister, cacheId);
  8773. }
  8774. else
  8775. {
  8776. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, funcInfo->yieldRegister, inputLocation);
  8777. }
  8778. byteCodeGenerator->EmitLeaveOpCodesBeforeYield();
  8779. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Yield, funcInfo->yieldRegister, funcInfo->yieldRegister);
  8780. byteCodeGenerator->EmitTryBlockHeadersAfterYield();
  8781. if (yieldStarIterator == Js::Constants::NoRegister)
  8782. {
  8783. byteCodeGenerator->Writer()->Reg2(Js::OpCode::ResumeYield, resultLocation, funcInfo->yieldRegister);
  8784. }
  8785. else
  8786. {
  8787. byteCodeGenerator->Writer()->Reg3(Js::OpCode::ResumeYieldStar, resultLocation, funcInfo->yieldRegister, yieldStarIterator);
  8788. }
  8789. }
  8790. void EmitYieldStar(ParseNode* yieldStarNode, ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo)
  8791. {
  8792. funcInfo->AcquireLoc(yieldStarNode);
  8793. Js::ByteCodeLabel loopEntrance = byteCodeGenerator->Writer()->DefineLabel();
  8794. Js::ByteCodeLabel continuePastLoop = byteCodeGenerator->Writer()->DefineLabel();
  8795. Js::RegSlot iteratorLocation = funcInfo->AcquireTmpRegister();
  8796. // Evaluate operand
  8797. Emit(yieldStarNode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  8798. funcInfo->ReleaseLoc(yieldStarNode->sxUni.pnode1);
  8799. EmitGetIterator(iteratorLocation, yieldStarNode->sxUni.pnode1->location, byteCodeGenerator, funcInfo);
  8800. // Call the iterator's next()
  8801. EmitIteratorNext(yieldStarNode->location, iteratorLocation, funcInfo->undefinedConstantRegister, byteCodeGenerator, funcInfo);
  8802. uint loopId = byteCodeGenerator->Writer()->EnterLoop(loopEntrance);
  8803. // since a yield* doesn't have a user defined body, we cannot return from this loop
  8804. // which means we don't need to support EmitJumpCleanup() and there do not need to
  8805. // remember the loopId like the loop statements do.
  8806. Js::RegSlot doneLocation = funcInfo->AcquireTmpRegister();
  8807. EmitIteratorComplete(doneLocation, yieldStarNode->location, byteCodeGenerator, funcInfo);
  8808. // branch past the loop if the done property is truthy
  8809. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, continuePastLoop, doneLocation);
  8810. funcInfo->ReleaseTmpRegister(doneLocation);
  8811. EmitYield(yieldStarNode->location, yieldStarNode->location, byteCodeGenerator, funcInfo, iteratorLocation);
  8812. funcInfo->ReleaseTmpRegister(iteratorLocation);
  8813. byteCodeGenerator->Writer()->Br(loopEntrance);
  8814. byteCodeGenerator->Writer()->MarkLabel(continuePastLoop);
  8815. byteCodeGenerator->Writer()->ExitLoop(loopId);
  8816. // Put the iterator result's value in yieldStarNode->location.
  8817. // It will be used as the result value of the yield* operator expression.
  8818. EmitIteratorValue(yieldStarNode->location, yieldStarNode->location, byteCodeGenerator, funcInfo);
  8819. }
  8820. void TrackIntConstantsOnGlobalUserObject(ByteCodeGenerator *byteCodeGenerator, bool isSymGlobalAndSingleAssignment, Js::PropertyId propertyId)
  8821. {
  8822. if (isSymGlobalAndSingleAssignment)
  8823. {
  8824. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalUserObject(propertyId);
  8825. }
  8826. }
  8827. void TrackIntConstantsOnGlobalObject(ByteCodeGenerator *byteCodeGenerator, bool isSymGlobalAndSingleAssignment, Js::PropertyId propertyId)
  8828. {
  8829. if (isSymGlobalAndSingleAssignment)
  8830. {
  8831. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalObject(propertyId);
  8832. }
  8833. }
  8834. void TrackIntConstantsOnGlobalObject(ByteCodeGenerator *byteCodeGenerator, Symbol *sym)
  8835. {
  8836. if (sym && sym->GetIsGlobal() && sym->IsAssignedOnce())
  8837. {
  8838. Js::PropertyId propertyId = sym->EnsurePosition(byteCodeGenerator);
  8839. byteCodeGenerator->GetScriptContext()->TrackIntConstPropertyOnGlobalObject(propertyId);
  8840. }
  8841. }
  8842. void TrackMemberNodesInObjectForIntConstants(ByteCodeGenerator *byteCodeGenerator, ParseNodePtr objNode)
  8843. {
  8844. Assert(objNode->nop == knopObject);
  8845. Assert(ParseNode::Grfnop(objNode->nop) & fnopUni);
  8846. ParseNodePtr memberList = objNode->sxUni.pnode1;
  8847. while (memberList != nullptr)
  8848. {
  8849. ParseNodePtr memberNode = memberList->nop == knopList ? memberList->sxBin.pnode1 : memberList;
  8850. ParseNodePtr memberNameNode = memberNode->sxBin.pnode1;
  8851. ParseNodePtr memberValNode = memberNode->sxBin.pnode2;
  8852. if (memberNameNode->nop != knopComputedName && memberValNode->nop == knopInt)
  8853. {
  8854. Js::PropertyId propertyId = memberNameNode->sxPid.PropertyIdFromNameNode();
  8855. TrackIntConstantsOnGlobalUserObject(byteCodeGenerator, true, propertyId);
  8856. }
  8857. memberList = memberList->nop == knopList ? memberList->sxBin.pnode2 : nullptr;
  8858. }
  8859. }
  8860. void TrackGlobalIntAssignmentsForknopDotProps(ParseNodePtr knopDotNode, ByteCodeGenerator * byteCodeGenerator)
  8861. {
  8862. Assert(knopDotNode->nop == knopDot);
  8863. ParseNodePtr objectNode = knopDotNode->sxBin.pnode1;
  8864. ParseNodePtr propertyNode = knopDotNode->sxBin.pnode2;
  8865. bool isSymGlobalAndSingleAssignment = false;
  8866. if (objectNode->nop == knopName)
  8867. {
  8868. Symbol * sym = objectNode->sxVar.sym;
  8869. isSymGlobalAndSingleAssignment = sym && sym->GetIsGlobal() && sym->IsAssignedOnce() && propertyNode->sxPid.pid->IsSingleAssignment();
  8870. Js::PropertyId propertyId = propertyNode->sxPid.PropertyIdFromNameNode();
  8871. TrackIntConstantsOnGlobalUserObject(byteCodeGenerator, isSymGlobalAndSingleAssignment, propertyId);
  8872. }
  8873. else if (objectNode->nop == knopThis)
  8874. {
  8875. // Assume knopThis always refer to GlobalObject
  8876. // Cases like "this.a = "
  8877. isSymGlobalAndSingleAssignment = propertyNode->sxPid.pid->IsSingleAssignment();
  8878. Js::PropertyId propertyId = propertyNode->sxPid.PropertyIdFromNameNode();
  8879. TrackIntConstantsOnGlobalObject(byteCodeGenerator, isSymGlobalAndSingleAssignment, propertyId);
  8880. }
  8881. }
  8882. void TrackGlobalIntAssignments(ParseNodePtr pnode, ByteCodeGenerator * byteCodeGenerator)
  8883. {
  8884. // Track the Global Int Constant properties' assignments here.
  8885. uint nodeType = ParseNode::Grfnop(pnode->nop);
  8886. if (nodeType & fnopAsg)
  8887. {
  8888. if (nodeType & fnopBin)
  8889. {
  8890. ParseNodePtr lhs = pnode->sxBin.pnode1;
  8891. ParseNodePtr rhs = pnode->sxBin.pnode2;
  8892. Assert(lhs && rhs);
  8893. // Don't track other than integers and objects with member nodes.
  8894. if (rhs->nop == knopObject && (ParseNode::Grfnop(rhs->nop) & fnopUni))
  8895. {
  8896. TrackMemberNodesInObjectForIntConstants(byteCodeGenerator, rhs);
  8897. }
  8898. else if (rhs->nop != knopInt &&
  8899. ((rhs->nop != knopLsh && rhs->nop != knopRsh) || (rhs->sxBin.pnode1->nop != knopInt || rhs->sxBin.pnode2->nop != knopInt)))
  8900. {
  8901. return;
  8902. }
  8903. if (lhs->nop == knopName)
  8904. {
  8905. // Handle "a = <Integer>" cases here
  8906. Symbol * sym = lhs->sxVar.sym;
  8907. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  8908. }
  8909. else if (lhs->nop == knopDot && lhs->sxBin.pnode2->nop == knopName)
  8910. {
  8911. // Cases like "obj.a = <Integer>"
  8912. TrackGlobalIntAssignmentsForknopDotProps(lhs, byteCodeGenerator);
  8913. }
  8914. }
  8915. else if (nodeType & fnopUni)
  8916. {
  8917. ParseNodePtr lhs = pnode->sxUni.pnode1;
  8918. if (lhs->nop == knopName)
  8919. {
  8920. // Cases like "a++"
  8921. Symbol * sym = lhs->sxVar.sym;
  8922. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  8923. }
  8924. else if (lhs->nop == knopDot && lhs->sxBin.pnode2->nop == knopName)
  8925. {
  8926. // Cases like "obj.a++"
  8927. TrackGlobalIntAssignmentsForknopDotProps(lhs, byteCodeGenerator);
  8928. }
  8929. }
  8930. }
  8931. }
  8932. void Emit(ParseNode *pnode, ByteCodeGenerator *byteCodeGenerator, FuncInfo *funcInfo, BOOL fReturnValue, bool isConstructorCall, ParseNode * bindPnode, bool isTopLevel)
  8933. {
  8934. if (pnode == nullptr)
  8935. {
  8936. return;
  8937. }
  8938. ThreadContext::ProbeCurrentStackNoDispose(Js::Constants::MinStackByteCodeVisitor, byteCodeGenerator->GetScriptContext());
  8939. TrackGlobalIntAssignments(pnode, byteCodeGenerator);
  8940. // printNop(pnode->nop);
  8941. switch (pnode->nop)
  8942. {
  8943. case knopList:
  8944. EmitList(pnode, byteCodeGenerator, funcInfo);
  8945. break;
  8946. case knopInt:
  8947. // currently, these are loaded at the top
  8948. break;
  8949. // PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  8950. case knopFlt:
  8951. // currently, these are loaded at the top
  8952. break;
  8953. // PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  8954. case knopStr:
  8955. // TODO: protocol for combining string constants
  8956. break;
  8957. // PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  8958. case knopRegExp:
  8959. funcInfo->GetParsedFunctionBody()->SetLiteralRegex(pnode->sxPid.regexPatternIndex, pnode->sxPid.regexPattern);
  8960. byteCodeGenerator->Writer()->Reg1Unsigned1(Js::OpCode::NewRegEx, funcInfo->AcquireLoc(pnode), pnode->sxPid.regexPatternIndex);
  8961. break; // PTNODE(knopThis , "this" ,None ,None ,fnopLeaf)
  8962. case knopThis:
  8963. // enregistered
  8964. // Try to load 'this' from a scope slot if we are in a derived class constructor with scope slots. Otherwise, this is a nop.
  8965. byteCodeGenerator->EmitScopeSlotLoadThis(funcInfo, funcInfo->thisPointerRegister);
  8966. break;
  8967. // PTNODE(knopNewTarget , "new.target" ,None , None , fnopLeaf)
  8968. case knopNewTarget:
  8969. break;
  8970. // PTNODE(knopSuper , "super" ,None , None , fnopLeaf)
  8971. case knopSuper:
  8972. if (!funcInfo->IsClassMember())
  8973. {
  8974. FuncInfo* nonLambdaFunc = funcInfo;
  8975. if (funcInfo->IsLambda())
  8976. {
  8977. nonLambdaFunc = byteCodeGenerator->FindEnclosingNonLambda();
  8978. }
  8979. if (nonLambdaFunc->IsGlobalFunction())
  8980. {
  8981. if ((byteCodeGenerator->GetFlags() & fscrEval))
  8982. {
  8983. byteCodeGenerator->Writer()->Reg1(isConstructorCall ? Js::OpCode::ScopedLdFuncObj : Js::OpCode::ScopedLdHomeObj, funcInfo->AcquireLoc(pnode));
  8984. }
  8985. else
  8986. {
  8987. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_BadSuperReference));
  8988. }
  8989. }
  8990. }
  8991. break;
  8992. // PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  8993. case knopNull:
  8994. // enregistered
  8995. break;
  8996. // PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  8997. case knopFalse:
  8998. // enregistered
  8999. break;
  9000. // PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  9001. case knopTrue:
  9002. // enregistered
  9003. break;
  9004. // PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  9005. case knopEmpty:
  9006. break;
  9007. // Unary operators.
  9008. // PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  9009. case knopNot:
  9010. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9011. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  9012. funcInfo->ReleaseLoc(pnode->sxUni.pnode1);
  9013. byteCodeGenerator->Writer()->Reg2(
  9014. Js::OpCode::Not_A, funcInfo->AcquireLoc(pnode), pnode->sxUni.pnode1->location);
  9015. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9016. break;
  9017. // PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  9018. case knopNeg:
  9019. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9020. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  9021. funcInfo->ReleaseLoc(pnode->sxUni.pnode1);
  9022. funcInfo->AcquireLoc(pnode);
  9023. byteCodeGenerator->Writer()->Reg2(
  9024. Js::OpCode::Neg_A, pnode->location, pnode->sxUni.pnode1->location);
  9025. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9026. break;
  9027. // PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  9028. case knopPos:
  9029. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9030. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  9031. funcInfo->ReleaseLoc(pnode->sxUni.pnode1);
  9032. byteCodeGenerator->Writer()->Reg2(
  9033. Js::OpCode::Conv_Num, funcInfo->AcquireLoc(pnode), pnode->sxUni.pnode1->location);
  9034. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9035. break;
  9036. // PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  9037. case knopLogNot:
  9038. {
  9039. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9040. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  9041. // For boolean expressions that compute a result, we have to burn a register for the result
  9042. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  9043. // full-on renaming in the back end.
  9044. funcInfo->AcquireLoc(pnode);
  9045. if (pnode->sxUni.pnode1->nop == knopInt)
  9046. {
  9047. int32 value = pnode->sxUni.pnode1->sxInt.lw;
  9048. Js::OpCode op = value ? Js::OpCode::LdFalse : Js::OpCode::LdTrue;
  9049. byteCodeGenerator->Writer()->Reg1(op, pnode->location);
  9050. }
  9051. else
  9052. {
  9053. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  9054. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdFalse, pnode->location);
  9055. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrTrue_A, doneLabel, pnode->sxUni.pnode1->location);
  9056. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, pnode->location);
  9057. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  9058. }
  9059. funcInfo->ReleaseLoc(pnode->sxUni.pnode1);
  9060. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9061. break;
  9062. }
  9063. // PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  9064. case knopEllipsis:
  9065. {
  9066. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  9067. // Transparently pass the location of the array.
  9068. pnode->location = pnode->sxUni.pnode1->location;
  9069. break;
  9070. }
  9071. // PTNODE(knopIncPost , "post++" ,Inc ,Uni ,fnopUni|fnopAsg)
  9072. case knopIncPost:
  9073. case knopDecPost:
  9074. // FALL THROUGH to the faster pre-inc/dec case if the result of the expression is not needed.
  9075. if (pnode->isUsed || fReturnValue)
  9076. {
  9077. byteCodeGenerator->StartStatement(pnode);
  9078. Js::OpCode op = Js::OpCode::Add_A;
  9079. if (pnode->nop == knopDecPost)
  9080. {
  9081. op = Js::OpCode::Sub_A;
  9082. }
  9083. // Grab a register for the expression result.
  9084. funcInfo->AcquireLoc(pnode);
  9085. // Load the initial value, convert it (this is the expression result), and increment it.
  9086. EmitLoad(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo);
  9087. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Num, pnode->location, pnode->sxUni.pnode1->location);
  9088. Js::RegSlot incDecResult = pnode->sxUni.pnode1->location;
  9089. if (funcInfo->RegIsConst(incDecResult))
  9090. {
  9091. // Avoid letting the add/sub overwrite a constant reg, as this may actually change the
  9092. // contents of the constant table.
  9093. incDecResult = funcInfo->AcquireTmpRegister();
  9094. }
  9095. Js::RegSlot oneReg = funcInfo->constantToRegister.LookupWithKey(1, Js::Constants::NoRegister);
  9096. Assert(oneReg != Js::Constants::NoRegister);
  9097. byteCodeGenerator->Writer()->Reg3(op, incDecResult, pnode->location, oneReg);
  9098. // Store the incremented value.
  9099. EmitAssignment(nullptr, pnode->sxUni.pnode1, incDecResult, byteCodeGenerator, funcInfo);
  9100. // Release the incremented value and the l-value.
  9101. if (incDecResult != pnode->sxUni.pnode1->location)
  9102. {
  9103. funcInfo->ReleaseTmpRegister(incDecResult);
  9104. }
  9105. funcInfo->ReleaseLoad(pnode->sxUni.pnode1);
  9106. byteCodeGenerator->EndStatement(pnode);
  9107. break;
  9108. }
  9109. else
  9110. {
  9111. pnode->nop = (pnode->nop == knopIncPost) ? knopIncPre : knopDecPre;
  9112. }
  9113. // FALL THROUGH to the fast pre-inc/dec case if the result of the expression is not needed.
  9114. // PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  9115. case knopIncPre:
  9116. case knopDecPre:
  9117. {
  9118. byteCodeGenerator->StartStatement(pnode);
  9119. Js::OpCode op = Js::OpCode::Incr_A;
  9120. if (pnode->nop == knopDecPre)
  9121. {
  9122. op = Js::OpCode::Decr_A;
  9123. }
  9124. // Assign a register for the result only if the result is used or the operand can't be assigned to
  9125. // (i.e., is a constant).
  9126. if (pnode->isUsed || fReturnValue)
  9127. {
  9128. funcInfo->AcquireLoc(pnode);
  9129. // Load the initial value and increment it (this is the expression result).
  9130. EmitLoad(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo);
  9131. byteCodeGenerator->Writer()->Reg2(op, pnode->location, pnode->sxUni.pnode1->location);
  9132. // Store the incremented value and release the l-value.
  9133. EmitAssignment(nullptr, pnode->sxUni.pnode1, pnode->location, byteCodeGenerator, funcInfo);
  9134. funcInfo->ReleaseLoad(pnode->sxUni.pnode1);
  9135. }
  9136. else
  9137. {
  9138. // Load the initial value and increment it (this is the expression result).
  9139. EmitLoad(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo);
  9140. Js::RegSlot incDecResult = pnode->sxUni.pnode1->location;
  9141. if (funcInfo->RegIsConst(incDecResult))
  9142. {
  9143. // Avoid letting the add/sub overwrite a constant reg, as this may actually change the
  9144. // contents of the constant table.
  9145. incDecResult = funcInfo->AcquireTmpRegister();
  9146. }
  9147. byteCodeGenerator->Writer()->Reg2(op, incDecResult, pnode->sxUni.pnode1->location);
  9148. // Store the incremented value and release the l-value.
  9149. EmitAssignment(nullptr, pnode->sxUni.pnode1, incDecResult, byteCodeGenerator, funcInfo);
  9150. if (incDecResult != pnode->sxUni.pnode1->location)
  9151. {
  9152. funcInfo->ReleaseTmpRegister(incDecResult);
  9153. }
  9154. funcInfo->ReleaseLoad(pnode->sxUni.pnode1);
  9155. }
  9156. byteCodeGenerator->EndStatement(pnode);
  9157. break;
  9158. }
  9159. // PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  9160. case knopTypeof:
  9161. {
  9162. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9163. ParseNode* pnodeOpnd = pnode->sxUni.pnode1;
  9164. switch (pnodeOpnd->nop)
  9165. {
  9166. case knopDot:
  9167. {
  9168. Emit(pnodeOpnd->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  9169. Js::PropertyId propertyId = pnodeOpnd->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  9170. Assert(pnodeOpnd->sxBin.pnode2->nop == knopName);
  9171. funcInfo->ReleaseLoc(pnodeOpnd->sxBin.pnode1);
  9172. funcInfo->AcquireLoc(pnode);
  9173. byteCodeGenerator->EmitTypeOfFld(funcInfo, propertyId, pnode->location, pnodeOpnd->sxBin.pnode1->location, Js::OpCode::LdFldForTypeOf);
  9174. break;
  9175. }
  9176. case knopIndex:
  9177. {
  9178. EmitBinaryOpnds(pnodeOpnd->sxBin.pnode1, pnodeOpnd->sxBin.pnode2, byteCodeGenerator, funcInfo);
  9179. funcInfo->ReleaseLoc(pnodeOpnd->sxBin.pnode2);
  9180. funcInfo->ReleaseLoc(pnodeOpnd->sxBin.pnode1);
  9181. funcInfo->AcquireLoc(pnode);
  9182. byteCodeGenerator->Writer()->Element(Js::OpCode::TypeofElem, pnode->location, pnodeOpnd->sxBin.pnode1->location, pnodeOpnd->sxBin.pnode2->location);
  9183. break;
  9184. }
  9185. case knopName:
  9186. {
  9187. funcInfo->AcquireLoc(pnode);
  9188. byteCodeGenerator->EmitPropTypeof(pnode->location, pnodeOpnd->sxPid.sym, pnodeOpnd->sxPid.pid, funcInfo);
  9189. break;
  9190. }
  9191. default:
  9192. Emit(pnodeOpnd, byteCodeGenerator, funcInfo, false);
  9193. funcInfo->ReleaseLoc(pnodeOpnd);
  9194. byteCodeGenerator->Writer()->Reg2(
  9195. Js::OpCode::Typeof, funcInfo->AcquireLoc(pnode), pnodeOpnd->location);
  9196. break;
  9197. }
  9198. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9199. break;
  9200. }
  9201. // PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  9202. case knopVoid:
  9203. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  9204. funcInfo->ReleaseLoc(pnode->sxUni.pnode1);
  9205. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, funcInfo->AcquireLoc(pnode));
  9206. break;
  9207. // PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  9208. case knopArray:
  9209. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9210. EmitArrayLiteral(pnode, byteCodeGenerator, funcInfo);
  9211. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9212. break;
  9213. // PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  9214. case knopObject:
  9215. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9216. funcInfo->AcquireLoc(pnode);
  9217. EmitObjectInitializers(pnode->sxUni.pnode1, pnode->location, byteCodeGenerator, funcInfo);
  9218. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9219. break;
  9220. // PTNODE(knopComputedName, "[name]" ,None ,Uni ,fnopUni)
  9221. case knopComputedName:
  9222. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  9223. if (pnode->location == Js::Constants::NoRegister)
  9224. {
  9225. // The name is some expression with no home location. We can just re-use the register.
  9226. pnode->location = pnode->sxUni.pnode1->location;
  9227. }
  9228. else if (pnode->location != pnode->sxUni.pnode1->location)
  9229. {
  9230. // The name had to be protected from side-effects of the RHS.
  9231. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxUni.pnode1->location);
  9232. }
  9233. break;
  9234. // Binary and Ternary Operators
  9235. case knopAdd:
  9236. EmitAdd(pnode, byteCodeGenerator, funcInfo);
  9237. break;
  9238. case knopSub:
  9239. case knopMul:
  9240. case knopExpo:
  9241. case knopDiv:
  9242. case knopMod:
  9243. case knopOr:
  9244. case knopXor:
  9245. case knopAnd:
  9246. case knopLsh:
  9247. case knopRsh:
  9248. case knopRs2:
  9249. case knopIn:
  9250. EmitBinary(nopToOp[pnode->nop], pnode, byteCodeGenerator, funcInfo);
  9251. break;
  9252. case knopInstOf:
  9253. {
  9254. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9255. EmitBinaryOpnds(pnode->sxBin.pnode1, pnode->sxBin.pnode2, byteCodeGenerator, funcInfo);
  9256. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  9257. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  9258. funcInfo->AcquireLoc(pnode);
  9259. uint cacheId = funcInfo->NewIsInstInlineCache();
  9260. byteCodeGenerator->Writer()->Reg3C(nopToOp[pnode->nop], pnode->location, pnode->sxBin.pnode1->location,
  9261. pnode->sxBin.pnode2->location, cacheId);
  9262. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9263. }
  9264. break;
  9265. case knopEq:
  9266. case knopEqv:
  9267. case knopNEqv:
  9268. case knopNe:
  9269. case knopLt:
  9270. case knopLe:
  9271. case knopGe:
  9272. case knopGt:
  9273. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9274. EmitBinaryOpnds(pnode->sxBin.pnode1, pnode->sxBin.pnode2, byteCodeGenerator, funcInfo);
  9275. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  9276. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  9277. funcInfo->AcquireLoc(pnode);
  9278. byteCodeGenerator->Writer()->Reg3(nopToCMOp[pnode->nop], pnode->location, pnode->sxBin.pnode1->location,
  9279. pnode->sxBin.pnode2->location);
  9280. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9281. break;
  9282. case knopNew:
  9283. {
  9284. EmitNew(pnode, byteCodeGenerator, funcInfo);
  9285. byteCodeGenerator->EndStatement(pnode);
  9286. break;
  9287. }
  9288. case knopDelete:
  9289. {
  9290. ParseNode *pexpr = pnode->sxUni.pnode1;
  9291. byteCodeGenerator->StartStatement(pnode);
  9292. switch (pexpr->nop)
  9293. {
  9294. case knopName:
  9295. {
  9296. funcInfo->AcquireLoc(pnode);
  9297. byteCodeGenerator->EmitPropDelete(pnode->location, pexpr->sxPid.sym, pexpr->sxPid.pid, funcInfo);
  9298. break;
  9299. }
  9300. case knopDot:
  9301. {
  9302. Emit(pexpr->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  9303. Js::PropertyId propertyId = pexpr->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  9304. funcInfo->ReleaseLoc(pexpr->sxBin.pnode1);
  9305. funcInfo->AcquireLoc(pnode);
  9306. if (pexpr->sxBin.pnode1->nop == knopSuper)
  9307. {
  9308. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeReferenceError, SCODE_CODE(JSERR_DeletePropertyWithSuper));
  9309. }
  9310. else
  9311. {
  9312. byteCodeGenerator->Writer()->Property(Js::OpCode::DeleteFld, pnode->location, pexpr->sxBin.pnode1->location,
  9313. funcInfo->FindOrAddReferencedPropertyId(propertyId));
  9314. }
  9315. break;
  9316. }
  9317. case knopIndex:
  9318. {
  9319. EmitBinaryOpnds(pexpr->sxBin.pnode1, pexpr->sxBin.pnode2, byteCodeGenerator, funcInfo);
  9320. funcInfo->ReleaseLoc(pexpr->sxBin.pnode2);
  9321. funcInfo->ReleaseLoc(pexpr->sxBin.pnode1);
  9322. funcInfo->AcquireLoc(pnode);
  9323. byteCodeGenerator->Writer()->Element(Js::OpCode::DeleteElemI_A, pnode->location, pexpr->sxBin.pnode1->location, pexpr->sxBin.pnode2->location);
  9324. break;
  9325. }
  9326. case knopThis:
  9327. {
  9328. funcInfo->AcquireLoc(pnode);
  9329. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdTrue, pnode->location);
  9330. break;
  9331. }
  9332. default:
  9333. {
  9334. Emit(pexpr, byteCodeGenerator, funcInfo, false);
  9335. funcInfo->ReleaseLoc(pexpr);
  9336. byteCodeGenerator->Writer()->Reg2(
  9337. Js::OpCode::Delete_A, funcInfo->AcquireLoc(pnode), pexpr->location);
  9338. break;
  9339. }
  9340. }
  9341. byteCodeGenerator->EndStatement(pnode);
  9342. break;
  9343. }
  9344. case knopCall:
  9345. {
  9346. byteCodeGenerator->StartStatement(pnode);
  9347. if (pnode->sxCall.pnodeTarget->nop == knopSuper)
  9348. {
  9349. byteCodeGenerator->EmitSuperCall(funcInfo, pnode, fReturnValue);
  9350. }
  9351. else
  9352. {
  9353. if (pnode->sxCall.isApplyCall && funcInfo->GetApplyEnclosesArgs())
  9354. {
  9355. // TODO[ianhall]: Can we remove the ApplyCall bytecode gen time optimization?
  9356. EmitApplyCall(pnode, Js::Constants::NoRegister, byteCodeGenerator, funcInfo, fReturnValue);
  9357. }
  9358. else
  9359. {
  9360. EmitCall(pnode, Js::Constants::NoRegister, byteCodeGenerator, funcInfo, fReturnValue, /*fEvaluateComponents*/ true, /*fHasNewTarget*/ false);
  9361. }
  9362. }
  9363. byteCodeGenerator->EndStatement(pnode);
  9364. break;
  9365. }
  9366. case knopIndex:
  9367. {
  9368. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9369. EmitBinaryOpnds(pnode->sxBin.pnode1, pnode->sxBin.pnode2, byteCodeGenerator, funcInfo);
  9370. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  9371. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  9372. funcInfo->AcquireLoc(pnode);
  9373. Js::RegSlot callObjLocation = pnode->sxBin.pnode1->location;
  9374. Js::RegSlot protoLocation =
  9375. (pnode->sxBin.pnode1->nop == knopSuper) ?
  9376. byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, funcInfo->superRegister, funcInfo) :
  9377. callObjLocation;
  9378. EmitSuperMethodBegin(pnode, byteCodeGenerator, funcInfo);
  9379. byteCodeGenerator->Writer()->Element(
  9380. Js::OpCode::LdElemI_A, pnode->location, protoLocation, pnode->sxBin.pnode2->location);
  9381. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9382. break;
  9383. }
  9384. // this is MemberExpression as rvalue
  9385. case knopDot:
  9386. {
  9387. Emit(pnode->sxBin.pnode1, byteCodeGenerator, funcInfo, false);
  9388. funcInfo->ReleaseLoc(pnode->sxBin.pnode1);
  9389. funcInfo->AcquireLoc(pnode);
  9390. Js::PropertyId propertyId = pnode->sxBin.pnode2->sxPid.PropertyIdFromNameNode();
  9391. Js::RegSlot callObjLocation = pnode->sxBin.pnode1->location;
  9392. Js::RegSlot protoLocation = callObjLocation;
  9393. EmitSuperMethodBegin(pnode, byteCodeGenerator, funcInfo);
  9394. uint cacheId = funcInfo->FindOrAddInlineCacheId(callObjLocation, propertyId, false, false);
  9395. if (pnode->IsCallApplyTargetLoad())
  9396. {
  9397. if (pnode->sxBin.pnode1->nop == knopSuper)
  9398. {
  9399. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, funcInfo->superRegister, funcInfo);
  9400. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFldForCallApplyTarget, pnode->location, tmpReg, cacheId);
  9401. }
  9402. else
  9403. {
  9404. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFldForCallApplyTarget, pnode->location, protoLocation, cacheId);
  9405. }
  9406. }
  9407. else
  9408. {
  9409. if (pnode->sxBin.pnode1->nop == knopSuper)
  9410. {
  9411. Js::RegSlot tmpReg = byteCodeGenerator->EmitLdObjProto(Js::OpCode::LdHomeObjProto, funcInfo->superRegister, funcInfo);
  9412. byteCodeGenerator->Writer()->PatchablePropertyWithThisPtr(Js::OpCode::LdSuperFld, pnode->location, tmpReg, funcInfo->thisPointerRegister, cacheId, isConstructorCall);
  9413. }
  9414. else
  9415. {
  9416. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, pnode->location, callObjLocation, cacheId, isConstructorCall);
  9417. }
  9418. }
  9419. break;
  9420. }
  9421. // PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  9422. case knopAsg:
  9423. {
  9424. ParseNode *lhs = pnode->sxBin.pnode1;
  9425. ParseNode *rhs = pnode->sxBin.pnode2;
  9426. byteCodeGenerator->StartStatement(pnode);
  9427. if (pnode->isUsed || fReturnValue)
  9428. {
  9429. // If the assignment result is used, grab a register to hold it and pass it to EmitAssignment,
  9430. // which will copy the assigned value there.
  9431. funcInfo->AcquireLoc(pnode);
  9432. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, false);
  9433. EmitAssignment(pnode, lhs, rhs->location, byteCodeGenerator, funcInfo);
  9434. }
  9435. else
  9436. {
  9437. EmitBinaryReference(lhs, rhs, byteCodeGenerator, funcInfo, false);
  9438. EmitAssignment(nullptr, lhs, rhs->location, byteCodeGenerator, funcInfo);
  9439. }
  9440. funcInfo->ReleaseLoc(rhs);
  9441. if (!(byteCodeGenerator->IsES6DestructuringEnabled() && (lhs->IsPattern())))
  9442. {
  9443. funcInfo->ReleaseReference(lhs);
  9444. }
  9445. byteCodeGenerator->EndStatement(pnode);
  9446. break;
  9447. }
  9448. case knopName:
  9449. funcInfo->AcquireLoc(pnode);
  9450. byteCodeGenerator->EmitPropLoad(pnode->location, pnode->sxPid.sym, pnode->sxPid.pid, funcInfo);
  9451. break;
  9452. case knopComma:
  9453. {
  9454. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9455. // The parser marks binary opnd pnodes as used, but value of the first opnd of a comma is not used.
  9456. // Easier to correct this here than to check every binary op in the parser.
  9457. ParseNode *pnode1 = pnode->sxBin.pnode1;
  9458. pnode1->isUsed = false;
  9459. if (pnode1->nop == knopComma)
  9460. {
  9461. // Spot fix for giant comma expressions that send us into OOS if we use a simple recursive
  9462. // algorithm. Instead of recursing on comma LHS's, iterate over them, pushing the RHS's onto
  9463. // a stack. (This suggests a model for removing recursion from Emit altogether...)
  9464. ArenaAllocator *alloc = byteCodeGenerator->GetAllocator();
  9465. SList<ParseNode *> rhsStack(alloc);
  9466. do
  9467. {
  9468. rhsStack.Push(pnode1->sxBin.pnode2);
  9469. pnode1 = pnode1->sxBin.pnode1;
  9470. pnode1->isUsed = false;
  9471. } while (pnode1->nop == knopComma);
  9472. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  9473. if (funcInfo->IsTmpReg(pnode1->location))
  9474. {
  9475. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Unused, pnode1->location);
  9476. }
  9477. while (!rhsStack.Empty())
  9478. {
  9479. ParseNode *pnodeRhs = rhsStack.Pop();
  9480. pnodeRhs->isUsed = false;
  9481. Emit(pnodeRhs, byteCodeGenerator, funcInfo, false);
  9482. if (funcInfo->IsTmpReg(pnodeRhs->location))
  9483. {
  9484. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Unused, pnodeRhs->location);
  9485. }
  9486. funcInfo->ReleaseLoc(pnodeRhs);
  9487. }
  9488. }
  9489. else
  9490. {
  9491. Emit(pnode1, byteCodeGenerator, funcInfo, false);
  9492. if (funcInfo->IsTmpReg(pnode1->location))
  9493. {
  9494. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Unused, pnode1->location);
  9495. }
  9496. }
  9497. funcInfo->ReleaseLoc(pnode1);
  9498. pnode->sxBin.pnode2->isUsed = pnode->isUsed || fReturnValue;
  9499. Emit(pnode->sxBin.pnode2, byteCodeGenerator, funcInfo, false);
  9500. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  9501. funcInfo->AcquireLoc(pnode);
  9502. if (pnode->sxBin.pnode2->isUsed && pnode->location != pnode->sxBin.pnode2->location)
  9503. {
  9504. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxBin.pnode2->location);
  9505. }
  9506. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9507. }
  9508. break;
  9509. // The binary logical ops && and || resolve to the value of the left-hand expression if its
  9510. // boolean value short-circuits the operation, and to the value of the right-hand expression
  9511. // otherwise. (In other words, the "truth" of the right-hand expression is never tested.)
  9512. // PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  9513. case knopLogOr:
  9514. {
  9515. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9516. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  9517. // We use a single dest here for the whole generating boolean expr, because we were poorly
  9518. // optimizing the previous version where we had a dest for each level
  9519. funcInfo->AcquireLoc(pnode);
  9520. EmitGeneratingBooleanExpression(pnode, doneLabel, true, doneLabel, true, pnode->location, byteCodeGenerator, funcInfo);
  9521. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  9522. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9523. break;
  9524. }
  9525. // PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  9526. case knopLogAnd:
  9527. {
  9528. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9529. Js::ByteCodeLabel doneLabel = byteCodeGenerator->Writer()->DefineLabel();
  9530. // We use a single dest here for the whole generating boolean expr, because we were poorly
  9531. // optimizing the previous version where we had a dest for each level
  9532. funcInfo->AcquireLoc(pnode);
  9533. EmitGeneratingBooleanExpression(pnode, doneLabel, true, doneLabel, true, pnode->location, byteCodeGenerator, funcInfo);
  9534. byteCodeGenerator->Writer()->MarkLabel(doneLabel);
  9535. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9536. break;
  9537. }
  9538. // PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  9539. case knopQmark:
  9540. {
  9541. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  9542. Js::ByteCodeLabel falseLabel = byteCodeGenerator->Writer()->DefineLabel();
  9543. Js::ByteCodeLabel skipLabel = byteCodeGenerator->Writer()->DefineLabel();
  9544. EmitBooleanExpression(pnode->sxTri.pnode1, trueLabel, falseLabel, byteCodeGenerator, funcInfo);
  9545. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  9546. funcInfo->ReleaseLoc(pnode->sxTri.pnode1);
  9547. // For boolean expressions that compute a result, we have to burn a register for the result
  9548. // so that the back end can identify it cheaply as a single temp lifetime. Revisit this if we do
  9549. // full-on renaming in the back end.
  9550. funcInfo->AcquireLoc(pnode);
  9551. Emit(pnode->sxTri.pnode2, byteCodeGenerator, funcInfo, false);
  9552. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxTri.pnode2->location);
  9553. funcInfo->ReleaseLoc(pnode->sxTri.pnode2);
  9554. // Record the branch bytecode offset
  9555. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_FromCurrentToNext);
  9556. byteCodeGenerator->Writer()->Br(skipLabel);
  9557. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  9558. Emit(pnode->sxTri.pnode3, byteCodeGenerator, funcInfo, false);
  9559. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxTri.pnode3->location);
  9560. funcInfo->ReleaseLoc(pnode->sxTri.pnode3);
  9561. byteCodeGenerator->Writer()->MarkLabel(skipLabel);
  9562. break;
  9563. }
  9564. case knopAsgAdd:
  9565. case knopAsgSub:
  9566. case knopAsgMul:
  9567. case knopAsgDiv:
  9568. case knopAsgExpo:
  9569. case knopAsgMod:
  9570. case knopAsgAnd:
  9571. case knopAsgXor:
  9572. case knopAsgOr:
  9573. case knopAsgLsh:
  9574. case knopAsgRsh:
  9575. case knopAsgRs2:
  9576. byteCodeGenerator->StartStatement(pnode);
  9577. // Assign a register for the result only if the result is used or the LHS can't be assigned to
  9578. // (i.e., is a constant).
  9579. if (pnode->isUsed || fReturnValue || funcInfo->RegIsConst(pnode->sxBin.pnode1->location))
  9580. {
  9581. // If the assign-op result is used, grab a register to hold it.
  9582. funcInfo->AcquireLoc(pnode);
  9583. // Grab a register for the initial value and load it.
  9584. EmitBinaryReference(pnode->sxBin.pnode1, pnode->sxBin.pnode2, byteCodeGenerator, funcInfo, true);
  9585. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  9586. // Do the arithmetic, store the result, and release the l-value.
  9587. byteCodeGenerator->Writer()->Reg3(nopToOp[pnode->nop], pnode->location, pnode->sxBin.pnode1->location,
  9588. pnode->sxBin.pnode2->location);
  9589. EmitAssignment(pnode, pnode->sxBin.pnode1, pnode->location, byteCodeGenerator, funcInfo);
  9590. }
  9591. else
  9592. {
  9593. // Grab a register for the initial value and load it.
  9594. EmitBinaryReference(pnode->sxBin.pnode1, pnode->sxBin.pnode2, byteCodeGenerator, funcInfo, true);
  9595. funcInfo->ReleaseLoc(pnode->sxBin.pnode2);
  9596. // Do the arithmetic, store the result, and release the l-value.
  9597. byteCodeGenerator->Writer()->Reg3(nopToOp[pnode->nop], pnode->sxBin.pnode1->location, pnode->sxBin.pnode1->location,
  9598. pnode->sxBin.pnode2->location);
  9599. EmitAssignment(nullptr, pnode->sxBin.pnode1, pnode->sxBin.pnode1->location, byteCodeGenerator, funcInfo);
  9600. }
  9601. funcInfo->ReleaseLoad(pnode->sxBin.pnode1);
  9602. byteCodeGenerator->EndStatement(pnode);
  9603. break;
  9604. // General nodes.
  9605. // PTNODE(knopTempRef , "temp ref" ,None ,Uni ,fnopUni)
  9606. case knopTempRef:
  9607. // TODO: check whether mov is necessary
  9608. funcInfo->AcquireLoc(pnode);
  9609. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxUni.pnode1->location);
  9610. break;
  9611. // PTNODE(knopTemp , "temp" ,None ,None ,fnopLeaf)
  9612. case knopTemp:
  9613. // Emit initialization code
  9614. if (pnode->sxVar.pnodeInit != nullptr)
  9615. {
  9616. byteCodeGenerator->StartStatement(pnode);
  9617. Emit(pnode->sxVar.pnodeInit, byteCodeGenerator, funcInfo, false);
  9618. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, pnode->location, pnode->sxVar.pnodeInit->location);
  9619. funcInfo->ReleaseLoc(pnode->sxVar.pnodeInit);
  9620. byteCodeGenerator->EndStatement(pnode);
  9621. }
  9622. break;
  9623. // PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  9624. case knopVarDecl:
  9625. case knopConstDecl:
  9626. case knopLetDecl:
  9627. {
  9628. // Emit initialization code
  9629. ParseNodePtr initNode = pnode->sxVar.pnodeInit;
  9630. AssertMsg(pnode->nop != knopConstDecl || initNode != nullptr, "knopConstDecl expected to have an initializer");
  9631. if (initNode != nullptr || pnode->nop == knopLetDecl)
  9632. {
  9633. Symbol *sym = pnode->sxVar.sym;
  9634. Js::RegSlot rhsLocation;
  9635. byteCodeGenerator->StartStatement(pnode);
  9636. if (initNode != nullptr)
  9637. {
  9638. Emit(initNode, byteCodeGenerator, funcInfo, false);
  9639. rhsLocation = initNode->location;
  9640. if (initNode->nop == knopObject)
  9641. {
  9642. TrackMemberNodesInObjectForIntConstants(byteCodeGenerator, initNode);
  9643. }
  9644. else if (initNode->nop == knopInt)
  9645. {
  9646. TrackIntConstantsOnGlobalObject(byteCodeGenerator, sym);
  9647. }
  9648. }
  9649. else
  9650. {
  9651. Assert(pnode->nop == knopLetDecl);
  9652. rhsLocation = funcInfo->AcquireTmpRegister();
  9653. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, rhsLocation);
  9654. }
  9655. if (pnode->nop != knopVarDecl)
  9656. {
  9657. Assert(sym->GetDecl() == pnode);
  9658. sym->SetNeedDeclaration(false);
  9659. }
  9660. EmitAssignment(nullptr, pnode, rhsLocation, byteCodeGenerator, funcInfo);
  9661. funcInfo->ReleaseTmpRegister(rhsLocation);
  9662. byteCodeGenerator->EndStatement(pnode);
  9663. }
  9664. break;
  9665. }
  9666. // PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  9667. case knopFncDecl:
  9668. // The "function declarations" were emitted in DefineFunctions()
  9669. if (!pnode->sxFnc.IsDeclaration())
  9670. {
  9671. byteCodeGenerator->DefineOneFunction(pnode, funcInfo, false);
  9672. }
  9673. break;
  9674. // PTNODE(knopClassDecl, "class" ,None ,None ,fnopLeaf)
  9675. case knopClassDecl:
  9676. {
  9677. funcInfo->AcquireLoc(pnode);
  9678. Assert(pnode->sxClass.pnodeConstructor);
  9679. pnode->sxClass.pnodeConstructor->location = pnode->location;
  9680. BeginEmitBlock(pnode->sxClass.pnodeBlock, byteCodeGenerator, funcInfo);
  9681. // Extends
  9682. if (pnode->sxClass.pnodeExtends)
  9683. {
  9684. // We can't do StartStatement/EndStatement for pnodeExtends here because the load locations may differ between
  9685. // defer and nondefer parse modes.
  9686. Emit(pnode->sxClass.pnodeExtends, byteCodeGenerator, funcInfo, false);
  9687. }
  9688. // Constructor
  9689. Emit(pnode->sxClass.pnodeConstructor, byteCodeGenerator, funcInfo, false);
  9690. EmitComputedFunctionNameVar(bindPnode, pnode->sxClass.pnodeConstructor, byteCodeGenerator);
  9691. if (pnode->sxClass.pnodeExtends)
  9692. {
  9693. byteCodeGenerator->StartStatement(pnode->sxClass.pnodeExtends);
  9694. byteCodeGenerator->Writer()->InitClass(pnode->location, pnode->sxClass.pnodeExtends->location);
  9695. byteCodeGenerator->EndStatement(pnode->sxClass.pnodeExtends);
  9696. }
  9697. else
  9698. {
  9699. byteCodeGenerator->Writer()->InitClass(pnode->location);
  9700. }
  9701. Js::RegSlot protoLoc = funcInfo->AcquireTmpRegister(); //register set if we have Instance Methods
  9702. int cacheId = funcInfo->FindOrAddInlineCacheId(pnode->location, Js::PropertyIds::prototype, false, false);
  9703. byteCodeGenerator->Writer()->PatchableProperty(Js::OpCode::LdFld, protoLoc, pnode->location, cacheId);
  9704. byteCodeGenerator->Writer()->Reg2(Js::OpCode::SetHomeObj, pnode->location, protoLoc);
  9705. // Static Methods
  9706. EmitClassInitializers(pnode->sxClass.pnodeStaticMembers, pnode->location, byteCodeGenerator, funcInfo, pnode, /*isObjectEmpty*/ false);
  9707. // Instance Methods
  9708. EmitClassInitializers(pnode->sxClass.pnodeMembers, protoLoc, byteCodeGenerator, funcInfo, pnode, /*isObjectEmpty*/ true);
  9709. funcInfo->ReleaseTmpRegister(protoLoc);
  9710. // Emit name binding.
  9711. if (pnode->sxClass.pnodeName)
  9712. {
  9713. Symbol * sym = pnode->sxClass.pnodeName->sxVar.sym;
  9714. sym->SetNeedDeclaration(false);
  9715. byteCodeGenerator->EmitPropStore(pnode->location, sym, nullptr, funcInfo, false, true);
  9716. }
  9717. EndEmitBlock(pnode->sxClass.pnodeBlock, byteCodeGenerator, funcInfo);
  9718. if (pnode->sxClass.pnodeExtends)
  9719. {
  9720. funcInfo->ReleaseLoc(pnode->sxClass.pnodeExtends);
  9721. }
  9722. if (pnode->sxClass.pnodeDeclName)
  9723. {
  9724. Symbol * sym = pnode->sxClass.pnodeDeclName->sxVar.sym;
  9725. sym->SetNeedDeclaration(false);
  9726. byteCodeGenerator->EmitPropStore(pnode->location, sym, nullptr, funcInfo, true, false);
  9727. }
  9728. if (pnode->sxClass.IsDefaultModuleExport())
  9729. {
  9730. byteCodeGenerator->EmitAssignmentToDefaultModuleExport(pnode, funcInfo);
  9731. }
  9732. break;
  9733. }
  9734. case knopStrTemplate:
  9735. STARTSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9736. EmitStringTemplate(pnode, byteCodeGenerator, funcInfo);
  9737. ENDSTATEMENET_IFTOPLEVEL(isTopLevel, pnode);
  9738. break;
  9739. case knopEndCode:
  9740. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_All);
  9741. // load undefined for the fallthrough case:
  9742. if (!funcInfo->IsGlobalFunction())
  9743. {
  9744. if (funcInfo->IsClassConstructor())
  9745. {
  9746. // For class constructors, we need to explicitly load 'this' into the return register.
  9747. byteCodeGenerator->EmitClassConstructorEndCode(funcInfo);
  9748. }
  9749. else
  9750. {
  9751. // In the global function, implicit return values are copied to the return register, and if
  9752. // necessary the return register is initialized at the top. Don't clobber the value here.
  9753. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, ByteCodeGenerator::ReturnRegister);
  9754. }
  9755. }
  9756. // Label for non-fall-through return
  9757. byteCodeGenerator->Writer()->MarkLabel(funcInfo->singleExit);
  9758. if (funcInfo->GetHasCachedScope())
  9759. {
  9760. byteCodeGenerator->Writer()->Empty(Js::OpCode::CommitScope);
  9761. }
  9762. byteCodeGenerator->StartStatement(pnode);
  9763. byteCodeGenerator->Writer()->Empty(Js::OpCode::Ret);
  9764. byteCodeGenerator->EndStatement(pnode);
  9765. break;
  9766. // PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  9767. case knopDebugger:
  9768. byteCodeGenerator->StartStatement(pnode);
  9769. byteCodeGenerator->Writer()->Empty(Js::OpCode::Break);
  9770. byteCodeGenerator->EndStatement(pnode);
  9771. break;
  9772. // PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  9773. case knopFor:
  9774. if (pnode->sxFor.pnodeInverted != nullptr)
  9775. {
  9776. byteCodeGenerator->EmitInvertedLoop(pnode, pnode->sxFor.pnodeInverted, funcInfo);
  9777. }
  9778. else
  9779. {
  9780. BeginEmitBlock(pnode->sxFor.pnodeBlock, byteCodeGenerator, funcInfo);
  9781. Emit(pnode->sxFor.pnodeInit, byteCodeGenerator, funcInfo, false);
  9782. funcInfo->ReleaseLoc(pnode->sxFor.pnodeInit);
  9783. if (byteCodeGenerator->IsES6ForLoopSemanticsEnabled())
  9784. {
  9785. CloneEmitBlock(pnode->sxFor.pnodeBlock, byteCodeGenerator, funcInfo);
  9786. }
  9787. EmitLoop(pnode,
  9788. pnode->sxFor.pnodeCond,
  9789. pnode->sxFor.pnodeBody,
  9790. pnode->sxFor.pnodeIncr,
  9791. byteCodeGenerator,
  9792. funcInfo,
  9793. fReturnValue,
  9794. FALSE,
  9795. pnode->sxFor.pnodeBlock);
  9796. EndEmitBlock(pnode->sxFor.pnodeBlock, byteCodeGenerator, funcInfo);
  9797. }
  9798. break;
  9799. // PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  9800. case knopIf:
  9801. {
  9802. byteCodeGenerator->StartStatement(pnode);
  9803. Js::ByteCodeLabel trueLabel = byteCodeGenerator->Writer()->DefineLabel();
  9804. Js::ByteCodeLabel falseLabel = byteCodeGenerator->Writer()->DefineLabel();
  9805. EmitBooleanExpression(pnode->sxIf.pnodeCond, trueLabel, falseLabel, byteCodeGenerator, funcInfo);
  9806. funcInfo->ReleaseLoc(pnode->sxIf.pnodeCond);
  9807. byteCodeGenerator->EndStatement(pnode);
  9808. byteCodeGenerator->Writer()->MarkLabel(trueLabel);
  9809. Emit(pnode->sxIf.pnodeTrue, byteCodeGenerator, funcInfo, fReturnValue);
  9810. funcInfo->ReleaseLoc(pnode->sxIf.pnodeTrue);
  9811. if (pnode->sxIf.pnodeFalse != nullptr)
  9812. {
  9813. // has else clause
  9814. Js::ByteCodeLabel skipLabel = byteCodeGenerator->Writer()->DefineLabel();
  9815. // Record the branch bytecode offset
  9816. byteCodeGenerator->Writer()->RecordStatementAdjustment(Js::FunctionBody::SAT_FromCurrentToNext);
  9817. // then clause skips else clause
  9818. byteCodeGenerator->Writer()->Br(skipLabel);
  9819. // generate code for else clause
  9820. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  9821. Emit(pnode->sxIf.pnodeFalse, byteCodeGenerator, funcInfo, fReturnValue);
  9822. funcInfo->ReleaseLoc(pnode->sxIf.pnodeFalse);
  9823. byteCodeGenerator->Writer()->MarkLabel(skipLabel);
  9824. }
  9825. else
  9826. {
  9827. byteCodeGenerator->Writer()->MarkLabel(falseLabel);
  9828. }
  9829. if (pnode->emitLabels)
  9830. {
  9831. byteCodeGenerator->Writer()->MarkLabel(pnode->sxStmt.breakLabel);
  9832. }
  9833. break;
  9834. }
  9835. case knopWhile:
  9836. EmitLoop(pnode,
  9837. pnode->sxWhile.pnodeCond,
  9838. pnode->sxWhile.pnodeBody,
  9839. nullptr,
  9840. byteCodeGenerator,
  9841. funcInfo,
  9842. fReturnValue);
  9843. break;
  9844. // PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  9845. case knopDoWhile:
  9846. EmitLoop(pnode,
  9847. pnode->sxWhile.pnodeCond,
  9848. pnode->sxWhile.pnodeBody,
  9849. nullptr,
  9850. byteCodeGenerator,
  9851. funcInfo,
  9852. fReturnValue,
  9853. true);
  9854. break;
  9855. // PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  9856. case knopForIn:
  9857. EmitForInOrForOf(pnode, byteCodeGenerator, funcInfo, fReturnValue);
  9858. break;
  9859. case knopForOf:
  9860. EmitForInOrForOf(pnode, byteCodeGenerator, funcInfo, fReturnValue);
  9861. break;
  9862. // PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  9863. case knopReturn:
  9864. byteCodeGenerator->StartStatement(pnode);
  9865. if (pnode->sxReturn.pnodeExpr != nullptr)
  9866. {
  9867. if (pnode->sxReturn.pnodeExpr->location == Js::Constants::NoRegister)
  9868. {
  9869. // No need to burn a register for the return value. If we need a temp, use R0 directly.
  9870. pnode->sxReturn.pnodeExpr->location = ByteCodeGenerator::ReturnRegister;
  9871. }
  9872. Emit(pnode->sxReturn.pnodeExpr, byteCodeGenerator, funcInfo, fReturnValue);
  9873. if (pnode->sxReturn.pnodeExpr->location != ByteCodeGenerator::ReturnRegister)
  9874. {
  9875. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, pnode->sxReturn.pnodeExpr->location);
  9876. }
  9877. funcInfo->GetParsedFunctionBody()->SetHasNoExplicitReturnValue(false);
  9878. }
  9879. else
  9880. {
  9881. byteCodeGenerator->Writer()->Reg1(Js::OpCode::LdUndef, ByteCodeGenerator::ReturnRegister);
  9882. }
  9883. if (funcInfo->IsClassConstructor())
  9884. {
  9885. // return expr; // becomes like below:
  9886. //
  9887. // if (IsObject(expr)) {
  9888. // return expr;
  9889. // } else if (IsBaseClassConstructor) {
  9890. // return this;
  9891. // } else if (!IsUndefined(expr)) {
  9892. // throw TypeError;
  9893. // }
  9894. Js::ByteCodeLabel returnExprLabel = byteCodeGenerator->Writer()->DefineLabel();
  9895. byteCodeGenerator->Writer()->BrReg1(Js::OpCode::BrOnObject_A, returnExprLabel, ByteCodeGenerator::ReturnRegister);
  9896. if (funcInfo->IsBaseClassConstructor())
  9897. {
  9898. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, funcInfo->thisPointerRegister);
  9899. }
  9900. else
  9901. {
  9902. Js::ByteCodeLabel returnThisLabel = byteCodeGenerator->Writer()->DefineLabel();
  9903. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::BrSrEq_A, returnThisLabel, ByteCodeGenerator::ReturnRegister, funcInfo->undefinedConstantRegister);
  9904. byteCodeGenerator->Writer()->W1(Js::OpCode::RuntimeTypeError, SCODE_CODE(JSERR_ClassDerivedConstructorInvalidReturnType));
  9905. byteCodeGenerator->Writer()->MarkLabel(returnThisLabel);
  9906. byteCodeGenerator->EmitClassConstructorEndCode(funcInfo);
  9907. }
  9908. byteCodeGenerator->Writer()->MarkLabel(returnExprLabel);
  9909. }
  9910. if (pnode->sxStmt.grfnop & fnopCleanup)
  9911. {
  9912. EmitJumpCleanup(pnode, nullptr, byteCodeGenerator, funcInfo);
  9913. }
  9914. byteCodeGenerator->Writer()->Br(funcInfo->singleExit);
  9915. byteCodeGenerator->EndStatement(pnode);
  9916. break;
  9917. case knopLabel:
  9918. break;
  9919. // PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  9920. case knopBlock:
  9921. if (pnode->sxBlock.pnodeStmt != nullptr)
  9922. {
  9923. EmitBlock(pnode, byteCodeGenerator, funcInfo, fReturnValue);
  9924. if (pnode->emitLabels)
  9925. {
  9926. byteCodeGenerator->Writer()->MarkLabel(pnode->sxStmt.breakLabel);
  9927. }
  9928. }
  9929. break;
  9930. // PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  9931. case knopWith:
  9932. {
  9933. Assert(pnode->sxWith.pnodeObj != nullptr);
  9934. byteCodeGenerator->StartStatement(pnode);
  9935. // Copy the with object to a temp register (the location assigned to pnode) so that if the with object
  9936. // is overwritten in the body, the lookups are not affected.
  9937. funcInfo->AcquireLoc(pnode);
  9938. Emit(pnode->sxWith.pnodeObj, byteCodeGenerator, funcInfo, false);
  9939. Js::RegSlot regVal = (byteCodeGenerator->GetScriptContext()->GetConfig()->IsES6UnscopablesEnabled()) ? funcInfo->AcquireTmpRegister() : pnode->location;
  9940. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Conv_Obj, regVal, pnode->sxWith.pnodeObj->location);
  9941. if (byteCodeGenerator->GetScriptContext()->GetConfig()->IsES6UnscopablesEnabled())
  9942. {
  9943. byteCodeGenerator->Writer()->Reg2(Js::OpCode::NewWithObject, pnode->location, regVal);
  9944. }
  9945. byteCodeGenerator->EndStatement(pnode);
  9946. #ifdef PERF_HINT
  9947. if (PHASE_TRACE1(Js::PerfHintPhase))
  9948. {
  9949. WritePerfHint(PerfHints::HasWithBlock, funcInfo->byteCodeFunction->GetFunctionBody(), byteCodeGenerator->Writer()->GetCurrentOffset() - 1);
  9950. }
  9951. #endif
  9952. if (pnode->sxWith.pnodeBody != nullptr)
  9953. {
  9954. Scope *scope = pnode->sxWith.scope;
  9955. scope->SetLocation(pnode->location);
  9956. byteCodeGenerator->PushScope(scope);
  9957. Js::DebuggerScope *debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnode, Js::DiagExtraScopesType::DiagWithScope, regVal);
  9958. if (byteCodeGenerator->ShouldTrackDebuggerMetadata())
  9959. {
  9960. byteCodeGenerator->Writer()->AddPropertyToDebuggerScope(debuggerScope, regVal, Js::Constants::NoProperty, /*shouldConsumeRegister*/ true, Js::DebuggerScopePropertyFlags_WithObject);
  9961. }
  9962. Emit(pnode->sxWith.pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  9963. funcInfo->ReleaseLoc(pnode->sxWith.pnodeBody);
  9964. byteCodeGenerator->PopScope();
  9965. byteCodeGenerator->RecordEndScopeObject(pnode);
  9966. }
  9967. if (pnode->emitLabels)
  9968. {
  9969. byteCodeGenerator->Writer()->MarkLabel(pnode->sxStmt.breakLabel);
  9970. }
  9971. if (byteCodeGenerator->GetScriptContext()->GetConfig()->IsES6UnscopablesEnabled())
  9972. {
  9973. funcInfo->ReleaseTmpRegister(regVal);
  9974. }
  9975. funcInfo->ReleaseLoc(pnode->sxWith.pnodeObj);
  9976. break;
  9977. }
  9978. // PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  9979. case knopBreak:
  9980. Assert(pnode->sxJump.pnodeTarget->emitLabels);
  9981. byteCodeGenerator->StartStatement(pnode);
  9982. if (pnode->sxStmt.grfnop & fnopCleanup)
  9983. {
  9984. EmitJumpCleanup(pnode, pnode->sxJump.pnodeTarget, byteCodeGenerator, funcInfo);
  9985. }
  9986. byteCodeGenerator->Writer()->Br(pnode->sxJump.pnodeTarget->sxStmt.breakLabel);
  9987. if (pnode->emitLabels)
  9988. {
  9989. byteCodeGenerator->Writer()->MarkLabel(pnode->sxStmt.breakLabel);
  9990. }
  9991. byteCodeGenerator->EndStatement(pnode);
  9992. break;
  9993. case knopContinue:
  9994. Assert(pnode->sxJump.pnodeTarget->emitLabels);
  9995. byteCodeGenerator->StartStatement(pnode);
  9996. if (pnode->sxStmt.grfnop & fnopCleanup)
  9997. {
  9998. EmitJumpCleanup(pnode, pnode->sxJump.pnodeTarget, byteCodeGenerator, funcInfo);
  9999. }
  10000. byteCodeGenerator->Writer()->Br(pnode->sxJump.pnodeTarget->sxStmt.continueLabel);
  10001. byteCodeGenerator->EndStatement(pnode);
  10002. break;
  10003. // PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  10004. case knopSwitch:
  10005. {
  10006. BOOL fHasDefault = false;
  10007. Assert(pnode->sxSwitch.pnodeVal != nullptr);
  10008. byteCodeGenerator->StartStatement(pnode);
  10009. Emit(pnode->sxSwitch.pnodeVal, byteCodeGenerator, funcInfo, false);
  10010. Js::RegSlot regVal = funcInfo->AcquireTmpRegister();
  10011. byteCodeGenerator->Writer()->Reg2(Js::OpCode::BeginSwitch, regVal, pnode->sxSwitch.pnodeVal->location);
  10012. BeginEmitBlock(pnode->sxSwitch.pnodeBlock, byteCodeGenerator, funcInfo);
  10013. byteCodeGenerator->EndStatement(pnode);
  10014. // TODO: if all cases are compile-time constants, emit a switch statement in the byte
  10015. // code so the BE can optimize it.
  10016. ParseNode *pnodeCase;
  10017. for (pnodeCase = pnode->sxSwitch.pnodeCases; pnodeCase; pnodeCase = pnodeCase->sxCase.pnodeNext)
  10018. {
  10019. // Jump to the first case body if this one doesn't match. Make sure any side-effects of the case
  10020. // expression take place regardless.
  10021. pnodeCase->sxCase.labelCase = byteCodeGenerator->Writer()->DefineLabel();
  10022. if (pnodeCase == pnode->sxSwitch.pnodeDefault)
  10023. {
  10024. fHasDefault = true;
  10025. continue;
  10026. }
  10027. Emit(pnodeCase->sxCase.pnodeExpr, byteCodeGenerator, funcInfo, false);
  10028. byteCodeGenerator->Writer()->BrReg2(
  10029. Js::OpCode::Case, pnodeCase->sxCase.labelCase, regVal, pnodeCase->sxCase.pnodeExpr->location);
  10030. funcInfo->ReleaseLoc(pnodeCase->sxCase.pnodeExpr);
  10031. }
  10032. // No explicit case value matches. Jump to the default arm (if any) or break out altogether.
  10033. if (fHasDefault)
  10034. {
  10035. byteCodeGenerator->Writer()->Br(Js::OpCode::EndSwitch, pnode->sxSwitch.pnodeDefault->sxCase.labelCase);
  10036. }
  10037. else
  10038. {
  10039. if (!pnode->emitLabels)
  10040. {
  10041. pnode->sxStmt.breakLabel = byteCodeGenerator->Writer()->DefineLabel();
  10042. }
  10043. byteCodeGenerator->Writer()->Br(Js::OpCode::EndSwitch, pnode->sxStmt.breakLabel);
  10044. }
  10045. // Now emit the case arms to which we jump on matching a case value.
  10046. for (pnodeCase = pnode->sxSwitch.pnodeCases; pnodeCase; pnodeCase = pnodeCase->sxCase.pnodeNext)
  10047. {
  10048. byteCodeGenerator->Writer()->MarkLabel(pnodeCase->sxCase.labelCase);
  10049. Emit(pnodeCase->sxCase.pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10050. funcInfo->ReleaseLoc(pnodeCase->sxCase.pnodeBody);
  10051. }
  10052. EndEmitBlock(pnode->sxSwitch.pnodeBlock, byteCodeGenerator, funcInfo);
  10053. funcInfo->ReleaseTmpRegister(regVal);
  10054. funcInfo->ReleaseLoc(pnode->sxSwitch.pnodeVal);
  10055. if (!fHasDefault || pnode->emitLabels)
  10056. {
  10057. byteCodeGenerator->Writer()->MarkLabel(pnode->sxStmt.breakLabel);
  10058. }
  10059. break;
  10060. }
  10061. case knopTryCatch:
  10062. {
  10063. Js::ByteCodeLabel catchLabel = (Js::ByteCodeLabel) - 1;
  10064. ParseNode *pnodeTry = pnode->sxTryCatch.pnodeTry;
  10065. Assert(pnodeTry);
  10066. ParseNode *pnodeCatch = pnode->sxTryCatch.pnodeCatch;
  10067. Assert(pnodeCatch);
  10068. catchLabel = byteCodeGenerator->Writer()->DefineLabel();
  10069. // Note: try uses OpCode::Leave which causes a return to parent interpreter thunk,
  10070. // same for catch block. Thus record cross interpreter frame entry/exit records for them.
  10071. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ true);
  10072. byteCodeGenerator->Writer()->Br(Js::OpCode::TryCatch, catchLabel);
  10073. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryCatch, catchLabel);
  10074. if (funcInfo->byteCodeFunction->IsCoroutine())
  10075. {
  10076. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  10077. }
  10078. Emit(pnodeTry->sxTry.pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10079. funcInfo->ReleaseLoc(pnodeTry->sxTry.pnodeBody);
  10080. if (funcInfo->byteCodeFunction->IsCoroutine())
  10081. {
  10082. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  10083. }
  10084. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(/* isEnterBlock = */ false);
  10085. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  10086. byteCodeGenerator->Writer()->Br(pnode->sxStmt.breakLabel);
  10087. byteCodeGenerator->Writer()->MarkLabel(catchLabel);
  10088. Assert(pnodeCatch->sxCatch.pnodeParam);
  10089. ParseNode *pnodeObj = pnodeCatch->sxCatch.pnodeParam;
  10090. Js::RegSlot location;
  10091. bool acquiredTempLocation = false;
  10092. Js::DebuggerScope *debuggerScope = nullptr;
  10093. Js::DebuggerScopePropertyFlags debuggerPropertyFlags = Js::DebuggerScopePropertyFlags_CatchObject;
  10094. bool isPattern = pnodeObj->nop == knopParamPattern;
  10095. if (isPattern)
  10096. {
  10097. location = pnodeObj->sxParamPattern.location;
  10098. }
  10099. else
  10100. {
  10101. location = pnodeObj->sxPid.sym->GetLocation();
  10102. }
  10103. if (location == Js::Constants::NoRegister)
  10104. {
  10105. location = funcInfo->AcquireLoc(pnodeObj);
  10106. acquiredTempLocation = true;
  10107. }
  10108. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Catch, location);
  10109. Scope *scope = pnodeCatch->sxCatch.scope;
  10110. byteCodeGenerator->PushScope(scope);
  10111. if (scope->GetMustInstantiate())
  10112. {
  10113. Assert(scope->GetLocation() == Js::Constants::NoRegister);
  10114. if (scope->GetIsObject())
  10115. {
  10116. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnode, Js::DiagCatchScopeInObject, funcInfo->InnerScopeToRegSlot(scope));
  10117. byteCodeGenerator->Writer()->Unsigned1(Js::OpCode::NewPseudoScope, scope->GetInnerScopeIndex());
  10118. }
  10119. else
  10120. {
  10121. int index = Js::DebuggerScope::InvalidScopeIndex;
  10122. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnode, Js::DiagCatchScopeInSlot, funcInfo->InnerScopeToRegSlot(scope), &index);
  10123. byteCodeGenerator->Writer()->Num3(Js::OpCode::NewInnerScopeSlots, scope->GetInnerScopeIndex(), scope->GetScopeSlotCount() + Js::ScopeSlots::FirstSlotIndex, index);
  10124. }
  10125. }
  10126. else
  10127. {
  10128. debuggerScope = byteCodeGenerator->RecordStartScopeObject(pnode, Js::DiagCatchScopeDirect, location);
  10129. }
  10130. auto ParamTrackAndInitialization = [&](Symbol *sym, bool initializeParam, Js::RegSlot location)
  10131. {
  10132. if (sym->IsInSlot(funcInfo))
  10133. {
  10134. Assert(scope->GetMustInstantiate());
  10135. if (scope->GetIsObject())
  10136. {
  10137. Js::OpCode op = (sym->GetDecl()->nop == knopLetDecl) ? Js::OpCode::InitUndeclLetFld :
  10138. byteCodeGenerator->GetInitFldOp(scope, scope->GetLocation(), funcInfo, false);
  10139. Js::PropertyId propertyId = sym->EnsurePosition(byteCodeGenerator);
  10140. uint cacheId = funcInfo->FindOrAddInlineCacheId(funcInfo->InnerScopeToRegSlot(scope), propertyId, false, true);
  10141. byteCodeGenerator->Writer()->ElementPIndexed(op, location, scope->GetInnerScopeIndex(), cacheId);
  10142. byteCodeGenerator->TrackActivationObjectPropertyForDebugger(debuggerScope, sym, debuggerPropertyFlags);
  10143. }
  10144. else
  10145. {
  10146. byteCodeGenerator->TrackSlotArrayPropertyForDebugger(debuggerScope, sym, sym->EnsurePosition(byteCodeGenerator), debuggerPropertyFlags);
  10147. if (initializeParam)
  10148. {
  10149. byteCodeGenerator->EmitLocalPropInit(location, sym, funcInfo);
  10150. }
  10151. else
  10152. {
  10153. Js::RegSlot tmpReg = funcInfo->AcquireTmpRegister();
  10154. byteCodeGenerator->Writer()->Reg1(Js::OpCode::InitUndecl, tmpReg);
  10155. byteCodeGenerator->EmitLocalPropInit(tmpReg, sym, funcInfo);
  10156. funcInfo->ReleaseTmpRegister(tmpReg);
  10157. }
  10158. }
  10159. }
  10160. else
  10161. {
  10162. byteCodeGenerator->TrackRegisterPropertyForDebugger(debuggerScope, sym, funcInfo, debuggerPropertyFlags);
  10163. if (initializeParam)
  10164. {
  10165. byteCodeGenerator->EmitLocalPropInit(location, sym, funcInfo);
  10166. }
  10167. else
  10168. {
  10169. byteCodeGenerator->Writer()->Reg1(Js::OpCode::InitUndecl, location);
  10170. }
  10171. }
  10172. };
  10173. if (isPattern)
  10174. {
  10175. Parser::MapBindIdentifier(pnodeObj->sxParamPattern.pnode1, [&](ParseNodePtr item)
  10176. {
  10177. Js::RegSlot itemLocation = item->sxVar.sym->GetLocation();
  10178. if (itemLocation == Js::Constants::NoRegister)
  10179. {
  10180. // The var has no assigned register, meaning it's captured, so we have no reg to write to.
  10181. // Emit the designated return reg in the byte code to avoid asserting on bad register.
  10182. itemLocation = ByteCodeGenerator::ReturnRegister;
  10183. }
  10184. ParamTrackAndInitialization(item->sxVar.sym, false /*initializeParam*/, itemLocation);
  10185. });
  10186. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10187. // Now emitting bytecode for destructuring pattern
  10188. byteCodeGenerator->StartStatement(pnodeCatch);
  10189. ParseNodePtr pnode1 = pnodeObj->sxParamPattern.pnode1;
  10190. Assert(pnode1->IsPattern());
  10191. EmitAssignment(nullptr, pnode1, location, byteCodeGenerator, funcInfo);
  10192. byteCodeGenerator->EndStatement(pnodeCatch);
  10193. }
  10194. else
  10195. {
  10196. ParamTrackAndInitialization(pnodeObj->sxPid.sym, true /*initializeParam*/, location);
  10197. if (scope->GetMustInstantiate())
  10198. {
  10199. pnodeObj->sxPid.sym->SetIsGlobalCatch(true);
  10200. }
  10201. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10202. // Allow a debugger to stop on the 'catch (e)'
  10203. byteCodeGenerator->StartStatement(pnodeCatch);
  10204. byteCodeGenerator->Writer()->Empty(Js::OpCode::Nop);
  10205. byteCodeGenerator->EndStatement(pnodeCatch);
  10206. }
  10207. ByteCodeGenerator::TryScopeRecord tryRecForCatch(Js::OpCode::ResumeCatch, catchLabel);
  10208. if (funcInfo->byteCodeFunction->IsCoroutine())
  10209. {
  10210. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForCatch);
  10211. }
  10212. Emit(pnodeCatch->sxCatch.pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10213. if (funcInfo->byteCodeFunction->IsCoroutine())
  10214. {
  10215. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  10216. }
  10217. byteCodeGenerator->PopScope();
  10218. byteCodeGenerator->RecordEndScopeObject(pnode);
  10219. funcInfo->ReleaseLoc(pnodeCatch->sxCatch.pnodeBody);
  10220. if (acquiredTempLocation)
  10221. {
  10222. funcInfo->ReleaseLoc(pnodeObj);
  10223. }
  10224. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  10225. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  10226. byteCodeGenerator->Writer()->MarkLabel(pnode->sxStmt.breakLabel);
  10227. break;
  10228. }
  10229. case knopTryFinally:
  10230. {
  10231. Js::ByteCodeLabel finallyLabel = (Js::ByteCodeLabel) - 1;
  10232. ParseNode *pnodeTry = pnode->sxTryFinally.pnodeTry;
  10233. Assert(pnodeTry);
  10234. ParseNode *pnodeFinally = pnode->sxTryFinally.pnodeFinally;
  10235. Assert(pnodeFinally);
  10236. // If we yield from the finally block after an exception, we have to store the exception object for the future next call.
  10237. // When we yield from the Try-Finally the offset to the end of the Try block is needed for the branch instruction.
  10238. Js::RegSlot regException = Js::Constants::NoRegister;
  10239. Js::RegSlot regOffset = Js::Constants::NoRegister;
  10240. finallyLabel = byteCodeGenerator->Writer()->DefineLabel();
  10241. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10242. // [CONSIDER][aneeshd] Ideally the TryFinallyWithYield opcode needs to be used only if there is a yield expression.
  10243. // For now, if the function is generator we are using the TryFinallyWithYield.
  10244. ByteCodeGenerator::TryScopeRecord tryRecForTry(Js::OpCode::TryFinallyWithYield, finallyLabel);
  10245. if (funcInfo->byteCodeFunction->IsCoroutine())
  10246. {
  10247. regException = funcInfo->AcquireTmpRegister();
  10248. regOffset = funcInfo->AcquireTmpRegister();
  10249. byteCodeGenerator->Writer()->BrReg2(Js::OpCode::TryFinallyWithYield, finallyLabel, regException, regOffset);
  10250. tryRecForTry.reg1 = regException;
  10251. tryRecForTry.reg2 = regOffset;
  10252. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForTry);
  10253. }
  10254. else
  10255. {
  10256. byteCodeGenerator->Writer()->Br(Js::OpCode::TryFinally, finallyLabel);
  10257. }
  10258. // Increasing the stack as we will be storing the additional values when we enter try..finally.
  10259. funcInfo->StartRecordingOutArgs(1);
  10260. Emit(pnodeTry->sxTry.pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10261. funcInfo->ReleaseLoc(pnodeTry->sxTry.pnodeBody);
  10262. if (funcInfo->byteCodeFunction->IsCoroutine())
  10263. {
  10264. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  10265. }
  10266. byteCodeGenerator->Writer()->Empty(Js::OpCode::Leave);
  10267. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  10268. // Note: although we don't use OpCode::Leave for finally block,
  10269. // OpCode::LeaveNull causes a return to parent interpreter thunk.
  10270. // This has to be on offset prior to offset of 1st statement of finally.
  10271. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(true);
  10272. byteCodeGenerator->Writer()->Br(pnode->sxStmt.breakLabel);
  10273. byteCodeGenerator->Writer()->MarkLabel(finallyLabel);
  10274. ByteCodeGenerator::TryScopeRecord tryRecForFinally(Js::OpCode::ResumeFinally, finallyLabel, regException, regOffset);
  10275. if (funcInfo->byteCodeFunction->IsCoroutine())
  10276. {
  10277. byteCodeGenerator->tryScopeRecordsList.LinkToEnd(&tryRecForFinally);
  10278. }
  10279. Emit(pnodeFinally->sxFinally.pnodeBody, byteCodeGenerator, funcInfo, fReturnValue);
  10280. funcInfo->ReleaseLoc(pnodeFinally->sxFinally.pnodeBody);
  10281. if (funcInfo->byteCodeFunction->IsCoroutine())
  10282. {
  10283. byteCodeGenerator->tryScopeRecordsList.UnlinkFromEnd();
  10284. funcInfo->ReleaseTmpRegister(regOffset);
  10285. funcInfo->ReleaseTmpRegister(regException);
  10286. }
  10287. funcInfo->EndRecordingOutArgs(1);
  10288. byteCodeGenerator->Writer()->RecordCrossFrameEntryExitRecord(false);
  10289. byteCodeGenerator->Writer()->Empty(Js::OpCode::LeaveNull);
  10290. byteCodeGenerator->Writer()->MarkLabel(pnode->sxStmt.breakLabel);
  10291. break;
  10292. }
  10293. case knopThrow:
  10294. byteCodeGenerator->StartStatement(pnode);
  10295. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  10296. byteCodeGenerator->Writer()->Reg1(Js::OpCode::Throw, pnode->sxUni.pnode1->location);
  10297. funcInfo->ReleaseLoc(pnode->sxUni.pnode1);
  10298. byteCodeGenerator->EndStatement(pnode);
  10299. break;
  10300. case knopYieldLeaf:
  10301. byteCodeGenerator->StartStatement(pnode);
  10302. funcInfo->AcquireLoc(pnode);
  10303. EmitYield(funcInfo->undefinedConstantRegister, pnode->location, byteCodeGenerator, funcInfo);
  10304. byteCodeGenerator->EndStatement(pnode);
  10305. break;
  10306. case knopAwait:
  10307. case knopYield:
  10308. byteCodeGenerator->StartStatement(pnode);
  10309. funcInfo->AcquireLoc(pnode);
  10310. Emit(pnode->sxUni.pnode1, byteCodeGenerator, funcInfo, false);
  10311. EmitYield(pnode->sxUni.pnode1->location, pnode->location, byteCodeGenerator, funcInfo);
  10312. funcInfo->ReleaseLoc(pnode->sxUni.pnode1);
  10313. byteCodeGenerator->EndStatement(pnode);
  10314. break;
  10315. case knopYieldStar:
  10316. byteCodeGenerator->StartStatement(pnode);
  10317. EmitYieldStar(pnode, byteCodeGenerator, funcInfo);
  10318. byteCodeGenerator->EndStatement(pnode);
  10319. break;
  10320. case knopExportDefault:
  10321. Emit(pnode->sxExportDefault.pnodeExpr, byteCodeGenerator, funcInfo, false);
  10322. byteCodeGenerator->EmitAssignmentToDefaultModuleExport(pnode->sxExportDefault.pnodeExpr, funcInfo);
  10323. funcInfo->ReleaseLoc(pnode->sxExportDefault.pnodeExpr);
  10324. pnode = pnode->sxExportDefault.pnodeExpr;
  10325. break;
  10326. default:
  10327. AssertMsg(0, "emit unhandled pnode op");
  10328. break;
  10329. }
  10330. if (fReturnValue && IsExpressionStatement(pnode, byteCodeGenerator->GetScriptContext()))
  10331. {
  10332. // If this statement may produce the global function's return value, copy its result to the return register.
  10333. // fReturnValue implies global function, which implies that "return" is a parse error.
  10334. Assert(funcInfo->IsGlobalFunction());
  10335. Assert(pnode->nop != knopReturn);
  10336. byteCodeGenerator->Writer()->Reg2(Js::OpCode::Ld_A, ByteCodeGenerator::ReturnRegister, pnode->location);
  10337. }
  10338. }