InterpreterStackFrame.cpp 357 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft Corporation and contributors. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "RuntimeLanguagePch.h"
  6. #include "RuntimeMathPch.h"
  7. #include "EHBailoutData.h"
  8. #include "Library/JavascriptRegularExpression.h"
  9. #if DBG_DUMP
  10. #include "ByteCode/OpCodeUtilAsmJs.h"
  11. #endif
  12. #include "Language/InterpreterStackFrame.h"
  13. #include "Library/JavascriptGeneratorFunction.h"
  14. #include "Library/ForInObjectEnumerator.h"
  15. #include "Library/AtomicsOperations.h"
  16. #include "../../WasmReader/WasmParseTree.h"
  17. ///----------------------------------------------------------------------------
  18. ///
  19. /// macros PROCESS_INtoOUT
  20. ///
  21. /// This set of macros defines standard patterns for processing OpCodes in
  22. /// RcInterpreter::Run(). Each macro is named for "in" - "out":
  23. /// - A: Var
  24. /// - I: Integer
  25. /// - R: Double
  26. /// - X: Nothing
  27. ///
  28. /// Examples:
  29. /// - "A2toA1" reads two registers, each storing an Var, and writes a single
  30. /// register with a new Var.
  31. /// - "A1I1toA2" reads two registers, first an Var and second an Int32, then
  32. /// writes two Var registers.
  33. ///
  34. /// Although these could use lookup tables to standard OpLayout types, this
  35. /// additional indirection would slow the main interpreter loop further by
  36. /// preventing the main 'switch' statement from using the OpCode to become a
  37. /// direct local-function jump.
  38. ///----------------------------------------------------------------------------
  39. #define PROCESS_FALLTHROUGH(name, func) \
  40. case OpCode::name:
  41. #define PROCESS_FALLTHROUGH_COMMON(name, func, suffix) \
  42. case OpCode::name:
  43. #define PROCESS_READ_LAYOUT(name, layout, suffix) \
  44. CompileAssert(OpCodeInfo<OpCode::name>::Layout == OpLayoutType::layout); \
  45. const unaligned OpLayout##layout##suffix * playout = m_reader.layout##suffix(ip); \
  46. Assert((playout != nullptr) == (Js::OpLayoutType::##layout != Js::OpLayoutType::Empty)); // Make sure playout is used
  47. #define PROCESS_NOP_COMMON(name, layout, suffix) \
  48. case OpCode::name: \
  49. { \
  50. PROCESS_READ_LAYOUT(name, layout, suffix); \
  51. break; \
  52. }
  53. #define PROCESS_NOP(name, layout) PROCESS_NOP_COMMON(name, layout,)
  54. #define PROCESS_CUSTOM_COMMON(name, func, layout, suffix) \
  55. case OpCode::name: \
  56. { \
  57. PROCESS_READ_LAYOUT(name, layout, suffix); \
  58. func(playout); \
  59. break; \
  60. }
  61. #define PROCESS_CUSTOM(name, func, layout) PROCESS_CUSTOM_COMMON(name, func, layout,)
  62. #define PROCESS_CUSTOM_L_COMMON(name, func, layout, regslot, suffix) \
  63. case OpCode::name: \
  64. { \
  65. PROCESS_READ_LAYOUT(name, layout, suffix); \
  66. func(playout); \
  67. break; \
  68. }
  69. #define PROCESS_CUSTOM_L(name, func, layout, regslot) PROCESS_CUSTOM_L_COMMON(name, func, layout, regslot,)
  70. #define PROCESS_CUSTOM_L_Arg_COMMON(name, func, suffix) PROCESS_CUSTOM_L_COMMON(name, func, Arg, Arg, suffix)
  71. #define PROCESS_CUSTOM_L_Arg2_COMMON(name, func, layout, suffix) PROCESS_CUSTOM_L_COMMON(name, func, layout, Arg, suffix)
  72. #define PROCESS_CUSTOM_L_Arg(name, func) PROCESS_CUSTOM_L_COMMON(name, func, Arg, Arg,)
  73. #define PROCESS_CUSTOM_ArgNoSrc_COMMON(name, func, suffix) PROCESS_CUSTOM_COMMON(name, func, ArgNoSrc, suffix)
  74. #define PROCESS_CUSTOM_ArgNoSrc(name, func) PROCESS_CUSTOM_COMMON(name, func, ArgNoSrc,)
  75. #define PROCESS_CUSTOM_L_R0_COMMON(name, func, layout, suffix) PROCESS_CUSTOM_L_COMMON(name, func, layout, R0, suffix)
  76. #define PROCESS_CUSTOM_L_R0(name, func, layout) PROCESS_CUSTOM_L_COMMON(name, func, layout, R0,)
  77. #define PROCESS_CUSTOM_L_Value_COMMON(name, func, layout, suffix) PROCESS_CUSTOM_L_COMMON(name, func, layout, Value, suffix)
  78. #define PROCESS_CUSTOM_L_Value(name, func, layout) PROCESS_CUSTOM_L_COMMON(name, func, layout, Value,)
  79. #define PROCESS_TRY(name, func) \
  80. case OpCode::name: \
  81. { \
  82. PROCESS_READ_LAYOUT(name, Br,); \
  83. func(playout); \
  84. ip = m_reader.GetIP(); \
  85. break; \
  86. }
  87. #define PROCESS_EMPTY(name, func) \
  88. case OpCode::name: \
  89. { \
  90. PROCESS_READ_LAYOUT(name, Empty, ); \
  91. func(); \
  92. ip = m_reader.GetIP(); \
  93. break; \
  94. }
  95. #define PROCESS_TRYBR2_COMMON(name, func, suffix) \
  96. case OpCode::name: \
  97. { \
  98. PROCESS_READ_LAYOUT(name, BrReg2, suffix); \
  99. func((const byte*)(playout + 1), playout->RelativeJumpOffset, playout->R1, playout->R2); \
  100. ip = m_reader.GetIP(); \
  101. break; \
  102. }
  103. #define PROCESS_CALL_COMMON(name, func, layout, suffix) \
  104. case OpCode::name: \
  105. { \
  106. PROCESS_READ_LAYOUT(name, layout, suffix); \
  107. func(playout); \
  108. break; \
  109. }
  110. #define PROCESS_CALL(name, func, layout) PROCESS_CALL_COMMON(name, func, layout,)
  111. #define PROCESS_CALL_FLAGS_None_COMMON(name, func, layout, suffix) PROCESS_CALL_COMMON(name, func, layout, suffix)
  112. #define PROCESS_CALL_FLAGS_Value_COMMON(name, func, layout, suffix) PROCESS_CALL_COMMON(name, func, layout, suffix)
  113. #define PROCESS_A1toXX_ALLOW_STACK_COMMON(name, func, suffix) \
  114. case OpCode::name: \
  115. { \
  116. PROCESS_READ_LAYOUT(name, Reg1, suffix); \
  117. func(GetRegAllowStackVar(playout->R0)); \
  118. break; \
  119. }
  120. #define PROCESS_A1toXX_COMMON(name, func, suffix) \
  121. case OpCode::name: \
  122. { \
  123. PROCESS_READ_LAYOUT(name, Reg1, suffix); \
  124. func(GetReg(playout->R0)); \
  125. break; \
  126. }
  127. #define PROCESS_A1toXX(name, func) PROCESS_A1toXX_COMMON(name, func,)
  128. #define PROCESS_A1toXXMem_COMMON(name, func, suffix) \
  129. case OpCode::name: \
  130. { \
  131. PROCESS_READ_LAYOUT(name, Reg1, suffix); \
  132. func(GetReg(playout->R0), GetScriptContext()); \
  133. break; \
  134. }
  135. #define PROCESS_A1toXXMem(name, func) PROCESS_A1toXXMem_COMMON(name, func,)
  136. #define PROCESS_A1toXXMemNonVar_COMMON(name, func, type, suffix) \
  137. case OpCode::name: \
  138. { \
  139. PROCESS_READ_LAYOUT(name, Reg1, suffix); \
  140. func((type)GetNonVarReg(playout->R0), GetScriptContext()); \
  141. break; \
  142. }
  143. #define PROCESS_A1toXXMemNonVar(name, func, type) PROCESS_A1toXXMemNonVar_COMMON(name, func, type,)
  144. #define PROCESS_XXtoA1_COMMON(name, func, suffix) \
  145. case OpCode::name: \
  146. { \
  147. PROCESS_READ_LAYOUT(name, Reg1, suffix); \
  148. SetReg(playout->R0, \
  149. func()); \
  150. break; \
  151. }
  152. #define PROCESS_XXtoA1(name, func) PROCESS_XXtoA1_COMMON(name, func,)
  153. #define PROCESS_XXtoA1NonVar_COMMON(name, func, suffix) \
  154. case OpCode::name: \
  155. { \
  156. PROCESS_READ_LAYOUT(name, Reg1, suffix); \
  157. SetNonVarReg(playout->R0, \
  158. func()); \
  159. break; \
  160. }
  161. #define PROCESS_XXtoA1NonVar(name, func) PROCESS_XXtoA1NonVar_COMMON(name, func,)
  162. #define PROCESS_XXtoA1Mem_COMMON(name, func, suffix) \
  163. case OpCode::name: \
  164. { \
  165. PROCESS_READ_LAYOUT(name, Reg1, suffix); \
  166. SetReg(playout->R0, \
  167. func(GetScriptContext())); \
  168. break; \
  169. }
  170. #define PROCESS_XXtoA1Mem(name, func) PROCESS_XXtoA1Mem_COMMON(name, func,)
  171. #define PROCESS_A1toA1_ALLOW_STACK_COMMON(name, func, suffix) \
  172. case OpCode::name: \
  173. { \
  174. PROCESS_READ_LAYOUT(name, Reg2, suffix); \
  175. SetRegAllowStackVar(playout->R0, \
  176. func(GetRegAllowStackVar(playout->R1))); \
  177. break; \
  178. }
  179. #define PROCESS_A1toA1_ALLOW_STACK(name, func) PROCESS_A1toA1_ALLOW_STACK_COMMON(name, func,)
  180. #define PROCESS_A1toA1_COMMON(name, func, suffix) \
  181. case OpCode::name: \
  182. { \
  183. PROCESS_READ_LAYOUT(name, Reg2, suffix); \
  184. SetReg(playout->R0, \
  185. func(GetReg(playout->R1))); \
  186. break; \
  187. }
  188. #define PROCESS_A1toA1(name, func) PROCESS_A1toA1_COMMON(name, func,)
  189. #define PROCESS_A1toA1Profiled_COMMON(name, func, suffix) \
  190. case OpCode::name: \
  191. { \
  192. PROCESS_READ_LAYOUT(name, ProfiledReg2, suffix); \
  193. SetReg(playout->R0, \
  194. func(GetReg(playout->R1), playout->profileId)); \
  195. break; \
  196. }
  197. #define PROCESS_A1toA1Profiled(name, func) PROCESS_A1toA1Profiled_COMMON(name, func,)
  198. #define PROCESS_A1toA1CallNoArg_COMMON(name, func, layout, suffix) \
  199. case OpCode::name: \
  200. { \
  201. PROCESS_READ_LAYOUT(name, layout, suffix); \
  202. SetReg(playout->R0, \
  203. func(playout)); \
  204. break; \
  205. }
  206. #define PROCESS_A1toA1CallNoArg(name, func, layout) PROCESS_A1toA1CallNoArg_COMMON(name, func, layout,)
  207. #define PROCESS_A1toA1Mem_COMMON(name, func, suffix) \
  208. case OpCode::name: \
  209. { \
  210. PROCESS_READ_LAYOUT(name, Reg2, suffix); \
  211. SetReg(playout->R0, \
  212. func(GetReg(playout->R1),GetScriptContext())); \
  213. break; \
  214. }
  215. #define PROCESS_A1toA1Mem(name, func) PROCESS_A1toA1Mem_COMMON(name, func,)
  216. #define PROCESS_A1toA1NonVar_COMMON(name, func, suffix) \
  217. case OpCode::name: \
  218. { \
  219. PROCESS_READ_LAYOUT(name, Reg2, suffix); \
  220. SetNonVarReg(playout->R0, \
  221. func(GetNonVarReg(playout->R1))); \
  222. break; \
  223. }
  224. #define PROCESS_A1toA1NonVar(name, func) PROCESS_A1toA1NonVar_COMMON(name, func,)
  225. #define PROCESS_A1toA1MemNonVar_COMMON(name, func, suffix) \
  226. case OpCode::name: \
  227. { \
  228. PROCESS_READ_LAYOUT(name, Reg2, suffix); \
  229. SetNonVarReg(playout->R0, \
  230. func(GetNonVarReg(playout->R1),GetScriptContext())); \
  231. break; \
  232. }
  233. #define PROCESS_A1toA1MemNonVar(name, func) PROCESS_A1toA1MemNonVar_COMMON(name, func,)
  234. #define PROCESS_INNERtoA1_COMMON(name, func, suffix) \
  235. case OpCode::name: \
  236. { \
  237. PROCESS_READ_LAYOUT(name, Reg1Unsigned1, suffix); \
  238. SetReg(playout->R0, InnerScopeFromIndex(playout->C1)); \
  239. break; \
  240. }
  241. #define PROCESS_INNERtoA1(name, fun) PROCESS_INNERtoA1_COMMON(name, func,)
  242. #define PROCESS_U1toINNERMemNonVar_COMMON(name, func, suffix) \
  243. case OpCode::name: \
  244. { \
  245. PROCESS_READ_LAYOUT(name, Unsigned1, suffix); \
  246. SetInnerScopeFromIndex(playout->C1, func(GetScriptContext())); \
  247. break; \
  248. }
  249. #define PROCESS_U1toINNERMemNonVar(name, func) PROCESS_U1toINNERMemNonVar_COMMON(name, func,)
  250. #define PROCESS_XXINNERtoA1MemNonVar_COMMON(name, func, suffix) \
  251. case OpCode::name: \
  252. { \
  253. PROCESS_READ_LAYOUT(name, Reg1Unsigned1, suffix); \
  254. SetNonVarReg(playout->R0, \
  255. func(InnerScopeFromIndex(playout->C1), GetScriptContext())); \
  256. break; \
  257. }
  258. #define PROCESS_XXINNERtoA1MemNonVar(name, func) PROCESS_XXINNERtoA1MemNonVar_COMMON(name, func,)
  259. #define PROCESS_A1INNERtoA1MemNonVar_COMMON(name, func, suffix) \
  260. case OpCode::name: \
  261. { \
  262. PROCESS_READ_LAYOUT(name, Reg2Int1, suffix); \
  263. SetNonVarReg(playout->R0, \
  264. func(InnerScopeFromIndex(playout->C1), GetNonVarReg(playout->R1), GetScriptContext())); \
  265. break; \
  266. }
  267. #define PROCESS_A1LOCALtoA1MemNonVar(name, func) PROCESS_A1LOCALtoA1MemNonVar_COMMON(name, func,)
  268. #define PROCESS_LOCALI1toA1_COMMON(name, func, suffix) \
  269. case OpCode::name: \
  270. { \
  271. PROCESS_READ_LAYOUT(name, Reg1Unsigned1, suffix); \
  272. SetReg(playout->R0, \
  273. func(this->localClosure, playout->C1)); \
  274. break; \
  275. }
  276. #define PROCESS_LOCALI1toA1(name, func) PROCESS_LOCALI1toA1_COMMON(name, func,)
  277. #define PROCESS_A1I1toA1_COMMON(name, func, suffix) \
  278. case OpCode::name: \
  279. { \
  280. PROCESS_READ_LAYOUT(name, Reg2Int1, suffix); \
  281. SetReg(playout->R0, \
  282. func(GetReg(playout->R1), playout->C1)); \
  283. break; \
  284. }
  285. #define PROCESS_A1I1toA1(name, func) PROCESS_A1I1toA1_COMMON(name, func,)
  286. #define PROCESS_A1I1toA1Mem_COMMON(name, func, suffix) \
  287. case OpCode::name: \
  288. { \
  289. PROCESS_READ_LAYOUT(name, Reg2Int1, suffix); \
  290. SetReg(playout->R0, \
  291. func(GetReg(playout->R1), playout->C1, GetScriptContext())); \
  292. break; \
  293. }
  294. #define PROCESS_A1I1toA1Mem(name, func) PROCESS_A1I1toA1Mem_COMMON(name, func,)
  295. #define PROCESS_RegextoA1_COMMON(name, func, suffix) \
  296. case OpCode::name: \
  297. { \
  298. PROCESS_READ_LAYOUT(name, Reg1Unsigned1, suffix); \
  299. SetReg(playout->R0, \
  300. func(this->m_functionBody->GetLiteralRegex(playout->C1), GetScriptContext())); \
  301. break; \
  302. }
  303. #define PROCESS_RegextoA1(name, func) PROCESS_RegextoA1_COMMON(name, func,)
  304. #define PROCESS_A2toXX_COMMON(name, func, suffix) \
  305. case OpCode::name: \
  306. { \
  307. PROCESS_READ_LAYOUT(name, Reg2, suffix); \
  308. func(GetReg(playout->R0), GetReg(playout->R1)); \
  309. break; \
  310. }
  311. #define PROCESS_A2toXX(name, func) PROCESS_A2toXX_COMMON(name, func,)
  312. #define PROCESS_A2toXXMemNonVar_COMMON(name, func, suffix) \
  313. case OpCode::name: \
  314. { \
  315. PROCESS_READ_LAYOUT(name, Reg2, suffix); \
  316. func(GetNonVarReg(playout->R0), GetNonVarReg(playout->R1), GetScriptContext()); \
  317. break; \
  318. }
  319. #define PROCESS_A2toXXMemNonVar(name, func) PROCESS_A2toXXMemNonVar_COMMON(name, func,)
  320. #define PROCESS_A1NonVarToA1_COMMON(name, func, suffix) \
  321. case OpCode::name: \
  322. { \
  323. PROCESS_READ_LAYOUT(name, Reg2, suffix); \
  324. SetReg(playout->R0, \
  325. func(GetNonVarReg(playout->R1))); \
  326. break; \
  327. }
  328. #define PROCESS_A2NonVarToA1Reg_COMMON(name, func, suffix) \
  329. case OpCode::name: \
  330. { \
  331. PROCESS_READ_LAYOUT(name, Reg3, suffix); \
  332. SetReg(playout->R0, \
  333. func(GetNonVarReg(playout->R1), playout->R2)); \
  334. break; \
  335. }
  336. #define PROCESS_A2toA1Mem_COMMON(name, func, suffix) \
  337. case OpCode::name: \
  338. { \
  339. PROCESS_READ_LAYOUT(name, Reg3, suffix); \
  340. SetReg(playout->R0, \
  341. func(GetReg(playout->R1), GetReg(playout->R2),GetScriptContext())); \
  342. break; \
  343. }
  344. #define PROCESS_A2toA1Mem(name, func) PROCESS_A2toA1Mem_COMMON(name, func,)
  345. #define PROCESS_A2toA1MemProfiled_COMMON(name, func, suffix) \
  346. case OpCode::name: \
  347. { \
  348. PROCESS_READ_LAYOUT(name, ProfiledReg3, suffix); \
  349. SetReg(playout->R0, \
  350. func(GetReg(playout->R1), GetReg(playout->R2),GetScriptContext(), playout->profileId)); \
  351. break; \
  352. }
  353. #define PROCESS_A2toA1MemProfiled(name, func) PROCESS_A2toA1MemProfiled_COMMON(name, func,)
  354. #define PROCESS_A2toA1NonVar_COMMON(name, func, suffix) \
  355. case OpCode::name: \
  356. { \
  357. PROCESS_READ_LAYOUT(name, Reg3, suffix); \
  358. SetNonVarReg(playout->R0, \
  359. func(GetNonVarReg(playout->R1), GetNonVarReg(playout->R2))); \
  360. break; \
  361. }
  362. #define PROCESS_A2toA1NonVar(name, func) PROCESS_A2toA1NonVar_COMMON(name, func,)
  363. #define PROCESS_A2toA1MemNonVar_COMMON(name, func, suffix) \
  364. case OpCode::name: \
  365. { \
  366. PROCESS_READ_LAYOUT(name, Reg3, suffix); \
  367. SetNonVarReg(playout->R0, \
  368. func(GetNonVarReg(playout->R1), GetNonVarReg(playout->R2),GetScriptContext())); \
  369. break; \
  370. }
  371. #define PROCESS_A2toA1MemNonVar(name, func) PROCESS_A2toA1MemNonVar_COMMON(name, func,)
  372. #define PROCESS_CMMem_COMMON(name, func, suffix) \
  373. case OpCode::name: \
  374. { \
  375. PROCESS_READ_LAYOUT(name, Reg3, suffix); \
  376. SetReg(playout->R0, \
  377. func(GetReg(playout->R1), GetReg(playout->R2), GetScriptContext()) ? JavascriptBoolean::OP_LdTrue(GetScriptContext()) : \
  378. JavascriptBoolean::OP_LdFalse(GetScriptContext())); \
  379. break; \
  380. }
  381. #define PROCESS_CMMem(name, func) PROCESS_CMMem_COMMON(name, func,)
  382. #define PROCESS_ELEM_RtU_to_XX_COMMON(name, func, suffix) \
  383. case OpCode::name: \
  384. { \
  385. PROCESS_READ_LAYOUT(name, ElementRootU, suffix); \
  386. func(playout->PropertyIdIndex); \
  387. break; \
  388. }
  389. #define PROCESS_ELEM_RtU_to_XX(name, func) PROCESS_ELEM_RtU_to_XX_COMMON(name, func,)
  390. #define PROCESS_ELEM_C2_to_XX_COMMON(name, func, suffix) \
  391. case OpCode::name: \
  392. { \
  393. PROCESS_READ_LAYOUT(name, ElementScopedC, suffix); \
  394. func(GetEnvForEvalCode(), playout->PropertyIdIndex, GetReg(playout->Value)); \
  395. break; \
  396. }
  397. #define PROCESS_ELEM_C2_to_XX(name, func) PROCESS_ELEM_C2_to_XX_COMMON(name, func,)
  398. #define PROCESS_GET_ELEM_SLOT_FB_COMMON(name, func, suffix) \
  399. case OpCode::name: \
  400. { \
  401. PROCESS_READ_LAYOUT(name, ElementSlot, suffix); \
  402. SetReg(playout->Value, \
  403. func((FrameDisplay*)GetNonVarReg(playout->Instance), this->m_functionBody->GetNestedFuncReference(playout->SlotIndex))); \
  404. break; \
  405. }
  406. #define PROCESS_GET_ELEM_SLOT_FB(name, func) PROCESS_GET_ELEM_SLOT_FB_COMMON(name, func,)
  407. #define PROCESS_GET_SLOT_FB_COMMON(name, func, suffix) \
  408. case OpCode::name: \
  409. { \
  410. PROCESS_READ_LAYOUT(name, ElementSlotI1, suffix); \
  411. SetReg(playout->Value, \
  412. func(this->GetFrameDisplayForNestedFunc(), this->m_functionBody->GetNestedFuncReference(playout->SlotIndex))); \
  413. break; \
  414. }
  415. #define PROCESS_GET_SLOT_FB(name, func) PROCESS_GET_SLOT_FB_COMMON(name, func,)
  416. #define PROCESS_GET_ELEM_IMem_COMMON(name, func, suffix) \
  417. case OpCode::name: \
  418. { \
  419. PROCESS_READ_LAYOUT(name, ElementI, suffix); \
  420. SetReg(playout->Value, \
  421. func(GetReg(playout->Instance), GetReg(playout->Element), GetScriptContext())); \
  422. break; \
  423. }
  424. #define PROCESS_GET_ELEM_IMem(name, func) PROCESS_GET_ELEM_IMem_COMMON(name, func,)
  425. #define PROCESS_GET_ELEM_IMem_Strict_COMMON(name, func, suffix) \
  426. case OpCode::name: \
  427. { \
  428. PROCESS_READ_LAYOUT(name, ElementI, suffix); \
  429. SetReg(playout->Value, \
  430. func(GetReg(playout->Instance), GetReg(playout->Element), GetScriptContext(), PropertyOperation_StrictMode)); \
  431. break; \
  432. }
  433. #define PROCESS_GET_ELEM_IMem_Strict(name, func) PROCESS_GET_ELEM_IMem_Strict_COMMON(name, func,)
  434. #define PROCESS_BR(name, func) \
  435. case OpCode::name: \
  436. { \
  437. PROCESS_READ_LAYOUT(name, Br,); \
  438. ip = func(playout); \
  439. break; \
  440. }
  441. #ifdef BYTECODE_BRANCH_ISLAND
  442. #define PROCESS_BRLONG(name, func) \
  443. case OpCode::name: \
  444. { \
  445. PROCESS_READ_LAYOUT(name, BrLong,); \
  446. ip = func(playout); \
  447. break; \
  448. }
  449. #endif
  450. #define PROCESS_BRS(name,func) \
  451. case OpCode::name: \
  452. { \
  453. PROCESS_READ_LAYOUT(name, BrS,); \
  454. if (func(playout->val,GetScriptContext())) \
  455. { \
  456. ip = m_reader.SetCurrentRelativeOffset(ip, playout->RelativeJumpOffset); \
  457. } \
  458. break; \
  459. }
  460. #define PROCESS_BRB_COMMON(name, func, suffix) \
  461. case OpCode::name: \
  462. { \
  463. PROCESS_READ_LAYOUT(name, BrReg1, suffix); \
  464. if (func(GetReg(playout->R1))) \
  465. { \
  466. ip = m_reader.SetCurrentRelativeOffset(ip, playout->RelativeJumpOffset); \
  467. } \
  468. break; \
  469. }
  470. #define PROCESS_BRB(name, func) PROCESS_BRB_COMMON(name, func,)
  471. #define PROCESS_BRB_ALLOW_STACK_COMMON(name, func, suffix) \
  472. case OpCode::name: \
  473. { \
  474. PROCESS_READ_LAYOUT(name, BrReg1, suffix); \
  475. if (func(GetRegAllowStackVar(playout->R1))) \
  476. { \
  477. ip = m_reader.SetCurrentRelativeOffset(ip, playout->RelativeJumpOffset); \
  478. } \
  479. break; \
  480. }
  481. #define PROCESS_BRB_ALLOW_STACK(name, func) PROCESS_BRB_ALLOW_STACK_COMMON(name, func,)
  482. #define PROCESS_BRBS_COMMON(name, func, suffix) \
  483. case OpCode::name: \
  484. { \
  485. PROCESS_READ_LAYOUT(name, BrReg1, suffix); \
  486. if (func(GetReg(playout->R1), GetScriptContext())) \
  487. { \
  488. ip = m_reader.SetCurrentRelativeOffset(ip, playout->RelativeJumpOffset); \
  489. } \
  490. break; \
  491. }
  492. #define PROCESS_BRBS(name, func) PROCESS_BRBS_COMMON(name, func,)
  493. #define PROCESS_BRBReturnP1toA1_COMMON(name, func, suffix) \
  494. case OpCode::name: \
  495. { \
  496. PROCESS_READ_LAYOUT(name, BrReg1Unsigned1, suffix); \
  497. SetReg(playout->R1, func(GetForInEnumerator(playout->C2))); \
  498. if (!GetReg(playout->R1)) \
  499. { \
  500. ip = m_reader.SetCurrentRelativeOffset(ip, playout->RelativeJumpOffset); \
  501. } \
  502. break; \
  503. }
  504. #define PROCESS_BRBReturnP1toA1(name, func) PROCESS_BRBReturnP1toA1_COMMON(name, func,)
  505. #define PROCESS_BRBMem_ALLOW_STACK_COMMON(name, func, suffix) \
  506. case OpCode::name: \
  507. { \
  508. PROCESS_READ_LAYOUT(name, BrReg1, suffix); \
  509. if (func(GetRegAllowStackVar(playout->R1),GetScriptContext())) \
  510. { \
  511. ip = m_reader.SetCurrentRelativeOffset(ip, playout->RelativeJumpOffset); \
  512. } \
  513. break; \
  514. }
  515. #define PROCESS_BRBMem_ALLOW_STACK(name, func) PROCESS_BRBMem_ALLOW_STACK_COMMON(name, func,)
  516. #define PROCESS_BRCMem_COMMON(name, func,suffix) \
  517. case OpCode::name: \
  518. { \
  519. PROCESS_READ_LAYOUT(name, BrReg2, suffix); \
  520. if (func(GetReg(playout->R1), GetReg(playout->R2),GetScriptContext())) \
  521. { \
  522. ip = m_reader.SetCurrentRelativeOffset(ip, playout->RelativeJumpOffset); \
  523. } \
  524. break; \
  525. }
  526. #define PROCESS_BRCMem(name, func) PROCESS_BRCMem_COMMON(name, func,)
  527. #define PROCESS_BRPROP(name, func) \
  528. case OpCode::name: \
  529. { \
  530. PROCESS_READ_LAYOUT(name, BrProperty,); \
  531. if (func(GetReg(playout->Instance), playout->PropertyIdIndex, GetScriptContext())) \
  532. { \
  533. ip = m_reader.SetCurrentRelativeOffset(ip, playout->RelativeJumpOffset); \
  534. } \
  535. break; \
  536. }
  537. #define PROCESS_BRLOCALPROP(name, func) \
  538. case OpCode::name: \
  539. { \
  540. PROCESS_READ_LAYOUT(name, BrLocalProperty,); \
  541. if (func(this->localClosure, playout->PropertyIdIndex, GetScriptContext())) \
  542. { \
  543. ip = m_reader.SetCurrentRelativeOffset(ip, playout->RelativeJumpOffset); \
  544. } \
  545. break; \
  546. }
  547. #define PROCESS_BRENVPROP(name, func) \
  548. case OpCode::name: \
  549. { \
  550. PROCESS_READ_LAYOUT(name, BrEnvProperty,); \
  551. if (func(LdEnv(), playout->SlotIndex, playout->PropertyIdIndex, GetScriptContext())) \
  552. { \
  553. ip = m_reader.SetCurrentRelativeOffset(ip, playout->RelativeJumpOffset); \
  554. } \
  555. break; \
  556. }
  557. #define PROCESS_W1(name, func) \
  558. case OpCode::name: \
  559. { \
  560. PROCESS_READ_LAYOUT(name, W1,); \
  561. func(playout->C1, GetScriptContext()); \
  562. break; \
  563. }
  564. #define PROCESS_U1toA1_COMMON(name, func, suffix) \
  565. case OpCode::name: \
  566. { \
  567. PROCESS_READ_LAYOUT(name, Reg1Unsigned1, suffix); \
  568. SetReg(playout->R0, \
  569. func(playout->C1,GetScriptContext())); \
  570. break; \
  571. }
  572. #define PROCESS_U1toA1(name, func) PROCESS_U1toA1_COMMON(name, func,)
  573. #define PROCESS_U1toA1NonVar_COMMON(name, func, suffix) \
  574. case OpCode::name: \
  575. { \
  576. PROCESS_READ_LAYOUT(name, Reg1Unsigned1, suffix); \
  577. SetNonVarReg(playout->R0, \
  578. func(playout->C1)); \
  579. break; \
  580. }
  581. #define PROCESS_U1toA1NonVar(name, func) PROCESS_U1toA1NonVar_COMMON(name, func,)
  582. #define PROCESS_U1toA1NonVar_FuncBody_COMMON(name, func, suffix) \
  583. case OpCode::name: \
  584. { \
  585. PROCESS_READ_LAYOUT(name, Reg1Unsigned1, suffix); \
  586. SetNonVarReg(playout->R0, \
  587. func(playout->C1,GetScriptContext(), this->m_functionBody)); \
  588. break; \
  589. }
  590. #define PROCESS_U1toA1NonVar_FuncBody(name, func) PROCESS_U1toA1NonVar_FuncBody_COMMON(name, func,)
  591. #define PROCESS_A1I2toXXNonVar_FuncBody(name, func) PROCESS_A1I2toXXNonVar_FuncBody_COMMON(name, func,)
  592. #define PROCESS_A1I2toXXNonVar_FuncBody_COMMON(name, func, suffix) \
  593. case OpCode::name: \
  594. { \
  595. PROCESS_READ_LAYOUT(name, Reg3, suffix); \
  596. func(playout->R0, playout->R1, playout->R2, GetScriptContext(), this->m_functionBody); \
  597. break; \
  598. }
  599. #define PROCESS_A1U1toXX_COMMON(name, func, suffix) \
  600. case OpCode::name: \
  601. { \
  602. PROCESS_READ_LAYOUT(name, Reg1Unsigned1, suffix); \
  603. func(GetReg(playout->R0), playout->C1); \
  604. break; \
  605. }
  606. #define PROCESS_A1U1toXX(name, func) PROCESS_A1U1toXX_COMMON(name, func,)
  607. #define PROCESS_A1U1toXXWithCache_COMMON(name, func, suffix) \
  608. case OpCode::name: \
  609. { \
  610. PROCESS_READ_LAYOUT(name, ProfiledReg1Unsigned1, suffix); \
  611. func(GetReg(playout->R0), playout->C1, playout->profileId); \
  612. break; \
  613. }
  614. #define PROCESS_A1U1toXXWithCache(name, func) PROCESS_A1U1toXXWithCache_COMMON(name, func,)
  615. #define PROCESS_EnvU1toXX_COMMON(name, func, suffix) \
  616. case OpCode::name: \
  617. { \
  618. PROCESS_READ_LAYOUT(name, Unsigned1, suffix); \
  619. func(LdEnv(), playout->C1); \
  620. break; \
  621. }
  622. #define PROCESS_EnvU1toXX(name, func) PROCESS_EnvU1toXX_COMMON(name, func,)
  623. #define PROCESS_GET_ELEM_SLOTNonVar_COMMON(name, func, layout, suffix) \
  624. case OpCode::name: \
  625. { \
  626. PROCESS_READ_LAYOUT(name, layout, suffix); \
  627. SetNonVarReg(playout->Value, func(GetNonVarReg(playout->Instance), playout)); \
  628. break; \
  629. }
  630. #define PROCESS_GET_ELEM_SLOTNonVar(name, func, layout) PROCESS_GET_ELEM_SLOTNonVar_COMMON(name, func, layout,)
  631. #define PROCESS_GET_ELEM_LOCALSLOTNonVar_COMMON(name, func, layout, suffix) \
  632. case OpCode::name: \
  633. { \
  634. PROCESS_READ_LAYOUT(name, layout, suffix); \
  635. SetNonVarReg(playout->Value, func((Var*)GetLocalClosure(), playout)); \
  636. break; \
  637. }
  638. #define PROCESS_GET_ELEM_LOCALSLOTNonVar(name, func, layout) PROCESS_GET_ELEM_LOCALSLOTNonVar_COMMON(name, func, layout,)
  639. #define PROCESS_GET_ELEM_PARAMSLOTNonVar_COMMON(name, func, layout, suffix) \
  640. case OpCode::name: \
  641. { \
  642. PROCESS_READ_LAYOUT(name, layout, suffix); \
  643. SetNonVarReg(playout->Value, func((Var*)GetParamClosure(), playout)); \
  644. break; \
  645. }
  646. #define PROCESS_GET_ELEM_PARAMSLOTNonVar(name, func, layout) PROCESS_GET_ELEM_PARAMSLOTNonVar_COMMON(name, func, layout,)
  647. #define PROCESS_GET_ELEM_INNERSLOTNonVar_COMMON(name, func, layout, suffix) \
  648. case OpCode::name: \
  649. { \
  650. PROCESS_READ_LAYOUT(name, layout, suffix); \
  651. SetNonVarReg(playout->Value, func(InnerScopeFromIndex(playout->SlotIndex1), playout)); \
  652. break; \
  653. }
  654. #define PROCESS_GET_ELEM_INNERSLOTNonVar(name, func, layout) PROCESS_GET_ELEM_INNERSLOTNonVar_COMMON(name, func, layout,)
  655. #define PROCESS_GET_ELEM_ENVSLOTNonVar_COMMON(name, func, layout, suffix) \
  656. case OpCode::name: \
  657. { \
  658. PROCESS_READ_LAYOUT(name, layout, suffix); \
  659. SetNonVarReg(playout->Value, func(LdEnv(), playout)); \
  660. break; \
  661. }
  662. #define PROCESS_GET_ELEM_ENVSLOTNonVar(name, func, layout) PROCESS_GET_ELEM_ENVSLOTNonVar_COMMON(name, func, layout,)
  663. #define PROCESS_SET_ELEM_SLOTNonVar_COMMON(name, func, suffix) \
  664. case OpCode::name: \
  665. { \
  666. PROCESS_READ_LAYOUT(name, ElementSlot, suffix); \
  667. func(GetNonVarReg(playout->Instance), playout->SlotIndex, GetRegAllowStackVarEnableOnly(playout->Value)); \
  668. break; \
  669. }
  670. #define PROCESS_SET_ELEM_SLOTNonVar(name, func) PROCESS_SET_ELEM_SLOTNonVar_COMMON(name, func,)
  671. #define PROCESS_SET_ELEM_LOCALSLOTNonVar_COMMON(name, func, suffix) \
  672. case OpCode::name: \
  673. { \
  674. PROCESS_READ_LAYOUT(name, ElementSlotI1, suffix); \
  675. func((Var*)GetLocalClosure(), playout->SlotIndex, GetRegAllowStackVarEnableOnly(playout->Value)); \
  676. break; \
  677. }
  678. #define PROCESS_SET_ELEM_LOCALSLOTNonVar(name, func) PROCESS_SET_ELEM_LOCALSLOTNonVar_COMMON(name, func,)
  679. #define PROCESS_SET_ELEM_PARAMSLOTNonVar_COMMON(name, func, suffix) \
  680. case OpCode::name: \
  681. { \
  682. PROCESS_READ_LAYOUT(name, ElementSlotI1, suffix); \
  683. func((Var*)GetParamClosure(), playout->SlotIndex, GetRegAllowStackVarEnableOnly(playout->Value)); \
  684. break; \
  685. }
  686. #define PROCESS_SET_ELEM_PARAMSLOTNonVar(name, func) PROCESS_SET_ELEM_PARAMSLOTNonVar_COMMON(name, func,); \
  687. #define PROCESS_SET_ELEM_INNERSLOTNonVar_COMMON(name, func, suffix) \
  688. case OpCode::name: \
  689. { \
  690. PROCESS_READ_LAYOUT(name, ElementSlotI2, suffix); \
  691. func(InnerScopeFromIndex(playout->SlotIndex1), playout->SlotIndex2, GetRegAllowStackVarEnableOnly(playout->Value)); \
  692. break; \
  693. }
  694. #define PROCESS_SET_ELEM_INNERSLOTNonVar(name, func) PROCESS_SET_ELEM_INNERSLOTNonVar_COMMON(name, func,)
  695. #define PROCESS_SET_ELEM_ENVSLOTNonVar_COMMON(name, func, suffix) \
  696. case OpCode::name: \
  697. { \
  698. PROCESS_READ_LAYOUT(name, ElementSlotI2, suffix); \
  699. func(LdEnv(), playout->SlotIndex1, playout->SlotIndex2, GetRegAllowStackVarEnableOnly(playout->Value)); \
  700. break; \
  701. }
  702. #define PROCESS_SET_ELEM_ENVSLOTNonVar(name, func) PROCESS_SET_ELEM_ENVSLOTNonVar_COMMON(name, func,)
  703. /*---------------------------------------------------------------------------------------------- */
  704. #define PROCESS_A3toA1Mem_COMMON(name, func, suffix) \
  705. case OpCode::name: \
  706. { \
  707. PROCESS_READ_LAYOUT(name, Reg4, suffix); \
  708. SetReg(playout->R0, \
  709. func(GetReg(playout->R1), GetReg(playout->R2), GetReg(playout->R3), GetScriptContext())); \
  710. break; \
  711. }
  712. #define PROCESS_A3toA1Mem(name, func) PROCESS_A3toA1Mem_COMMON(name, func,)
  713. /*---------------------------------------------------------------------------------------------- */
  714. #define PROCESS_A2I1toA1Mem_COMMON(name, func, suffix) \
  715. case OpCode::name: \
  716. { \
  717. PROCESS_READ_LAYOUT(name, Reg3B1, suffix); \
  718. SetReg(playout->R0, \
  719. func(GetReg(playout->R1), GetReg(playout->R2), playout->B3, GetScriptContext())); \
  720. break; \
  721. }
  722. #define PROCESS_A2I1toA1Mem(name, func) PROCESS_A2I1toA1Mem_COMMON(name, func,)
  723. /*---------------------------------------------------------------------------------------------- */
  724. #define PROCESS_A2I1toXXMem_COMMON(name, func, suffix) \
  725. case OpCode::name: \
  726. { \
  727. PROCESS_READ_LAYOUT(name, Reg2B1, suffix); \
  728. func(GetReg(playout->R0), GetReg(playout->R1), playout->B2, scriptContext); \
  729. break; \
  730. }
  731. #define PROCESS_A2I1toXXMem(name, func) PROCESS_A2I1toXXMem_COMMON(name, func,)
  732. /*---------------------------------------------------------------------------------------------- */
  733. #define PROCESS_A3I1toXXMem_COMMON(name, func, suffix) \
  734. case OpCode::name: \
  735. { \
  736. PROCESS_READ_LAYOUT(name, Reg3B1, suffix); \
  737. func(GetReg(playout->R0), GetReg(playout->R1), GetReg(playout->R2), playout->B3, scriptContext); \
  738. break; \
  739. }
  740. #define PROCESS_A3I1toXXMem(name, func) PROCESS_A3I1toXXMem_COMMON(name, func,)
  741. #if ENABLE_PROFILE_INFO
  742. #define PROCESS_IP_TARG_IMPL(name, func, layoutSize) \
  743. case OpCode::name: \
  744. { \
  745. Assert(!switchProfileMode); \
  746. ip = func<layoutSize, INTERPRETERPROFILE>(ip); \
  747. if(switchProfileMode) \
  748. { \
  749. m_reader.SetIP(ip); \
  750. return nullptr; \
  751. } \
  752. break; \
  753. }
  754. #else
  755. #define PROCESS_IP_TARG_IMPL(name, func, layoutSize) \
  756. case OpCode::name: \
  757. { \
  758. ip = func<layoutSize, INTERPRETERPROFILE>(ip); \
  759. break; \
  760. }
  761. #endif
  762. #define PROCESS_IP_TARG_COMMON(name, func, suffix) PROCESS_IP_TARG##suffix(name, func)
  763. #define PROCESS_IP_TARG_Large(name, func) PROCESS_IP_TARG_IMPL(name, func, Js::LargeLayout)
  764. #define PROCESS_IP_TARG_Medium(name, func) PROCESS_IP_TARG_IMPL(name, func, Js::MediumLayout)
  765. #define PROCESS_IP_TARG_Small(name, func) PROCESS_IP_TARG_IMPL(name, func, Js::SmallLayout)
  766. #if ENABLE_TTD
  767. #if ENABLE_TTD_DIAGNOSTICS_TRACING
  768. #define SHOULD_DO_TTD_STACK_STMT_OP(CTX) ((CTX)->ShouldPerformRecordOrReplayAction())
  769. #else
  770. #define SHOULD_DO_TTD_STACK_STMT_OP(CTX) ((CTX)->ShouldPerformRecordOrReplayDebuggerAction())
  771. #endif
  772. #endif
  773. namespace Js
  774. {
  775. Var InterpreterStackFrame::InnerScopeFromRegSlot(RegSlot reg) const
  776. {
  777. return InnerScopeFromIndex(reg - m_functionBody->GetFirstInnerScopeRegister());
  778. }
  779. Var InterpreterStackFrame::InnerScopeFromIndex(uint32 index) const
  780. {
  781. if (index >= m_functionBody->GetInnerScopeCount())
  782. {
  783. AssertMsg(false, "Illegal byte code: bad inner scope index");
  784. Js::Throw::FatalInternalError();
  785. }
  786. Assert(this->innerScopeArray != nullptr);
  787. return this->innerScopeArray[index];
  788. }
  789. void InterpreterStackFrame::SetInnerScopeFromIndex(uint32 index, Var scope)
  790. {
  791. if (index >= m_functionBody->GetInnerScopeCount())
  792. {
  793. AssertMsg(false, "Illegal byte code: bad inner scope index");
  794. Js::Throw::FatalInternalError();
  795. }
  796. Assert(this->innerScopeArray != nullptr);
  797. this->innerScopeArray[index] = scope;
  798. }
  799. const int k_stackFrameVarCount = (sizeof(InterpreterStackFrame) + sizeof(Var) - 1) / sizeof(Var);
  800. InterpreterStackFrame::Setup::Setup(Js::ScriptFunction * function, Js::Arguments& args, bool bailedOut, bool inlinee)
  801. : function(function), inParams(args.Values), inSlotsCount(args.Info.Count), executeFunction(function->GetFunctionBody()), callFlags(args.Info.Flags), bailedOutOfInlinee(inlinee), bailedOut(bailedOut)
  802. {
  803. SetupInternal();
  804. }
  805. InterpreterStackFrame::Setup::Setup(Js::ScriptFunction * function, Var * inParams, int inSlotsCount)
  806. : function(function), inParams(inParams), inSlotsCount(inSlotsCount), executeFunction(function->GetFunctionBody()), callFlags(CallFlags_None), bailedOutOfInlinee(false), bailedOut(false)
  807. {
  808. SetupInternal();
  809. }
  810. void InterpreterStackFrame::Setup::SetupInternal()
  811. {
  812. if (this->function->GetHasInlineCaches() && Js::ScriptFunctionWithInlineCache::Is(this->function))
  813. {
  814. this->inlineCaches = (void**)Js::ScriptFunctionWithInlineCache::FromVar(this->function)->GetInlineCaches();
  815. Assert(this->inlineCaches != nullptr);
  816. }
  817. else
  818. {
  819. this->inlineCaches = this->executeFunction->GetInlineCaches();
  820. }
  821. this->inlineCacheCount = this->executeFunction->GetInlineCacheCount();
  822. //
  823. // Compute the amount of memory needed on the stack:
  824. // - We compute this in 'Atoms' instead of 'bytes' to keep everything natural word aligned.
  825. //
  826. this->localCount = this->executeFunction->GetLocalsCount();
  827. uint extraVarCount = 0;
  828. #if ENABLE_PROFILE_INFO
  829. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(this->executeFunction))
  830. {
  831. extraVarCount += (sizeof(ImplicitCallFlags) * this->executeFunction->GetLoopCount() + sizeof(Var) - 1) / sizeof(Var);
  832. }
  833. #endif
  834. // If we bailed out, we will use the JIT frame's for..in enumerators
  835. uint forInVarCount = bailedOut? 0 : (this->executeFunction->GetForInLoopDepth() * (sizeof(Js::ForInObjectEnumerator) / sizeof(Var)));
  836. this->varAllocCount = k_stackFrameVarCount + localCount + this->executeFunction->GetOutParamMaxDepth() + forInVarCount +
  837. extraVarCount + this->executeFunction->GetInnerScopeCount();
  838. if (this->executeFunction->DoStackNestedFunc() && this->executeFunction->GetNestedCount() != 0)
  839. {
  840. // Track stack funcs...
  841. this->varAllocCount += (sizeof(StackScriptFunction) * this->executeFunction->GetNestedCount()) / sizeof(Var);
  842. if (!this->bailedOutOfInlinee)
  843. {
  844. // Frame display (if environment depth is statically known)...
  845. if (this->executeFunction->DoStackFrameDisplay())
  846. {
  847. uint16 envDepth = this->executeFunction->GetEnvDepth();
  848. Assert(envDepth != (uint16)-1);
  849. this->varAllocCount += sizeof(FrameDisplay) / sizeof(Var) + (envDepth + 1);
  850. }
  851. // ...and scope slots (if any)
  852. if (this->executeFunction->DoStackScopeSlots())
  853. {
  854. uint32 scopeSlots = this->executeFunction->scopeSlotArraySize;
  855. Assert(scopeSlots != 0);
  856. this->varAllocCount += scopeSlots + Js::ScopeSlots::FirstSlotIndex;
  857. }
  858. }
  859. }
  860. }
  861. InterpreterStackFrame *
  862. InterpreterStackFrame::Setup::InitializeAllocation(__in_ecount(varAllocCount) Var * allocation, bool initParams, bool profileParams, LoopHeader* loopHeaderArray, DWORD_PTR stackAddr
  863. #if DBG
  864. , Var invalidStackVar
  865. #endif
  866. )
  867. {
  868. //
  869. // Initialize the new InterpreterStackFrame instance on the program stack.
  870. //
  871. //This will fail if InterpreterStackFrame ever gets a non-empty ctor (you'll need to use
  872. //placement_new(allocation, InterpreterStackFrame) instead, though that will cause problems
  873. //if the placement_new is surrounded by a try/finally since this would mix C++/SEH exception
  874. //handling.
  875. __analysis_assume(varAllocCount >= k_stackFrameVarCount + localCount);
  876. InterpreterStackFrame* newInstance = (InterpreterStackFrame*)allocation;
  877. newInstance->scriptContext = this->executeFunction->GetScriptContext();
  878. newInstance->m_inSlotsCount = this->inSlotsCount;
  879. newInstance->m_inParams = this->inParams;
  880. newInstance->m_callFlags = this->callFlags;
  881. newInstance->m_outParams = newInstance->m_localSlots + localCount;
  882. newInstance->m_outSp = newInstance->m_outParams;
  883. newInstance->m_outSpCached = nullptr;
  884. newInstance->m_arguments = NULL;
  885. newInstance->function = this->function;
  886. newInstance->m_functionBody = this->executeFunction;
  887. newInstance->inlineCaches = this->inlineCaches;
  888. newInstance->inlineCacheCount = this->inlineCacheCount;
  889. newInstance->currentLoopNum = LoopHeader::NoLoop;
  890. newInstance->currentLoopCounter = 0;
  891. newInstance->m_flags = InterpreterStackFrameFlags_None;
  892. newInstance->closureInitDone = false;
  893. newInstance->isParamScopeDone = false;
  894. newInstance->shouldCacheSP = true;
  895. #if ENABLE_PROFILE_INFO
  896. newInstance->switchProfileMode = false;
  897. newInstance->isAutoProfiling = false;
  898. newInstance->switchProfileModeOnLoopEndNumber = 0u - 1;
  899. #endif
  900. newInstance->ehBailoutData = nullptr;
  901. newInstance->nestedTryDepth = -1;
  902. newInstance->nestedCatchDepth = -1;
  903. newInstance->nestedFinallyDepth = -1;
  904. newInstance->retOffset = 0;
  905. newInstance->localFrameDisplay = nullptr;
  906. newInstance->localClosure = nullptr;
  907. newInstance->paramClosure = nullptr;
  908. newInstance->innerScopeArray = nullptr;
  909. newInstance->m_asmJsBuffer = nullptr;
  910. #ifdef ENABLE_WASM
  911. newInstance->m_wasmMemory = nullptr;
  912. #endif
  913. Var* outparamsEnd = newInstance->m_outParams + this->executeFunction->GetOutParamMaxDepth();
  914. #if DBG
  915. newInstance->m_outParamsEnd = outparamsEnd;
  916. #endif
  917. bool doInterruptProbe = newInstance->scriptContext->GetThreadContext()->DoInterruptProbe(this->executeFunction);
  918. #if ENABLE_NATIVE_CODEGEN
  919. bool doJITLoopBody =
  920. !this->executeFunction->GetScriptContext()->GetConfig()->IsNoNative() &&
  921. !(this->executeFunction->GetHasTry() && (PHASE_OFF((Js::JITLoopBodyInTryCatchPhase), this->executeFunction))) &&
  922. !(this->executeFunction->GetHasFinally() && (PHASE_OFF((Js::JITLoopBodyInTryFinallyPhase), this->executeFunction))) &&
  923. (this->executeFunction->ForceJITLoopBody() || this->executeFunction->IsJitLoopBodyPhaseEnabled()) &&
  924. !this->executeFunction->IsInDebugMode();
  925. #endif
  926. // Pick a version of the LoopBodyStart OpCode handlers that is hardcoded to do loop body JIT and
  927. // interrupt probes as needed.
  928. if (doInterruptProbe)
  929. {
  930. #if ENABLE_NATIVE_CODEGEN
  931. if (doJITLoopBody)
  932. {
  933. newInstance->opProfiledLoopBodyStart = &InterpreterStackFrame::ProfiledLoopBodyStart<true, true>;
  934. newInstance->opLoopBodyStart = &InterpreterStackFrame::LoopBodyStart<true, true>;
  935. }
  936. else
  937. #endif
  938. {
  939. #if ENABLE_PROFILE_INFO
  940. newInstance->opProfiledLoopBodyStart = &InterpreterStackFrame::ProfiledLoopBodyStart<true, false>;
  941. #endif
  942. newInstance->opLoopBodyStart = &InterpreterStackFrame::LoopBodyStart<true, false>;
  943. }
  944. }
  945. else
  946. {
  947. #if ENABLE_NATIVE_CODEGEN
  948. if (doJITLoopBody)
  949. {
  950. newInstance->opProfiledLoopBodyStart = &InterpreterStackFrame::ProfiledLoopBodyStart<false, true>;
  951. newInstance->opLoopBodyStart = &InterpreterStackFrame::LoopBodyStart<false, true>;
  952. }
  953. else
  954. #endif
  955. {
  956. #if ENABLE_PROFILE_INFO
  957. newInstance->opProfiledLoopBodyStart = &InterpreterStackFrame::ProfiledLoopBodyStart<false, false>;
  958. #endif
  959. newInstance->opLoopBodyStart = &InterpreterStackFrame::LoopBodyStart<false, false>;
  960. }
  961. }
  962. newInstance->loopHeaderArray = loopHeaderArray;
  963. newInstance->m_stackAddress = stackAddr;
  964. #if ENABLE_PROFILE_INFO
  965. // the savedLoopImplicitCallFlags is allocated at the end of the out param array
  966. newInstance->savedLoopImplicitCallFlags = nullptr;
  967. #endif
  968. char * nextAllocBytes = (char *)(outparamsEnd);
  969. // If we bailed out, we will use the JIT frame's for..in enumerators
  970. if (bailedOut || this->executeFunction->GetForInLoopDepth() == 0)
  971. {
  972. newInstance->forInObjectEnumerators = nullptr;
  973. }
  974. else
  975. {
  976. newInstance->forInObjectEnumerators = (ForInObjectEnumerator *)nextAllocBytes;
  977. nextAllocBytes += sizeof(ForInObjectEnumerator) * this->executeFunction->GetForInLoopDepth();
  978. }
  979. if (this->executeFunction->GetInnerScopeCount())
  980. {
  981. newInstance->innerScopeArray = (Var*)nextAllocBytes;
  982. nextAllocBytes += this->executeFunction->GetInnerScopeCount() * sizeof(Var);
  983. }
  984. if (this->executeFunction->DoStackNestedFunc() && this->executeFunction->GetNestedCount() != 0)
  985. {
  986. newInstance->InitializeStackFunctions((StackScriptFunction *)nextAllocBytes);
  987. nextAllocBytes = nextAllocBytes + sizeof(StackScriptFunction) * this->executeFunction->GetNestedCount();
  988. if (!this->bailedOutOfInlinee)
  989. {
  990. if (this->executeFunction->DoStackFrameDisplay())
  991. {
  992. uint16 envDepth = this->executeFunction->GetEnvDepth();
  993. Assert(envDepth != (uint16)-1);
  994. newInstance->localFrameDisplay = (FrameDisplay*)nextAllocBytes;
  995. newInstance->localFrameDisplay->SetLength(0); // Start with no scopes. It will get set in NewFrameDisplay
  996. nextAllocBytes += sizeof(FrameDisplay) + (envDepth + 1) * sizeof(Var);
  997. }
  998. if (this->executeFunction->DoStackScopeSlots())
  999. {
  1000. uint32 scopeSlots = this->executeFunction->scopeSlotArraySize;
  1001. Assert(scopeSlots != 0);
  1002. ScopeSlots((Field(Var)*)nextAllocBytes).SetCount(0); // Start with count as 0. It will get set in NewScopeSlots
  1003. newInstance->localClosure = nextAllocBytes;
  1004. nextAllocBytes += (scopeSlots + ScopeSlots::FirstSlotIndex) * sizeof(Var);
  1005. }
  1006. }
  1007. }
  1008. #if ENABLE_PROFILE_INFO
  1009. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(this->executeFunction))
  1010. {
  1011. /*
  1012. __analysis_assume(varAllocCount == (k_stackFrameVarCount + localCount + executeFunction->GetOutParamMaxDepth()
  1013. + ((sizeof(ImplicitCallFlags) * executeFunction->GetLoopCount() + sizeof(Var) - 1) / sizeof(Var))));
  1014. */
  1015. newInstance->savedLoopImplicitCallFlags = (ImplicitCallFlags *)nextAllocBytes;
  1016. for (uint i = 0; i < this->executeFunction->GetLoopCount(); i++)
  1017. {
  1018. #pragma prefast(suppress:26015, "Above analysis assume doesn't work")
  1019. newInstance->savedLoopImplicitCallFlags[i] = ImplicitCall_None;
  1020. }
  1021. }
  1022. #endif
  1023. #if DBG
  1024. if (CONFIG_ISENABLED(InitializeInterpreterSlotsWithInvalidStackVarFlag))
  1025. {
  1026. // Fill the local slots with the invalid stack var so that we will crash deterministically if something goes wrong
  1027. for (uint i = 0; i < localCount; ++i)
  1028. {
  1029. newInstance->m_localSlots[i] = invalidStackVar;
  1030. }
  1031. }
  1032. else
  1033. {
  1034. memset(newInstance->m_localSlots, 0, sizeof(Js::Var) * localCount);
  1035. }
  1036. #else
  1037. if (newInstance->m_functionBody->IsInDebugMode())
  1038. {
  1039. // In the debug mode zero out the local slot, so this could prevent locals being uninitialized in the case of setNextStatement.
  1040. memset(newInstance->m_localSlots, 0, sizeof(Js::Var) * localCount);
  1041. }
  1042. else
  1043. {
  1044. Js::RegSlot varCount = function->GetFunctionBody()->GetVarCount();
  1045. if (varCount)
  1046. {
  1047. // Zero out the non-constant var slots.
  1048. Js::RegSlot constantCount = function->GetFunctionBody()->GetConstantCount();
  1049. memset(newInstance->m_localSlots + constantCount, 0, varCount * sizeof(Js::Var));
  1050. }
  1051. // Zero out the return slot. This is not a user local, so the byte code will not initialize
  1052. // it to "undefined". And it's not an expression temp, so, for instance, a jitted loop body may expect
  1053. // it to be valid on entry to the loop, where "valid" means either a var or null.
  1054. newInstance->SetNonVarReg(0, NULL);
  1055. }
  1056. #endif
  1057. // Wasm doesn't use const table
  1058. if (!executeFunction->IsWasmFunction())
  1059. {
  1060. // Initialize the low end of the local slots from the constant table.
  1061. // Skip the slot for the return value register.
  1062. this->executeFunction->InitConstantSlots(&newInstance->m_localSlots[FunctionBody::FirstRegSlot]);
  1063. }
  1064. // Set local FD/SS pointers to null until after we've successfully probed the stack in the process loop.
  1065. // That way we avoid trying to box these structures before they've been initialized in the byte code.
  1066. if (this->executeFunction->DoStackFrameDisplay())
  1067. {
  1068. newInstance->SetNonVarReg(executeFunction->GetLocalFrameDisplayRegister(), nullptr);
  1069. }
  1070. if (this->executeFunction->DoStackScopeSlots())
  1071. {
  1072. Assert(!executeFunction->HasScopeObject());
  1073. newInstance->SetNonVarReg(executeFunction->GetLocalClosureRegister(), nullptr);
  1074. }
  1075. Var *prestDest = &newInstance->m_localSlots[this->executeFunction->GetConstantCount()];
  1076. if (initParams)
  1077. {
  1078. #if ENABLE_PROFILE_INFO
  1079. Assert(!this->executeFunction->NeedEnsureDynamicProfileInfo());
  1080. #endif
  1081. if (profileParams)
  1082. {
  1083. #if ENABLE_PROFILE_INFO
  1084. Assert(this->executeFunction->HasExecutionDynamicProfileInfo());
  1085. #endif
  1086. FunctionBody* functionBody = this->executeFunction;
  1087. InitializeParams(newInstance, [functionBody](Var param, ArgSlot index)
  1088. {
  1089. #if ENABLE_PROFILE_INFO
  1090. functionBody->GetDynamicProfileInfo()->RecordParameterInfo(functionBody, index - 1, param);
  1091. #endif
  1092. }, &prestDest);
  1093. }
  1094. else
  1095. {
  1096. InitializeParams(newInstance, [](Var param, ArgSlot index) {}, &prestDest);
  1097. }
  1098. }
  1099. if (this->executeFunction->GetHasRestParameter())
  1100. {
  1101. InitializeRestParam(newInstance, prestDest);
  1102. }
  1103. Js::RegSlot envReg = executeFunction->GetEnvRegister();
  1104. if (envReg != Js::Constants::NoRegister && envReg < executeFunction->GetConstantCount())
  1105. {
  1106. Assert(this->executeFunction->GetThisRegisterForEventHandler() == Constants::NoRegister);
  1107. // The correct FD (possibly distinct from the one on the function) is passed in the constant table.
  1108. this->function->SetEnvironment((Js::FrameDisplay*)newInstance->GetNonVarReg(envReg));
  1109. }
  1110. return newInstance;
  1111. }
  1112. template <class Fn>
  1113. void InterpreterStackFrame::Setup::InitializeParams(InterpreterStackFrame * newInstance, Fn callback, Var **pprestDest)
  1114. {
  1115. ArgSlot requiredInParamCount = executeFunction->GetInParamsCount();
  1116. Assert(requiredInParamCount > 1);
  1117. if (this->inSlotsCount >= requiredInParamCount)
  1118. {
  1119. Var * pArg = &newInstance->m_localSlots[executeFunction->GetConstantCount()];
  1120. Var * paGivenSrc = this->inParams + 1;
  1121. ArgSlot paramIndex = 1;
  1122. do
  1123. {
  1124. Var src = *paGivenSrc++;
  1125. callback(src, paramIndex);
  1126. *pArg++ = src;
  1127. paramIndex++;
  1128. }
  1129. while (paramIndex < requiredInParamCount);
  1130. *pprestDest = pArg;
  1131. }
  1132. else
  1133. {
  1134. InitializeParamsAndUndef(newInstance, callback, pprestDest);
  1135. }
  1136. }
  1137. template <class Fn>
  1138. void InterpreterStackFrame::Setup::InitializeParamsAndUndef(InterpreterStackFrame * newInstance, Fn callback, Var **pprestDest)
  1139. {
  1140. Var * pArg = &newInstance->m_localSlots[executeFunction->GetConstantCount()];
  1141. Var * paGivenSrc = this->inParams + 1;
  1142. ArgSlot requiredInParamCount = executeFunction->GetInParamsCount();
  1143. ArgSlot paramIndex = 1;
  1144. while (paramIndex < this->inSlotsCount)
  1145. {
  1146. Var src = *paGivenSrc++;
  1147. callback(src, paramIndex);
  1148. *pArg++ = src;
  1149. paramIndex++;
  1150. }
  1151. Var varUndef = executeFunction->GetScriptContext()->GetLibrary()->GetUndefined();
  1152. do
  1153. {
  1154. callback(varUndef, paramIndex);
  1155. *pArg++ = varUndef;
  1156. paramIndex++;
  1157. }
  1158. while (paramIndex < requiredInParamCount);
  1159. *pprestDest = pArg;
  1160. }
  1161. void InterpreterStackFrame::Setup::InitializeRestParam(InterpreterStackFrame * newInstance, Var *dest)
  1162. {
  1163. Var *src = this->inParams + executeFunction->GetInParamsCount();
  1164. if (this->inSlotsCount > executeFunction->GetInParamsCount())
  1165. {
  1166. // Create the rest array and copy the args directly into the contiguous head segment.
  1167. int excess = this->inSlotsCount - executeFunction->GetInParamsCount();
  1168. *dest = JavascriptArray::OP_NewScArray(excess, executeFunction->GetScriptContext());
  1169. JavascriptArray *array = static_cast<JavascriptArray *>(*dest);
  1170. Field(Var)* elements = SparseArraySegment<Var>::From(array->GetHead())->elements;
  1171. CopyArray(elements, excess, src, excess);
  1172. }
  1173. else
  1174. {
  1175. // Rest is an empty array when there are no excess parameters.
  1176. *dest = JavascriptArray::OP_NewScArray(0, executeFunction->GetScriptContext());
  1177. }
  1178. }
  1179. FrameDisplay * InterpreterStackFrame::GetEnvForEvalCode()
  1180. {
  1181. FrameDisplay *pScope;
  1182. if (m_functionBody->GetIsStrictMode() && m_functionBody->GetIsGlobalFunc())
  1183. {
  1184. pScope = this->GetLocalFrameDisplay();
  1185. }
  1186. else
  1187. {
  1188. pScope = (FrameDisplay*)this->LdEnv();
  1189. }
  1190. return pScope;
  1191. }
  1192. void InterpreterStackFrame::InitializeClosures()
  1193. {
  1194. FunctionBody *executeFunction = this->function->GetFunctionBody();
  1195. Var environment;
  1196. if (executeFunction->IsParamAndBodyScopeMerged())
  1197. {
  1198. this->SetIsParamScopeDone(true);
  1199. }
  1200. RegSlot thisRegForEventHandler = executeFunction->GetThisRegisterForEventHandler();
  1201. if (thisRegForEventHandler != Constants::NoRegister)
  1202. {
  1203. Var varThis = OP_ArgIn0();
  1204. SetReg(thisRegForEventHandler, varThis);
  1205. environment = JavascriptOperators::OP_LdHandlerScope(varThis, GetScriptContext());
  1206. this->SetEnv((FrameDisplay*)environment);
  1207. }
  1208. else if (this->paramClosure != nullptr)
  1209. {
  1210. // When paramClosure is non-null we are calling this method to initialize the closure for body scope.
  1211. // In this case we have to use the param scope's closure as the parent for the body scope's frame display.
  1212. Assert(!executeFunction->IsParamAndBodyScopeMerged());
  1213. environment = this->GetLocalFrameDisplay();
  1214. }
  1215. else
  1216. {
  1217. environment = this->LdEnv();
  1218. }
  1219. Var funcExprScope = nullptr;
  1220. Js::RegSlot funcExprScopeReg = executeFunction->GetFuncExprScopeRegister();
  1221. if (funcExprScopeReg != Constants::NoRegister && this->paramClosure == nullptr)
  1222. {
  1223. // t0 = NewPseudoScope
  1224. // t1 = LdFrameDisplay t0 env
  1225. funcExprScope = JavascriptOperators::OP_NewPseudoScope(GetScriptContext());
  1226. SetReg(funcExprScopeReg, funcExprScope);
  1227. }
  1228. RegSlot closureReg = executeFunction->GetLocalClosureRegister();
  1229. if (closureReg != Js::Constants::NoRegister)
  1230. {
  1231. Assert(closureReg >= executeFunction->GetConstantCount());
  1232. if (executeFunction->HasScopeObject())
  1233. {
  1234. this->NewScopeObject();
  1235. }
  1236. else
  1237. {
  1238. this->NewScopeSlots();
  1239. }
  1240. this->SetNonVarReg(closureReg, nullptr);
  1241. }
  1242. Js::RegSlot frameDisplayReg = executeFunction->GetLocalFrameDisplayRegister();
  1243. if (frameDisplayReg != Js::Constants::NoRegister)
  1244. {
  1245. Assert(frameDisplayReg >= executeFunction->GetConstantCount());
  1246. if (funcExprScope != nullptr)
  1247. {
  1248. environment = OP_LdFrameDisplay(funcExprScope, environment, GetScriptContext());
  1249. }
  1250. if (closureReg != Js::Constants::NoRegister)
  1251. {
  1252. void *argHead = this->GetLocalClosure();
  1253. environment = this->NewFrameDisplay(argHead, environment);
  1254. }
  1255. this->SetLocalFrameDisplay((Js::FrameDisplay*)environment);
  1256. this->SetNonVarReg(frameDisplayReg, nullptr);
  1257. }
  1258. this->closureInitDone = true;
  1259. }
  1260. #ifdef _M_IX86
  1261. #ifdef ASMJS_PLAT
  1262. int InterpreterStackFrame::GetAsmJsArgSize(AsmJsCallStackLayout* stack)
  1263. {
  1264. JavascriptFunction * func = stack->functionObject;
  1265. AsmJsFunctionInfo* asmInfo = func->GetFunctionBody()->GetAsmJsFunctionInfo();
  1266. uint argSize = (uint)(asmInfo->GetArgByteSize());
  1267. argSize = ::Math::Align<int32>(argSize, 8);
  1268. // 2 * sizeof(Var) is for functionObject, and another push that DynamicInterpreterThunk does
  1269. return argSize + 2 * sizeof(Var);
  1270. }
  1271. int InterpreterStackFrame::GetDynamicRetType(AsmJsCallStackLayout* stack)
  1272. {
  1273. return GetRetType(stack->functionObject);
  1274. }
  1275. int InterpreterStackFrame::GetRetType(JavascriptFunction* func)
  1276. {
  1277. AsmJsFunctionInfo* asmInfo = func->GetFunctionBody()->GetAsmJsFunctionInfo();
  1278. return asmInfo->GetReturnType().which();
  1279. }
  1280. #ifdef ASMJS_PLAT
  1281. /*
  1282. AsmInterpreterThunk
  1283. -------------------
  1284. This is the entrypoint for all Asm Interpreter calls (external and internal)
  1285. TODO - Make this a dynamic Interpreter thunk to support ETW
  1286. Functionality:
  1287. 1) Prolog
  1288. 2) call AsmInterpreter passing the function object
  1289. 3) Get The return type
  1290. 4) Check for Double or Float return type
  1291. 5) If true then retrieve the value stored at a constant offset from the ScriptContext
  1292. 6) Get Argument Size for callee cleanup
  1293. 7) EpiLog
  1294. a) Retrieve the frame pointer
  1295. b) Store the return address in register (edx)
  1296. c) Clean the arguments based on the arguments size
  1297. d) push the return address back into the stack
  1298. */
  1299. __declspec(naked)
  1300. void InterpreterStackFrame::InterpreterAsmThunk(AsmJsCallStackLayout* layout)
  1301. {
  1302. __asm
  1303. {
  1304. //Prologue
  1305. push ebp;
  1306. mov ebp, esp;
  1307. // Allocate space to put the return value
  1308. sub esp, 16;
  1309. and esp, -16;
  1310. push esp;
  1311. push layout;
  1312. call InterpreterStackFrame::AsmJsInterpreter;
  1313. // we need to move stack around in order to do callee cleanup
  1314. // unfortunately, we don't really have enough registers to do this cleanly
  1315. //
  1316. // we are rearranging the stack from this:
  1317. // 0x14 caller push scriptArg1
  1318. // 0x10 caller push functionObject
  1319. // 0x0C DynamicInterpreterThunk return address
  1320. // 0x08 DynamicInterpreterThunk push ebp
  1321. // 0x04 DynamicInterpreterThunk push functionObject
  1322. // 0x00 InterpreterAsmThunk return address <- stack pointer
  1323. // to this:
  1324. // 0x14 DynamicInterpreterThunk return address
  1325. // 0x10 DynamicInterpreterThunk push ebp
  1326. // 0x0C InterpreterAsmThunk return address <- stack pointer
  1327. // Read return value into possible registers
  1328. movups xmm0, [esp];
  1329. mov edx, [esp + 4];
  1330. mov eax, [esp];
  1331. mov ecx, layout;
  1332. // Epilog, callee cleanup
  1333. mov esp, ebp;
  1334. pop ebp;
  1335. push eax; // save eax
  1336. push edx; // save edx
  1337. // we have to do +0x8 on all stack addresses because we saved 2 registers
  1338. push ecx; // ebp has been restored, we can't use parameters anymore
  1339. call InterpreterStackFrame::GetAsmJsArgSize;
  1340. mov ecx, eax;
  1341. lea eax, [esp + ecx * 1 + 0x8 + 0x8]; // eax will be our stack destination
  1342. mov edx, [esp + 0xC + 0x8];
  1343. mov [eax], edx; // move the dynamic interpreter thunk return location
  1344. mov edx, [esp + 0x8 + 0x8];
  1345. mov [eax - 0x4], edx; // move the dynamic interpreter thunk "push ebp" location
  1346. // skip "push functionObject"
  1347. mov edx, [esp + 0x0 + 0x8];
  1348. mov [eax - 0x8], edx; // move the return location
  1349. pop edx; // restore possible int64 return value
  1350. pop eax; // restore return value
  1351. add esp, ecx; // cleanup arguments
  1352. ret;
  1353. }
  1354. }
  1355. #endif
  1356. #endif
  1357. #endif
  1358. #if DYNAMIC_INTERPRETER_THUNK
  1359. #ifdef _M_IX86
  1360. __declspec(naked)
  1361. Var InterpreterStackFrame::DelayDynamicInterpreterThunk(RecyclableObject* function, CallInfo callInfo, ...)
  1362. {
  1363. __asm
  1364. {
  1365. push ebp
  1366. mov ebp, esp
  1367. push [esp+8] // push function object
  1368. call InterpreterStackFrame::EnsureDynamicInterpreterThunk;
  1369. #ifdef _CONTROL_FLOW_GUARD
  1370. // verify that the call target is valid
  1371. push eax
  1372. mov ecx, eax
  1373. call[__guard_check_icall_fptr]
  1374. pop eax
  1375. #endif
  1376. pop ebp
  1377. jmp eax
  1378. }
  1379. }
  1380. #endif
  1381. #endif
  1382. #if ENABLE_PROFILE_INFO
  1383. JavascriptMethod InterpreterStackFrame::EnsureDynamicInterpreterThunk(Js::ScriptFunction * function)
  1384. {
  1385. #if DYNAMIC_INTERPRETER_THUNK
  1386. Assert(function);
  1387. Js::FunctionBody *functionBody = function->GetFunctionBody();
  1388. JavascriptMethod entrypoint = functionBody->EnsureDynamicInterpreterThunk(function->GetFunctionEntryPointInfo());
  1389. Assert(!IsDelayDynamicInterpreterThunk(functionBody->GetDirectEntryPoint(function->GetEntryPointInfo())));
  1390. if (function->GetEntryPoint() == InterpreterStackFrame::DelayDynamicInterpreterThunk)
  1391. {
  1392. // If we are not profiling, or the function object is not cross site, this is the direct entry point.
  1393. // Change the entry point on the object
  1394. Assert(functionBody->GetDirectEntryPoint(function->GetEntryPointInfo()) == entrypoint);
  1395. function->ChangeEntryPoint(function->GetEntryPointInfo(), entrypoint);
  1396. }
  1397. // Return the original entry point to be called
  1398. return entrypoint;
  1399. #else
  1400. return function->GetEntryPoint();
  1401. #endif
  1402. }
  1403. #endif
  1404. bool InterpreterStackFrame::IsDelayDynamicInterpreterThunk(JavascriptMethod entryPoint)
  1405. {
  1406. return
  1407. #if DYNAMIC_INTERPRETER_THUNK
  1408. #if _M_X64
  1409. entryPoint == InterpreterStackFrame::AsmJsDelayDynamicInterpreterThunk ||
  1410. #endif
  1411. entryPoint == InterpreterStackFrame::DelayDynamicInterpreterThunk;
  1412. #else
  1413. false;
  1414. #endif
  1415. }
  1416. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  1417. THREAD_LOCAL int InterpreterThunkStackCountTracker::s_count = 0;
  1418. #endif
  1419. #if DYNAMIC_INTERPRETER_THUNK
  1420. #pragma optimize("", off)
  1421. #ifdef ASMJS_PLAT
  1422. void InterpreterStackFrame::StaticInterpreterAsmThunk(RecyclableObject* function, ...)
  1423. {
  1424. InterpreterAsmThunk((AsmJsCallStackLayout*)&function);
  1425. }
  1426. #endif
  1427. #if !defined(_M_ARM64)
  1428. Var InterpreterStackFrame::StaticInterpreterThunk(RecyclableObject* function, CallInfo callInfo, ...)
  1429. {
  1430. return InterpreterThunk((JavascriptCallStackLayout*)&function);
  1431. }
  1432. #else
  1433. // Language\arm64\arm64_Thunks.asm
  1434. #endif
  1435. #pragma optimize("", on)
  1436. Var InterpreterStackFrame::InterpreterThunk(JavascriptCallStackLayout* layout)
  1437. {
  1438. Js::ScriptFunction * function = Js::ScriptFunction::UnsafeFromVar(layout->functionObject);
  1439. Js::ArgumentReader args(&layout->callInfo, layout->args);
  1440. void* localReturnAddress = _ReturnAddress();
  1441. void* localAddressOfReturnAddress = _AddressOfReturnAddress();
  1442. return InterpreterHelper(function, args, localReturnAddress, localAddressOfReturnAddress);
  1443. }
  1444. #else
  1445. #pragma optimize("", off)
  1446. Var InterpreterStackFrame::InterpreterThunk(RecyclableObject* function, CallInfo callInfo, ...)
  1447. {
  1448. ARGUMENTS(args, callInfo);
  1449. void* localReturnAddress = _ReturnAddress();
  1450. void* localAddressOfReturnAddress = _AddressOfReturnAddress();
  1451. Assert(ScriptFunction::Is(function));
  1452. return InterpreterHelper(ScriptFunction::FromVar(function), args, localReturnAddress, localAddressOfReturnAddress);
  1453. }
  1454. #pragma optimize("", on)
  1455. #endif
  1456. const bool InterpreterStackFrame::ShouldDoProfile(FunctionBody* executeFunction)
  1457. {
  1458. #if ENABLE_PROFILE_INFO
  1459. const bool doProfile = executeFunction->GetInterpreterExecutionMode(false) == ExecutionMode::ProfilingInterpreter ||
  1460. (executeFunction->IsInDebugMode() && DynamicProfileInfo::IsEnabled(executeFunction));
  1461. return doProfile;
  1462. #else
  1463. return false;
  1464. #endif
  1465. }
  1466. InterpreterStackFrame* InterpreterStackFrame::CreateInterpreterStackFrameForGenerator(ScriptFunction* function, FunctionBody* executeFunction, JavascriptGenerator* generator, bool doProfile)
  1467. {
  1468. //
  1469. // Allocate a new InterpreterStackFrame instance on the recycler heap.
  1470. // It will live with the JavascriptGenerator object.
  1471. //
  1472. ScriptContext* functionScriptContext = function->GetScriptContext();
  1473. Arguments generatorArgs = generator->GetArguments();
  1474. InterpreterStackFrame::Setup setup(function, generatorArgs);
  1475. size_t varAllocCount = setup.GetAllocationVarCount();
  1476. size_t varSizeInBytes = varAllocCount * sizeof(Var);
  1477. DWORD_PTR stackAddr = reinterpret_cast<DWORD_PTR>(&generator); // use any stack address from this frame to ensure correct debugging functionality
  1478. LoopHeader* loopHeaderArray = executeFunction->GetHasAllocatedLoopHeaders() ? executeFunction->GetLoopHeaderArrayPtr() : nullptr;
  1479. Var* allocation = RecyclerNewPlus(functionScriptContext->GetRecycler(), varSizeInBytes, Var);
  1480. AnalysisAssert(allocation);
  1481. InterpreterStackFrame* newInstance;
  1482. #if DBG
  1483. // Allocate invalidVar on GC instead of stack since this InterpreterStackFrame will out live the current real frame
  1484. Js::RecyclableObject* invalidVar = (Js::RecyclableObject*)RecyclerNewPlusLeaf(functionScriptContext->GetRecycler(), sizeof(Js::RecyclableObject), Var);
  1485. AnalysisAssert(invalidVar);
  1486. memset(reinterpret_cast<void*>(invalidVar), 0xFE, sizeof(Js::RecyclableObject));
  1487. newInstance = setup.InitializeAllocation(allocation, executeFunction->GetHasImplicitArgIns(), doProfile, loopHeaderArray, stackAddr, invalidVar);
  1488. #else
  1489. newInstance = setup.InitializeAllocation(allocation, executeFunction->GetHasImplicitArgIns(), doProfile, loopHeaderArray, stackAddr);
  1490. #endif
  1491. newInstance->m_reader.Create(executeFunction);
  1492. generator->SetFrame(newInstance, varSizeInBytes);
  1493. return newInstance;
  1494. }
  1495. Var InterpreterStackFrame::InterpreterHelper(ScriptFunction* function, ArgumentReader args, void* returnAddress, void* addressOfReturnAddress, AsmJsReturnStruct* asmJsReturn)
  1496. {
  1497. const bool isAsmJs = asmJsReturn != nullptr;
  1498. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  1499. // Support for simulating partially initialized interpreter stack frame.
  1500. InterpreterThunkStackCountTracker tracker;
  1501. if (CONFIG_ISENABLED(InjectPartiallyInitializedInterpreterFrameErrorFlag) &&
  1502. CONFIG_FLAG(InjectPartiallyInitializedInterpreterFrameError) == InterpreterThunkStackCountTracker::GetCount())
  1503. {
  1504. switch (CONFIG_FLAG(InjectPartiallyInitializedInterpreterFrameErrorType))
  1505. {
  1506. case 0:
  1507. DebugBreak();
  1508. break;
  1509. case 1:
  1510. Js::JavascriptError::MapAndThrowError(function->GetScriptContext(), VBSERR_InternalError);
  1511. break;
  1512. default:
  1513. DebugBreak();
  1514. }
  1515. }
  1516. #endif
  1517. ScriptContext* functionScriptContext = function->GetScriptContext();
  1518. ThreadContext * threadContext = functionScriptContext->GetThreadContext();
  1519. Assert(!threadContext->IsDisableImplicitException());
  1520. functionScriptContext->VerifyAlive(!function->IsExternal());
  1521. Assert(threadContext->IsScriptActive());
  1522. Assert(threadContext->IsInScript());
  1523. FunctionBody* executeFunction = JavascriptFunction::UnsafeFromVar(function)->GetFunctionBody();
  1524. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  1525. if (!isAsmJs && executeFunction->IsInDebugMode() != functionScriptContext->IsScriptContextInDebugMode()) // debug mode mismatch
  1526. {
  1527. if (executeFunction->GetUtf8SourceInfo()->GetIsLibraryCode())
  1528. {
  1529. Assert(!executeFunction->IsInDebugMode()); // Library script byteCode is never in debug mode
  1530. }
  1531. else
  1532. {
  1533. Throw::FatalInternalError();
  1534. }
  1535. }
  1536. #endif
  1537. if (executeFunction->GetInterpretedCount() == 0)
  1538. {
  1539. executeFunction->TraceInterpreterExecutionMode();
  1540. }
  1541. class AutoRestore
  1542. {
  1543. private:
  1544. ThreadContext *const threadContext;
  1545. const uint8 savedLoopDepth;
  1546. public:
  1547. AutoRestore(ThreadContext *const threadContext, FunctionBody *const executeFunction)
  1548. : threadContext(threadContext),
  1549. savedLoopDepth(threadContext->LoopDepth())
  1550. {
  1551. if (savedLoopDepth != 0 && !executeFunction->GetIsAsmJsFunction())
  1552. {
  1553. executeFunction->SetWasCalledFromLoop();
  1554. }
  1555. }
  1556. ~AutoRestore()
  1557. {
  1558. threadContext->SetLoopDepth(savedLoopDepth);
  1559. }
  1560. } autoRestore(threadContext, executeFunction);
  1561. #if ENABLE_PROFILE_INFO
  1562. DynamicProfileInfo * dynamicProfileInfo = nullptr;
  1563. const bool doProfile = ShouldDoProfile(executeFunction);
  1564. if (doProfile)
  1565. {
  1566. #if !DYNAMIC_INTERPRETER_THUNK
  1567. executeFunction->EnsureDynamicProfileInfo();
  1568. #endif
  1569. dynamicProfileInfo = executeFunction->GetDynamicProfileInfo();
  1570. threadContext->ClearImplicitCallFlags();
  1571. }
  1572. #else
  1573. const bool doProfile = false;
  1574. #endif
  1575. executeFunction->IncreaseInterpretedCount();
  1576. #ifdef BGJIT_STATS
  1577. functionScriptContext->interpretedCount++;
  1578. functionScriptContext->maxFuncInterpret = max(functionScriptContext->maxFuncInterpret, executeFunction->GetInterpretedCount());
  1579. #endif
  1580. AssertMsg(!executeFunction->IsDeferredParseFunction(),
  1581. "Non-intrinsic functions must provide byte-code to execute");
  1582. executeFunction->BeginExecution();
  1583. bool fReleaseAlloc = false;
  1584. InterpreterStackFrame* newInstance = nullptr;
  1585. if (!isAsmJs && executeFunction->IsCoroutine())
  1586. {
  1587. // If the FunctionBody is a generator then this call is being made by one of the three
  1588. // generator resuming methods: next(), throw(), or return(). They all pass the generator
  1589. // object as the first of two arguments. The real user arguments are obtained from the
  1590. // generator object. The second argument is the ResumeYieldData which is only needed
  1591. // when resuming a generator and so it only used here if a frame already exists on the
  1592. // generator object.
  1593. AssertOrFailFastMsg(args.Info.Count == 2 && ((args.Info.Flags & CallFlags_ExtraArg) == CallFlags_None), "Generator ScriptFunctions should only be invoked by generator APIs with the pair of arguments they pass in -- the generator object and a ResumeYieldData pointer");
  1594. JavascriptGenerator* generator = JavascriptGenerator::FromVar(args[0]);
  1595. newInstance = generator->GetFrame();
  1596. if (newInstance != nullptr)
  1597. {
  1598. ResumeYieldData* resumeYieldData = static_cast<ResumeYieldData*>(args[1]);
  1599. newInstance->SetNonVarReg(executeFunction->GetYieldRegister(), resumeYieldData);
  1600. // The debugger relies on comparing stack addresses of frames to decide when a step_out is complete so
  1601. // give the InterpreterStackFrame a legit enough stack address to make this comparison work.
  1602. newInstance->m_stackAddress = reinterpret_cast<DWORD_PTR>(&generator);
  1603. }
  1604. else
  1605. {
  1606. newInstance = CreateInterpreterStackFrameForGenerator(function, executeFunction, generator, doProfile);
  1607. }
  1608. }
  1609. else
  1610. {
  1611. InterpreterStackFrame::Setup setup(function, args);
  1612. size_t varAllocCount = setup.GetAllocationVarCount();
  1613. size_t varSizeInBytes = varAllocCount * sizeof(Var);
  1614. //
  1615. // Allocate a new InterpreterStackFrame instance on the interpreter's virtual stack.
  1616. //
  1617. DWORD_PTR stackAddr;
  1618. Var* allocation;
  1619. // If the locals area exceeds a certain limit, allocate it from a private arena rather than
  1620. // this frame. The current limit is based on an old assert on the number of locals we would allow here.
  1621. if (varAllocCount > InterpreterStackFrame::LocalsThreshold)
  1622. {
  1623. ArenaAllocator *tmpAlloc = nullptr;
  1624. fReleaseAlloc = functionScriptContext->EnsureInterpreterArena(&tmpAlloc);
  1625. allocation = (Var*)tmpAlloc->Alloc(varSizeInBytes);
  1626. stackAddr = reinterpret_cast<DWORD_PTR>(&allocation); // use a stack address so the debugger stepping logic works (step-out, for example, compares stack depths to determine when to complete the step)
  1627. }
  1628. else
  1629. {
  1630. PROBE_STACK_PARTIAL_INITIALIZED_INTERPRETER_FRAME(functionScriptContext, Js::Constants::MinStackInterpreter + varSizeInBytes);
  1631. allocation = (Var*)_alloca(varSizeInBytes);
  1632. #if DBG
  1633. memset(allocation, 0xFE, varSizeInBytes);
  1634. #endif
  1635. stackAddr = reinterpret_cast<DWORD_PTR>(allocation);
  1636. }
  1637. /*
  1638. * If the function has any loop headers, we allocate an array for the loop headers wrappers, and
  1639. * reference the wrappers in the array. We then push the pointer to the array onto the stack itself.
  1640. * We do this so that while the function is being interpreted, we don't want the jitted loop
  1641. * bodies to be collected, even if the loop body isn't being executed. The loop body will
  1642. * get collected when the function has been JITted, and when the function exits the interpreter.
  1643. * The array contains nulls if the loop body isn't jitted (or hasn't been jitted yet) but
  1644. * it's cheaper to just copy them all into the recycler array rather than just the ones that
  1645. * have been jitted.
  1646. */
  1647. LoopHeader* loopHeaderArray = nullptr;
  1648. if (executeFunction->GetHasAllocatedLoopHeaders())
  1649. {
  1650. // Loop header array is recycler allocated, so we push it on the stack
  1651. // When we scan the stack, we'll recognize it as a recycler allocated
  1652. // object, and mark it's contents and keep the individual loop header
  1653. // wrappers alive
  1654. loopHeaderArray = executeFunction->GetLoopHeaderArrayPtr();
  1655. }
  1656. #if DBG
  1657. Js::RecyclableObject * invalidStackVar = (Js::RecyclableObject*)_alloca(sizeof(Js::RecyclableObject));
  1658. memset(reinterpret_cast<void*>(invalidStackVar), 0xFE, sizeof(Js::RecyclableObject));
  1659. newInstance = setup.InitializeAllocation(allocation, executeFunction->GetHasImplicitArgIns() && !isAsmJs, doProfile, loopHeaderArray, stackAddr, invalidStackVar);
  1660. #else
  1661. newInstance = setup.InitializeAllocation(allocation, executeFunction->GetHasImplicitArgIns() && !isAsmJs, doProfile, loopHeaderArray, stackAddr);
  1662. #endif
  1663. newInstance->m_reader.Create(executeFunction);
  1664. }
  1665. //
  1666. // Execute the function's byte-code, returning the return-value:
  1667. // - Mark that the function is current executing and may not be modified.
  1668. //
  1669. #if ENABLE_TTD
  1670. TTD::TTDExceptionFramePopper exceptionFramePopper;
  1671. if(SHOULD_DO_TTD_STACK_STMT_OP(functionScriptContext))
  1672. {
  1673. bool isInFinally = newInstance->TestFlags(Js::InterpreterStackFrameFlags_WithinFinallyBlock);
  1674. threadContext->TTDExecutionInfo->PushCallEvent(function, args.Info.Count, args.Values, isInFinally);
  1675. exceptionFramePopper.PushInfo(threadContext->TTDExecutionInfo, function);
  1676. }
  1677. #endif
  1678. Var aReturn = nullptr;
  1679. {
  1680. #ifdef ENABLE_SCRIPT_DEBUGGING
  1681. if (!isAsmJs && executeFunction->IsInDebugMode())
  1682. {
  1683. #if DYNAMIC_INTERPRETER_THUNK
  1684. PushPopFrameHelper pushPopFrameHelper(newInstance, returnAddress, addressOfReturnAddress);
  1685. aReturn = newInstance->DebugProcess();
  1686. #else
  1687. aReturn = newInstance->DebugProcessThunk(_ReturnAddress(), _AddressOfReturnAddress());
  1688. #endif
  1689. }
  1690. else
  1691. #endif
  1692. {
  1693. #if DYNAMIC_INTERPRETER_THUNK
  1694. PushPopFrameHelper pushPopFrameHelper(newInstance, returnAddress, addressOfReturnAddress);
  1695. aReturn = newInstance->Process();
  1696. #else
  1697. aReturn = newInstance->ProcessThunk(_ReturnAddress(), _AddressOfReturnAddress());
  1698. #endif
  1699. }
  1700. }
  1701. executeFunction->EndExecution();
  1702. #if ENABLE_TTD
  1703. if(SHOULD_DO_TTD_STACK_STMT_OP(functionScriptContext))
  1704. {
  1705. exceptionFramePopper.PopInfo();
  1706. threadContext->TTDExecutionInfo->PopCallEvent(function, aReturn);
  1707. }
  1708. #endif
  1709. #ifdef ASMJS_PLAT
  1710. if (isAsmJs)
  1711. {
  1712. asmJsReturn->i = newInstance->GetRegRawInt(0);
  1713. asmJsReturn->l = newInstance->GetRegRawInt64(0);
  1714. asmJsReturn->d = newInstance->GetRegRawDouble(0);
  1715. asmJsReturn->f = newInstance->GetRegRawFloat(0);
  1716. asmJsReturn->simd = newInstance->GetRegRawSimd(0);
  1717. }
  1718. #endif
  1719. if (fReleaseAlloc)
  1720. {
  1721. functionScriptContext->ReleaseInterpreterArena();
  1722. }
  1723. #if ENABLE_PROFILE_INFO
  1724. if (doProfile)
  1725. {
  1726. dynamicProfileInfo->RecordImplicitCallFlags(threadContext->GetImplicitCallFlags());
  1727. }
  1728. #endif
  1729. return aReturn;
  1730. }
  1731. #ifdef ASMJS_PLAT
  1732. #if _M_IX86
  1733. void InterpreterStackFrame::AsmJsInterpreter(AsmJsCallStackLayout* stack, byte* retDst)
  1734. {
  1735. ScriptFunction * function = (ScriptFunction*)stack->functionObject;
  1736. Var* paramsAddr = stack->args;
  1737. int flags = CallFlags_Value;
  1738. ArgSlot nbArgs = ArgSlotMath::Add(function->GetFunctionBody()->GetAsmJsFunctionInfo()->GetArgCount(), 1);
  1739. CallInfo callInfo((CallFlags)flags, nbArgs);
  1740. ArgumentReader args(&callInfo, paramsAddr);
  1741. void* returnAddress = _ReturnAddress();
  1742. void* addressOfReturnAddress = _AddressOfReturnAddress();
  1743. #if ENABLE_PROFILE_INFO
  1744. function->GetFunctionBody()->EnsureDynamicProfileInfo();
  1745. #endif
  1746. AsmJsReturnStruct asmJsReturn = { 0 };
  1747. InterpreterHelper(function, args, returnAddress, addressOfReturnAddress, &asmJsReturn);
  1748. //Handle return value
  1749. AsmJsRetType::Which retType = (AsmJsRetType::Which) GetRetType(function);
  1750. switch (retType)
  1751. {
  1752. #ifdef ENABLE_WASM_SIMD
  1753. case AsmJsRetType::Int32x4:
  1754. case AsmJsRetType::Bool32x4:
  1755. case AsmJsRetType::Bool16x8:
  1756. case AsmJsRetType::Bool8x16:
  1757. case AsmJsRetType::Float32x4:
  1758. case AsmJsRetType::Float64x2:
  1759. case AsmJsRetType::Int16x8:
  1760. case AsmJsRetType::Int8x16:
  1761. case AsmJsRetType::Uint32x4:
  1762. case AsmJsRetType::Uint16x8:
  1763. case AsmJsRetType::Uint8x16:
  1764. Assert(Wasm::Simd::IsEnabled());
  1765. *(AsmJsSIMDValue*)retDst = asmJsReturn.simd;
  1766. break;
  1767. #endif
  1768. // double return
  1769. case AsmJsRetType::Double:
  1770. *(double*)retDst = asmJsReturn.d;
  1771. break;
  1772. // float return
  1773. case AsmJsRetType::Float:
  1774. *(float*)retDst = asmJsReturn.f;
  1775. break;
  1776. // signed or void return
  1777. case AsmJsRetType::Signed:
  1778. case AsmJsRetType::Void:
  1779. *(int*)retDst = asmJsReturn.i;
  1780. break;
  1781. case AsmJsRetType::Int64:
  1782. *(int64*)retDst = asmJsReturn.l;
  1783. break;
  1784. default:
  1785. Assume(false);
  1786. }
  1787. }
  1788. #elif _M_X64
  1789. typedef double(*AsmJsInterpreterDoubleEP)(AsmJsCallStackLayout*, void *);
  1790. typedef float(*AsmJsInterpreterFloatEP)(AsmJsCallStackLayout*, void *);
  1791. typedef int(*AsmJsInterpreterIntEP)(AsmJsCallStackLayout*, void *);
  1792. typedef int64(*AsmJsInterpreterInt64EP)(AsmJsCallStackLayout*, void *);
  1793. void * InterpreterStackFrame::GetAsmJsInterpreterEntryPoint(AsmJsCallStackLayout* stack)
  1794. {
  1795. JavascriptFunction * function = stack->functionObject;
  1796. void * entryPoint = nullptr;
  1797. switch (function->GetFunctionBody()->GetAsmJsFunctionInfo()->GetReturnType().which())
  1798. {
  1799. case Js::AsmJsRetType::Double:
  1800. {
  1801. entryPoint = (void*)(AsmJsInterpreterDoubleEP)Js::InterpreterStackFrame::AsmJsInterpreter < double > ;
  1802. break;
  1803. }
  1804. case Js::AsmJsRetType::Float:
  1805. {
  1806. entryPoint = (void*)(AsmJsInterpreterFloatEP)Js::InterpreterStackFrame::AsmJsInterpreter < float > ;
  1807. break;
  1808. }
  1809. case Js::AsmJsRetType::Signed:
  1810. case Js::AsmJsRetType::Void:
  1811. {
  1812. entryPoint = (void*)(AsmJsInterpreterIntEP)Js::InterpreterStackFrame::AsmJsInterpreter < int > ;
  1813. break;
  1814. }
  1815. case Js::AsmJsRetType::Int64:
  1816. {
  1817. entryPoint = (void*)(AsmJsInterpreterInt64EP)Js::InterpreterStackFrame::AsmJsInterpreter < int64 > ;
  1818. break;
  1819. }
  1820. #ifdef ENABLE_WASM_SIMD
  1821. case Js::AsmJsRetType::Int32x4:
  1822. case Js::AsmJsRetType::Bool32x4:
  1823. case Js::AsmJsRetType::Bool16x8:
  1824. case Js::AsmJsRetType::Bool8x16:
  1825. case Js::AsmJsRetType::Float32x4:
  1826. case Js::AsmJsRetType::Float64x2:
  1827. case Js::AsmJsRetType::Int16x8:
  1828. case Js::AsmJsRetType::Int8x16:
  1829. case Js::AsmJsRetType::Uint32x4:
  1830. case Js::AsmJsRetType::Uint16x8:
  1831. case Js::AsmJsRetType::Uint8x16:
  1832. {
  1833. entryPoint = (void*)Js::InterpreterStackFrame::AsmJsInterpreterSimdJs;
  1834. break;
  1835. }
  1836. #endif
  1837. default:
  1838. Assume(UNREACHED);
  1839. }
  1840. return entryPoint;
  1841. }
  1842. template<typename T>
  1843. T InterpreterStackFrame::AsmJsInterpreter(AsmJsCallStackLayout* layout)
  1844. {
  1845. Js::ScriptFunction * function = Js::ScriptFunction::FromVar(layout->functionObject);
  1846. int flags = CallFlags_Value;
  1847. ArgSlot nbArgs = ArgSlotMath::Add(function->GetFunctionBody()->GetAsmJsFunctionInfo()->GetArgCount(), 1);
  1848. CallInfo callInfo((CallFlags)flags, nbArgs);
  1849. ArgumentReader args(&callInfo, (Var*)layout->args);
  1850. void* returnAddress = _ReturnAddress();
  1851. void* addressOfReturnAddress = _AddressOfReturnAddress();
  1852. function->GetFunctionBody()->EnsureDynamicProfileInfo();
  1853. AsmJsReturnStruct asmJsReturn = { 0 };
  1854. InterpreterHelper(function, args, returnAddress, addressOfReturnAddress, &asmJsReturn);
  1855. return asmJsReturn.GetRetVal<T>();
  1856. }
  1857. __m128 InterpreterStackFrame::AsmJsInterpreterSimdJs(AsmJsCallStackLayout* layout)
  1858. {
  1859. return AsmJsInterpreter<X86SIMDValue>(layout).m128_value;
  1860. }
  1861. #endif
  1862. #endif
  1863. ///----------------------------------------------------------------------------
  1864. ///
  1865. /// InterpreterStackFrame::SetOut()
  1866. ///
  1867. /// SetOut() change the Var value stored in the specified "out parameter"
  1868. /// register.
  1869. ///
  1870. ///----------------------------------------------------------------------------
  1871. inline void InterpreterStackFrame::SetOut(ArgSlot outRegisterID, Var aValue)
  1872. {
  1873. //
  1874. // The "out" parameter slots are located at the end of the local register range, counting
  1875. // forwards. This results in the "in" parameter slots being disjoint from the rest of the
  1876. // InterpreterStackFrame.
  1877. // ..., InterpreterStackFrame A, Locals A[], ..., Out A:0, Out A:1, Out A:2, ...
  1878. // | In B:0, In B:1, ..., InterpreterStackFrame B, Locals B[], ...
  1879. // (current 'this') |
  1880. // (new 'this' after call)
  1881. //
  1882. Assert(m_outParams + outRegisterID < m_outSp);
  1883. m_outParams[outRegisterID] = aValue;
  1884. }
  1885. inline void InterpreterStackFrame::SetOut(ArgSlot_OneByte outRegisterID, Var aValue)
  1886. {
  1887. Assert(m_outParams + outRegisterID < m_outSp);
  1888. m_outParams[outRegisterID] = aValue;
  1889. }
  1890. inline void InterpreterStackFrame::OP_SetOutAsmDb( RegSlot outRegisterID, double val )
  1891. {
  1892. Assert(m_outParams + outRegisterID < m_outSp);
  1893. m_outParams[outRegisterID] = JavascriptNumber::NewWithCheck( val, scriptContext );
  1894. }
  1895. inline void InterpreterStackFrame::OP_SetOutAsmInt( RegSlot outRegisterID, int val )
  1896. {
  1897. Assert( m_outParams + outRegisterID < m_outSp );
  1898. m_outParams[outRegisterID] = JavascriptNumber::ToVar( val, scriptContext );
  1899. }
  1900. void InterpreterStackFrame::OP_SetOutAsmFlt(RegSlot outRegisterID, float val)
  1901. {
  1902. OP_SetOutAsmDb(outRegisterID, (double)val);
  1903. }
  1904. inline void InterpreterStackFrame::OP_I_SetOutAsmFlt(RegSlot outRegisterID, float val)
  1905. {
  1906. Assert(m_outParams + outRegisterID < m_outSp);
  1907. *(float*)(&(m_outParams[outRegisterID])) = val;
  1908. }
  1909. inline void InterpreterStackFrame::OP_I_SetOutAsmLong(RegSlot outRegisterID, int64 val)
  1910. {
  1911. Assert(m_outParams + outRegisterID < m_outSp);
  1912. *(int64*)(&(m_outParams[outRegisterID])) = val;
  1913. }
  1914. inline void InterpreterStackFrame::OP_I_SetOutAsmInt(RegSlot outRegisterID, int val)
  1915. {
  1916. Assert(m_outParams + outRegisterID < m_outSp);
  1917. *(int*)(&(m_outParams[outRegisterID])) = val;
  1918. }
  1919. inline void InterpreterStackFrame::OP_I_SetOutAsmDb(RegSlot outRegisterID, double val)
  1920. {
  1921. Assert(m_outParams + outRegisterID < m_outSp);
  1922. *(double*)(&(m_outParams[outRegisterID])) = val;
  1923. }
  1924. inline void InterpreterStackFrame::OP_I_SetOutAsmSimd(RegSlot outRegisterID, AsmJsSIMDValue val)
  1925. {
  1926. Assert(m_outParams + outRegisterID < m_outSp);
  1927. *(AsmJsSIMDValue*)(&(m_outParams[outRegisterID])) = val;
  1928. }
  1929. template<int type, bool toJs>
  1930. void InterpreterStackFrame::OP_InvalidWasmTypeConversion(...)
  1931. {
  1932. #ifdef ENABLE_WASM
  1933. CompileAssert(type < Wasm::WasmTypes::Limit);
  1934. const char16* fromType = toJs ? Wasm::WasmTypes::GetTypeName(static_cast<Wasm::WasmTypes::WasmType>(type)) : _u("Javascript Variable");
  1935. const char16* toType = toJs ? _u("Javascript Variable") : Wasm::WasmTypes::GetTypeName(static_cast<Wasm::WasmTypes::WasmType>(type));
  1936. JavascriptError::ThrowTypeErrorVar(scriptContext, WASMERR_InvalidTypeConversion, fromType, toType);
  1937. #else
  1938. Assert(UNREACHED); //shouldn't get there
  1939. JavascriptError::ThrowTypeErrorVar(scriptContext, WASMERR_InvalidTypeConversion, _u("unknown"), _u("unknown")); //throw for a release build
  1940. #endif
  1941. }
  1942. // This will be called in the beginning of the try_finally.
  1943. inline void InterpreterStackFrame::CacheSp()
  1944. {
  1945. // Before caching the current m_outSp, we will be storing the previous the previously stored value in the m_outSpCached.
  1946. *m_outSp++ = (Var)m_outSpCached;
  1947. *m_outSp++ = (Var)m_outParams;
  1948. m_outSpCached = m_outSp - 2;
  1949. }
  1950. inline void InterpreterStackFrame::RestoreSp()
  1951. {
  1952. // This will be called in the Finally block to restore from the previous SP cached.
  1953. // m_outSpCached can be null if the catch block is called.
  1954. if (m_outSpCached != nullptr)
  1955. {
  1956. Assert(m_outSpCached < m_outSp);
  1957. m_outSp = m_outSpCached;
  1958. m_outSpCached = (Var*)*m_outSp;
  1959. Assert(m_outSpCached == nullptr || m_outSpCached <= m_outSp);
  1960. m_outParams = (Var*)*(m_outSp + 1);
  1961. }
  1962. else
  1963. {
  1964. ResetOut();
  1965. }
  1966. }
  1967. inline void InterpreterStackFrame::PushOut(Var aValue)
  1968. {
  1969. *m_outSp++ = aValue;
  1970. }
  1971. inline void InterpreterStackFrame::PopOut(ArgSlot argCount)
  1972. {
  1973. ArgSlotMath::Inc(argCount);
  1974. m_outSp -= argCount;
  1975. m_outParams = (Var*)*m_outSp;
  1976. AssertMsg(m_localSlots + this->m_functionBody->GetLocalsCount() <= m_outSp &&
  1977. m_outSp < (m_localSlots + this->m_functionBody->GetLocalsCount() + this->m_functionBody->GetOutParamMaxDepth()),
  1978. "out args Stack pointer not in range after Pop");
  1979. }
  1980. void InterpreterStackFrame::ResetOut()
  1981. {
  1982. //
  1983. // Reset the m_outParams and m_outSp
  1984. //
  1985. m_outParams = m_localSlots + this->m_functionBody->GetLocalsCount();
  1986. m_outSp = m_outParams;
  1987. m_outSpCached = nullptr;
  1988. }
  1989. #ifdef ENABLE_SCRIPT_DEBUGGING
  1990. _NOINLINE
  1991. Var InterpreterStackFrame::DebugProcessThunk(void* returnAddress, void* addressOfReturnAddress)
  1992. {
  1993. PushPopFrameHelper pushPopFrameHelper(this, returnAddress, addressOfReturnAddress);
  1994. return this->DebugProcess();
  1995. }
  1996. //
  1997. // Under debug mode allow the exception to be swallowed and execution to continue
  1998. // if the debugger has specified that behavior.
  1999. //
  2000. Var InterpreterStackFrame::DebugProcess()
  2001. {
  2002. Assert(this->returnAddress != nullptr);
  2003. while (true)
  2004. {
  2005. JavascriptExceptionObject *exception = nullptr;
  2006. try
  2007. {
  2008. #if ENABLE_TTD
  2009. if(SHOULD_DO_TTD_STACK_STMT_OP(this->scriptContext))
  2010. {
  2011. return this->ProcessWithDebugging_PreviousStmtTracking();
  2012. }
  2013. else
  2014. {
  2015. return this->ProcessWithDebugging();
  2016. }
  2017. #else
  2018. return this->ProcessWithDebugging();
  2019. #endif
  2020. }
  2021. catch (const Js::JavascriptException& err)
  2022. {
  2023. JavascriptExceptionObject *exception_ = err.GetAndClear();
  2024. Assert(exception_);
  2025. exception = exception_;
  2026. }
  2027. if (exception)
  2028. {
  2029. bool skipException = false;
  2030. if (exception != scriptContext->GetThreadContext()->GetPendingSOErrorObject()
  2031. && exception != scriptContext->GetThreadContext()->GetPendingOOMErrorObject())
  2032. {
  2033. skipException = exception->IsDebuggerSkip();
  2034. }
  2035. if (skipException)
  2036. {
  2037. // If we are going to swallow the exception then advance to the beginning of the next user statement
  2038. if (exception->IsIgnoreAdvanceToNextStatement()
  2039. || this->scriptContext->GetDebugContext()->GetProbeContainer()->AdvanceToNextUserStatement(this->m_functionBody, &this->m_reader))
  2040. {
  2041. // We must fix up the return value to at least be undefined:
  2042. this->SetReg((RegSlot)0,this->scriptContext->GetLibrary()->GetUndefined());
  2043. // If we recover from the exception, there may be a chance the out pointers in the InterpreterStackframe are not in a proper state.
  2044. // Reset them to correct the stack.
  2045. ResetOut();
  2046. // If we can successfully advance then continuing processing
  2047. continue;
  2048. }
  2049. }
  2050. JavascriptExceptionOperators::DoThrowCheckClone(exception, scriptContext);
  2051. }
  2052. }
  2053. }
  2054. #endif
  2055. template<typename OpCodeType, Js::OpCode (ReadOpFunc)(const byte*&), void (TracingFunc)(InterpreterStackFrame*, OpCodeType)>
  2056. OpCodeType InterpreterStackFrame::ReadOp(const byte *& ip)
  2057. {
  2058. #if DBG || DBG_DUMP
  2059. //
  2060. // For debugging byte-code, store the current offset before the instruction is read:
  2061. // - We convert this to "void *" to encourage the debugger to always display in hex,
  2062. // which matches the displayed offsets used by ByteCodeDumper.
  2063. //
  2064. this->DEBUG_currentByteOffset = (void *) m_reader.GetCurrentOffset();
  2065. #endif
  2066. OpCodeType op = (OpCodeType)ReadOpFunc(ip);
  2067. #if DBG_DUMP
  2068. TracingFunc(this, op);
  2069. #endif
  2070. return op;
  2071. }
  2072. void InterpreterStackFrame::TraceOpCode(InterpreterStackFrame* that, Js::OpCode op)
  2073. {
  2074. #if DBG_DUMP
  2075. that->scriptContext->byteCodeHistogram[(int)op]++;
  2076. if (PHASE_TRACE(Js::InterpreterPhase, that->m_functionBody))
  2077. {
  2078. Output::Print(_u("%d.%d:Executing %s at offset 0x%X\n"), that->m_functionBody->GetSourceContextId(), that->m_functionBody->GetLocalFunctionId(), Js::OpCodeUtil::GetOpCodeName(op), that->DEBUG_currentByteOffset);
  2079. }
  2080. #endif
  2081. }
  2082. void InterpreterStackFrame::TraceAsmJsOpCode(InterpreterStackFrame* that, Js::OpCodeAsmJs op)
  2083. {
  2084. #if DBG_DUMP && defined(ASMJS_PLAT)
  2085. if(PHASE_TRACE(Js::AsmjsInterpreterPhase, that->m_functionBody))
  2086. {
  2087. Output::Print(_u("%d.%d:Executing %s at offset 0x%X\n"), that->m_functionBody->GetSourceContextId(), that->m_functionBody->GetLocalFunctionId(), Js::OpCodeUtilAsmJs::GetOpCodeName(op), that->DEBUG_currentByteOffset);
  2088. }
  2089. #endif
  2090. }
  2091. #if ENABLE_TTD
  2092. template<typename OpCodeType, Js::OpCode(ReadOpFunc)(const byte*&), void (TracingFunc)(InterpreterStackFrame*, OpCodeType)>
  2093. OpCodeType InterpreterStackFrame::ReadOp_WPreviousStmtTracking(const byte *& ip)
  2094. {
  2095. #if DBG || DBG_DUMP
  2096. //
  2097. // For debugging byte-code, store the current offset before the instruction is read:
  2098. // - We convert this to "void *" to encourage the debugger to always display in hex,
  2099. // which matches the displayed offsets used by ByteCodeDumper.
  2100. //
  2101. this->DEBUG_currentByteOffset = (void *)m_reader.GetCurrentOffset();
  2102. #endif
  2103. #if ENABLE_TTD
  2104. AssertMsg(this->scriptContext->GetThreadContext()->IsRuntimeInTTDMode(), "We never be fetching an opcode via this path if this is not true!!!");
  2105. #endif
  2106. if(SHOULD_DO_TTD_STACK_STMT_OP(this->scriptContext))
  2107. {
  2108. TTD::ExecutionInfoManager* executionMgr = this->scriptContext->GetThreadContext()->TTDExecutionInfo;
  2109. executionMgr->UpdateCurrentStatementInfo(m_reader.GetCurrentOffset());
  2110. }
  2111. OpCodeType op = (OpCodeType)ReadOpFunc(ip);
  2112. #if DBG_DUMP
  2113. TracingFunc(this, op);
  2114. #endif
  2115. return op;
  2116. }
  2117. #endif
  2118. _NOINLINE
  2119. Var InterpreterStackFrame::ProcessThunk(void* address, void* addressOfReturnAddress)
  2120. {
  2121. PushPopFrameHelper pushPopFrameHelper(this, address, addressOfReturnAddress);
  2122. return this->Process();
  2123. }
  2124. #ifdef ASMJS_PLAT
  2125. Var InterpreterStackFrame::ProcessAsmJsModule()
  2126. {
  2127. FunctionBody* asmJsModuleFunctionBody = GetFunctionBody();
  2128. AsmJsModuleInfo* info = asmJsModuleFunctionBody->GetAsmJsModuleInfo();
  2129. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2130. if (Configuration::Global.flags.ForceAsmJsLinkFail)
  2131. {
  2132. AsmJSCompiler::OutputError(this->scriptContext, _u("Asm.js Runtime Error : Forcing link failure"));
  2133. return this->ProcessLinkFailedAsmJsModule();
  2134. }
  2135. #endif
  2136. if (m_inSlotsCount != info->GetArgInCount() + 1)
  2137. {
  2138. // Error reparse without asm.js
  2139. AsmJSCompiler::OutputError(this->scriptContext, _u("Asm.js Runtime Error : Invalid module argument count"));
  2140. return this->ProcessLinkFailedAsmJsModule();
  2141. }
  2142. const AsmJsModuleMemory& moduleMemory = info->GetModuleMemory();
  2143. Field(Var)* moduleMemoryPtr = RecyclerNewArray(scriptContext->GetRecycler(), Field(Var), moduleMemory.mMemorySize);
  2144. Field(Var)* arrayBufferPtr = moduleMemoryPtr + moduleMemory.mArrayBufferOffset;
  2145. Assert(moduleMemory.mArrayBufferOffset == AsmJsModuleMemory::MemoryTableBeginOffset);
  2146. Field(Var)* stdLibPtr = moduleMemoryPtr + moduleMemory.mStdLibOffset;
  2147. int* localIntSlots = (int*)(moduleMemoryPtr + moduleMemory.mIntOffset);
  2148. float* localFloatSlots = (float*)(moduleMemoryPtr + moduleMemory.mFloatOffset);
  2149. double* localDoubleSlots = (double*)(moduleMemoryPtr + moduleMemory.mDoubleOffset);
  2150. Field(Var)* localFunctionImports = moduleMemoryPtr + moduleMemory.mFFIOffset ;
  2151. Field(Var)* localModuleFunctions = moduleMemoryPtr + moduleMemory.mFuncOffset ;
  2152. Field(Field(Var)*)* localFunctionTables = (Field(Field(Var)*)*)(moduleMemoryPtr + moduleMemory.mFuncPtrOffset) ;
  2153. ThreadContext* threadContext = this->scriptContext->GetThreadContext();
  2154. *stdLibPtr = (m_inSlotsCount > 1) ? m_inParams[1] : nullptr;
  2155. Var foreign = (m_inSlotsCount > 2) ? m_inParams[2] : nullptr;
  2156. *arrayBufferPtr = (m_inSlotsCount > 3) ? m_inParams[3] : nullptr;
  2157. //cache the current state of the disable implicit call flag
  2158. DisableImplicitFlags prevDisableImplicitFlags = threadContext->GetDisableImplicitFlags();
  2159. ImplicitCallFlags saveImplicitcallFlags = threadContext->GetImplicitCallFlags();
  2160. // Disable implicit calls to check if any of the VarImport or Function Import leads to implicit calls
  2161. threadContext->DisableImplicitCall();
  2162. threadContext->SetImplicitCallFlags(ImplicitCallFlags::ImplicitCall_None);
  2163. bool checkParamResult = ASMLink::CheckParams(this->scriptContext, info, *stdLibPtr, foreign, *arrayBufferPtr);
  2164. if (!checkParamResult)
  2165. {
  2166. // don't need to print, because checkParams will do it for us
  2167. goto linkFailure;
  2168. }
  2169. else if (this->CheckAndResetImplicitCall(prevDisableImplicitFlags, saveImplicitcallFlags))
  2170. {
  2171. AsmJSCompiler::OutputError(this->scriptContext, _u("Asm.js Runtime Error : Params have side effects"));
  2172. return this->ProcessLinkFailedAsmJsModule();
  2173. }
  2174. // Initialize Variables
  2175. for (int i = 0; i < info->GetVarCount(); i++)
  2176. {
  2177. const auto& var = info->GetVar(i);
  2178. const AsmJsVarType type(var.type);
  2179. if (type.isInt())
  2180. {
  2181. localIntSlots[var.location] = var.initialiser.intInit;
  2182. }
  2183. else if (type.isFloat())
  2184. {
  2185. localFloatSlots[var.location] = var.initialiser.floatInit;
  2186. }
  2187. else if (type.isDouble())
  2188. {
  2189. localDoubleSlots[var.location] = var.initialiser.doubleInit;
  2190. }
  2191. else
  2192. {
  2193. Assert(UNREACHED);
  2194. }
  2195. }
  2196. // Load constant variables
  2197. for (int i = 0; i < info->GetVarImportCount(); i++)
  2198. {
  2199. const auto& import = info->GetVarImport(i);
  2200. const AsmJsVarType type(import.type);
  2201. // this might throw, but it would anyway in non-asm.js
  2202. Var value = JavascriptOperators::OP_GetProperty(foreign, import.field, scriptContext);
  2203. // check if there is implicit call and if there is implicit call then clear the disableimplicitcall flag
  2204. if (this->CheckAndResetImplicitCall(prevDisableImplicitFlags, saveImplicitcallFlags))
  2205. {
  2206. AsmJSCompiler::OutputError(this->scriptContext, _u("Asm.js Runtime Error : Accessing var import %s has side effects"), this->scriptContext->GetPropertyName(import.field)->GetBuffer());
  2207. return this->ProcessLinkFailedAsmJsModule();
  2208. }
  2209. if (CONFIG_FLAG(AsmJsEdge))
  2210. {
  2211. // emscripten had a bug which caused this check to fail in some circumstances, so this check fails for some demos
  2212. if (!TaggedNumber::Is(value) && (!RecyclableObject::Is(value) || DynamicType::Is(RecyclableObject::FromVar(value)->GetTypeId())))
  2213. {
  2214. AsmJSCompiler::OutputError(this->scriptContext, _u("Asm.js Runtime Error : Var import %s must be primitive"), this->scriptContext->GetPropertyName(import.field)->GetBuffer());
  2215. goto linkFailure;
  2216. }
  2217. }
  2218. if (type.isInt())
  2219. {
  2220. int val = JavascriptMath::ToInt32(value, scriptContext);
  2221. localIntSlots[import.location] = val;
  2222. }
  2223. else if (type.isFloat())
  2224. {
  2225. float val = (float)JavascriptConversion::ToNumber(value, scriptContext);
  2226. localFloatSlots[import.location] = val;
  2227. }
  2228. else if (type.isDouble())
  2229. {
  2230. double val = JavascriptConversion::ToNumber(value, scriptContext);
  2231. localDoubleSlots[import.location] = val;
  2232. }
  2233. // check for implicit call after converting to number
  2234. if (this->CheckAndResetImplicitCall(prevDisableImplicitFlags, saveImplicitcallFlags))
  2235. {
  2236. // Runtime error
  2237. AsmJSCompiler::OutputError(this->scriptContext, _u("Asm.js Runtime Error : Accessing var import %s has side effects"), this->scriptContext->GetPropertyName(import.field)->GetBuffer());
  2238. return this->ProcessLinkFailedAsmJsModule();
  2239. }
  2240. }
  2241. // Load external functions
  2242. for (int i = 0; i < info->GetFunctionImportCount(); i++)
  2243. {
  2244. const auto& import = info->GetFunctionImport(i);
  2245. // this might throw, but it would anyway in non-asm.js
  2246. Var importFunc = JavascriptOperators::OP_GetProperty(foreign, import.field, scriptContext);
  2247. // check if there is implicit call and if there is implicit call then clear the disableimplicitcall flag
  2248. if (this->CheckAndResetImplicitCall(prevDisableImplicitFlags, saveImplicitcallFlags))
  2249. {
  2250. AsmJSCompiler::OutputError(this->scriptContext, _u("Asm.js Runtime Error : Accessing foreign function import %s has side effects"), this->scriptContext->GetPropertyName(import.field)->GetBuffer());
  2251. return this->ProcessLinkFailedAsmJsModule();
  2252. }
  2253. if (!JavascriptFunction::Is(importFunc))
  2254. {
  2255. AsmJSCompiler::OutputError(this->scriptContext, _u("Asm.js Runtime Error : Foreign function import %s is not a function"), this->scriptContext->GetPropertyName(import.field)->GetBuffer());
  2256. goto linkFailure;
  2257. }
  2258. localFunctionImports[import.location] = importFunc;
  2259. }
  2260. threadContext->SetDisableImplicitFlags(prevDisableImplicitFlags);
  2261. threadContext->SetImplicitCallFlags(saveImplicitcallFlags);
  2262. // scope
  2263. {
  2264. FrameDisplay* pDisplay = RecyclerNewPlus(scriptContext->GetRecycler(), sizeof(void*), FrameDisplay, 0);
  2265. //DynamicObject* asmModule = scriptContext->GetLibrary()->CreateObject(false, 1);
  2266. //JavascriptOperators::OP_SetProperty(asmModule, PropertyIds::module, moduleMemoryPtr, scriptContext);
  2267. //pDisplay->SetItem(0, this->function);
  2268. for (int i = 0; i < info->GetFunctionCount(); i++)
  2269. {
  2270. const auto& modFunc = info->GetFunction(i);
  2271. // TODO: add more runtime checks here
  2272. FunctionInfoPtrPtr functionInfo = m_functionBody->GetNestedFuncReference(i);
  2273. AsmJsScriptFunction* scriptFuncObj = AsmJsScriptFunction::OP_NewAsmJsFunc(pDisplay, functionInfo);
  2274. localModuleFunctions[modFunc.location] = scriptFuncObj;
  2275. if (scriptFuncObj->GetDynamicType()->GetEntryPoint() == DefaultDeferredDeserializeThunk)
  2276. {
  2277. JavascriptFunction::DeferredDeserialize(scriptFuncObj);
  2278. }
  2279. scriptFuncObj->GetDynamicType()->SetEntryPoint(AsmJsExternalEntryPoint);
  2280. scriptFuncObj->GetFunctionBody()->GetAsmJsFunctionInfo()->SetModuleFunctionBody(asmJsModuleFunctionBody);
  2281. scriptFuncObj->SetModuleEnvironment(moduleMemoryPtr);
  2282. if (!info->IsRuntimeProcessed())
  2283. {
  2284. // don't reset entrypoint upon relinking
  2285. FunctionEntryPointInfo* entrypointInfo = (FunctionEntryPointInfo*)scriptFuncObj->GetEntryPointInfo();
  2286. entrypointInfo->SetIsAsmJSFunction(true);
  2287. #if DYNAMIC_INTERPRETER_THUNK
  2288. if (!PHASE_ON1(AsmJsJITTemplatePhase))
  2289. {
  2290. entrypointInfo->jsMethod = AsmJsDefaultEntryThunk;
  2291. }
  2292. #endif
  2293. }
  2294. }
  2295. }
  2296. // Initialize function table arrays
  2297. for (int i = 0; i < info->GetFunctionTableCount(); i++)
  2298. {
  2299. const auto& modFuncTable = info->GetFunctionTable(i);
  2300. Field(Var)* funcTableArray = RecyclerNewArray(scriptContext->GetRecycler(), Field(Var), modFuncTable.size);
  2301. for (uint j = 0; j < modFuncTable.size; j++)
  2302. {
  2303. // get the module function index
  2304. const RegSlot index = modFuncTable.moduleFunctionIndex[j];
  2305. // assign the module function pointer to the array
  2306. Var functionPtr = localModuleFunctions[index];
  2307. funcTableArray[j] = functionPtr;
  2308. }
  2309. localFunctionTables[i] = funcTableArray;
  2310. }
  2311. // Do MTJRC/MAIC:0 check
  2312. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2313. if (
  2314. (PHASE_ON1(Js::AsmJsJITTemplatePhase) && CONFIG_FLAG(MaxTemplatizedJitRunCount) == 0) ||
  2315. (!PHASE_ON1(Js::AsmJsJITTemplatePhase) && (CONFIG_FLAG(MaxAsmJsInterpreterRunCount) == 0 || CONFIG_FLAG(ForceNative)))
  2316. )
  2317. {
  2318. if (PHASE_TRACE1(AsmjsEntryPointInfoPhase))
  2319. {
  2320. Output::Print(_u("%s Scheduling For Full JIT at callcount:%d\n"), asmJsModuleFunctionBody->GetDisplayName(), 0);
  2321. Output::Flush();
  2322. }
  2323. for (int i = 0; i < info->GetFunctionCount(); i++)
  2324. {
  2325. ScriptFunction* functionObj = (ScriptFunction*)PointerValue(localModuleFunctions[i]);
  2326. AnalysisAssert(functionObj != nullptr);
  2327. // don't want to generate code for APIs like changeHeap
  2328. if (functionObj->GetEntryPoint() == Js::AsmJsExternalEntryPoint)
  2329. {
  2330. WAsmJs::JitFunctionIfReady(functionObj);
  2331. }
  2332. }
  2333. }
  2334. #endif
  2335. info->SetIsRuntimeProcessed(true);
  2336. // create export object
  2337. if (info->GetExportsCount())
  2338. {
  2339. Var newObj = JavascriptOperators::NewScObjectLiteral(GetScriptContext(), info->GetExportsIdArray(),
  2340. this->GetFunctionBody()->GetObjectLiteralTypeRef(0));
  2341. for (int i = 0; i < info->GetExportsCount(); i++)
  2342. {
  2343. auto ex = info->GetExport(i);
  2344. Var func = localModuleFunctions[*ex.location];
  2345. JavascriptOperators::OP_InitProperty(newObj, *ex.id, func);
  2346. }
  2347. SetReg((RegSlot)0, newObj);
  2348. return newObj;
  2349. }
  2350. // export only 1 function
  2351. {
  2352. Var exportFunc = localModuleFunctions[info->GetExportFunctionIndex()];
  2353. SetReg((RegSlot)0, exportFunc);
  2354. return exportFunc;
  2355. }
  2356. linkFailure:
  2357. threadContext->SetDisableImplicitFlags(prevDisableImplicitFlags);
  2358. threadContext->SetImplicitCallFlags(saveImplicitcallFlags);
  2359. return this->ProcessLinkFailedAsmJsModule();
  2360. }
  2361. Var InterpreterStackFrame::ProcessLinkFailedAsmJsModule()
  2362. {
  2363. AsmJSCompiler::OutputError(this->scriptContext, _u("asm.js linking failed."));
  2364. Js::FunctionBody* asmJsModuleFunctionBody = GetFunctionBody();
  2365. AsmJsModuleInfo* info = asmJsModuleFunctionBody->GetAsmJsModuleInfo();
  2366. // do not support relinking with failed relink
  2367. if (info->IsRuntimeProcessed())
  2368. {
  2369. Js::Throw::OutOfMemory();
  2370. }
  2371. ScriptFunction * funcObj = GetJavascriptFunction();
  2372. ScriptFunction::ReparseAsmJsModule(&funcObj);
  2373. const bool doProfile =
  2374. funcObj->GetFunctionBody()->GetInterpreterExecutionMode(false) == ExecutionMode::ProfilingInterpreter ||
  2375. (funcObj->GetFunctionBody()->IsInDebugMode() && DynamicProfileInfo::IsEnabled(funcObj->GetFunctionBody()));
  2376. DynamicProfileInfo * dynamicProfileInfo = nullptr;
  2377. if (doProfile)
  2378. {
  2379. dynamicProfileInfo = funcObj->GetFunctionBody()->GetDynamicProfileInfo();
  2380. funcObj->GetScriptContext()->GetThreadContext()->ClearImplicitCallFlags();
  2381. }
  2382. // after reparsing, we want to also use a new interpreter stack frame, as it will have different characteristics than the asm.js version
  2383. InterpreterStackFrame::Setup setup(funcObj, m_inParams, m_inSlotsCount);
  2384. size_t varAllocCount = setup.GetAllocationVarCount();
  2385. size_t varSizeInBytes = varAllocCount * sizeof(Var);
  2386. Var* allocation = nullptr;
  2387. DWORD_PTR stackAddr;
  2388. bool fReleaseAlloc = false;
  2389. if (varAllocCount > InterpreterStackFrame::LocalsThreshold)
  2390. {
  2391. ArenaAllocator *tmpAlloc = nullptr;
  2392. fReleaseAlloc = GetScriptContext()->EnsureInterpreterArena(&tmpAlloc);
  2393. allocation = (Var*)tmpAlloc->Alloc(varSizeInBytes);
  2394. // use a stack address so the debugger stepping logic works (step-out, for example, compares stack depths to determine when to complete the step)
  2395. // debugger stepping does not matter here, but it's worth being consistent with normal stack frame
  2396. stackAddr = reinterpret_cast<DWORD_PTR>(&allocation);
  2397. }
  2398. else
  2399. {
  2400. PROBE_STACK_PARTIAL_INITIALIZED_INTERPRETER_FRAME(GetScriptContext(), Js::Constants::MinStackInterpreter + varSizeInBytes);
  2401. allocation = (Var*)_alloca(varSizeInBytes);
  2402. stackAddr = reinterpret_cast<DWORD_PTR>(allocation);
  2403. }
  2404. #if DBG
  2405. Var invalidStackVar = (Js::RecyclableObject*)_alloca(sizeof(Js::RecyclableObject));
  2406. memset(invalidStackVar, 0xFE, sizeof(Js::RecyclableObject));
  2407. InterpreterStackFrame * newInstance = newInstance = setup.InitializeAllocation(allocation, funcObj->GetFunctionBody()->GetHasImplicitArgIns(), doProfile, nullptr, stackAddr, invalidStackVar);
  2408. #else
  2409. InterpreterStackFrame * newInstance = newInstance = setup.InitializeAllocation(allocation, funcObj->GetFunctionBody()->GetHasImplicitArgIns(), doProfile, nullptr, stackAddr);
  2410. #endif
  2411. newInstance->m_reader.Create(funcObj->GetFunctionBody());
  2412. // now that we have set up the new frame, let's interpret it!
  2413. funcObj->GetFunctionBody()->BeginExecution();
  2414. PushPopFrameHelper pushPopFrameHelper(newInstance, this->returnAddress, this->addressOfReturnAddress);
  2415. Var retVal = newInstance->ProcessUnprofiled();
  2416. if (doProfile)
  2417. {
  2418. dynamicProfileInfo->RecordImplicitCallFlags(GetScriptContext()->GetThreadContext()->GetImplicitCallFlags());
  2419. }
  2420. if (fReleaseAlloc)
  2421. {
  2422. GetScriptContext()->ReleaseInterpreterArena();
  2423. }
  2424. return retVal;
  2425. }
  2426. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2427. int AsmJsCallDepth = 0;
  2428. #endif
  2429. // Function memory allocation should be done the same way as
  2430. // T AsmJsCommunEntryPoint(Js::ScriptFunction* func, ...) (AsmJSJitTemplate.cpp)
  2431. // update any changes there
  2432. /*
  2433. This function does the following fixup
  2434. Stack Before Stack After
  2435. ============== ================
  2436. | VarConstants | | VarConstants |
  2437. |--------------| |-----------------
  2438. | IntConstants | | IntConstants |
  2439. |--------------| | ------------ |
  2440. | FloatConst | | Int Vars+Tmps |
  2441. |--------------| |----------------|
  2442. | DoubleConst | | FloatConst |
  2443. |--------------| | ---------- |
  2444. | Var&Temps | | Flt Vars+tmps |
  2445. |==============| |----------------|
  2446. | DoubleConst |
  2447. | ----------- |
  2448. | Dbl Vars+Tmps |
  2449. ================
  2450. intSrc,FltSrc&DblSrc are pointers to the stack before the change
  2451. m_localIntSlots,m_localFloatSlots,m_localDoubleSlots are pointers to the stack after the change
  2452. */
  2453. void InterpreterStackFrame::AlignMemoryForAsmJs()
  2454. {
  2455. FunctionBody *const functionBody = GetFunctionBody();
  2456. ScriptFunction* func = GetJavascriptFunction();
  2457. uint32& callCount = ((FunctionEntryPointInfo*)func->GetEntryPointInfo())->callsCount;
  2458. WAsmJs::JitFunctionIfReady(func, ++callCount);
  2459. AsmJsFunctionInfo* info = functionBody->GetAsmJsFunctionInfo();
  2460. // The const table is copied after the FirstRegSlot
  2461. byte* constTable = (byte*)(m_localSlots + FunctionBody::FirstRegSlot);
  2462. byte* slotsStart = (byte*)m_localSlots;
  2463. // Must do in reverse order to avoid overwriting const of other type as we move things around
  2464. for (int i = WAsmJs::LIMIT - 1; i >= 0; --i)
  2465. {
  2466. WAsmJs::Types type = (WAsmJs::Types)i;
  2467. auto typeInfo = info->GetTypedSlotInfo(type);
  2468. byte* destination = slotsStart + typeInfo->byteOffset;
  2469. switch (type)
  2470. {
  2471. case WAsmJs::INT32: m_localIntSlots = (int*)destination; break;
  2472. case WAsmJs::INT64: m_localInt64Slots = (int64*)destination; break;
  2473. case WAsmJs::FLOAT32: m_localFloatSlots = (float*)destination; break;
  2474. case WAsmJs::FLOAT64: m_localDoubleSlots = (double*)destination; break;
  2475. case WAsmJs::SIMD: m_localSimdSlots = (AsmJsSIMDValue*)destination; break;
  2476. default:
  2477. CompileAssert(WAsmJs::SIMD == WAsmJs::LastType);
  2478. Assert(false);
  2479. break;
  2480. }
  2481. byte* source = constTable + typeInfo->constSrcByteOffset;
  2482. if (typeInfo->constCount > 0 && source != destination)
  2483. {
  2484. // Make sure slots are aligned for this type
  2485. Assert(::Math::Align<intptr_t>((intptr_t)destination, (intptr_t)WAsmJs::GetTypeByteSize(type)) == (intptr_t)destination);
  2486. Assert(typeInfo->constSrcByteOffset != Js::Constants::InvalidOffset);
  2487. uint constByteSize = typeInfo->constCount * WAsmJs::GetTypeByteSize(type);
  2488. memmove_s(destination, constByteSize, source, constByteSize);
  2489. }
  2490. }
  2491. // Load module environment
  2492. AsmJsScriptFunction* asmJsFunc = AsmJsScriptFunction::FromVar(this->function);
  2493. m_localSlots[AsmJsFunctionMemory::ModuleEnvRegister] = asmJsFunc->GetModuleEnvironment();
  2494. m_localSlots[AsmJsFunctionMemory::ArrayBufferRegister] = nullptr;
  2495. #ifdef ENABLE_WASM
  2496. if (WasmScriptFunction::Is(func))
  2497. {
  2498. WasmScriptFunction* wasmFunc = WasmScriptFunction::FromVar(func);
  2499. m_wasmMemory = wasmFunc->GetWebAssemblyMemory();
  2500. m_signatures = func->GetFunctionBody()->GetAsmJsFunctionInfo()->GetWebAssemblyModule()->GetSignatures();
  2501. }
  2502. else
  2503. #endif
  2504. {
  2505. m_asmJsBuffer = asmJsFunc->GetAsmJsArrayBuffer();
  2506. }
  2507. m_localSlots[AsmJsFunctionMemory::ArraySizeRegister] = 0; // do not cache ArraySize in the interpreter
  2508. m_localSlots[AsmJsFunctionMemory::ScriptContextBufferRegister] = functionBody->GetScriptContext();
  2509. int* intArg = m_localIntSlots + info->GetTypedSlotInfo(WAsmJs::INT32)->constCount;
  2510. int64* int64Arg = m_localInt64Slots + info->GetTypedSlotInfo(WAsmJs::INT64)->constCount;
  2511. double* doubleArg = m_localDoubleSlots + info->GetTypedSlotInfo(WAsmJs::FLOAT64)->constCount;
  2512. float* floatArg = m_localFloatSlots + info->GetTypedSlotInfo(WAsmJs::FLOAT32)->constCount;
  2513. #ifdef ENABLE_WASM_SIMD
  2514. AsmJsSIMDValue* simdArg = m_localSimdSlots + info->GetTypedSlotInfo(WAsmJs::SIMD)->constCount;
  2515. #endif
  2516. // Move the arguments to the right location
  2517. ArgSlot argCount = info->GetArgCount();
  2518. #if _M_X64 && _WIN32
  2519. uint homingAreaSize = 0;
  2520. #endif
  2521. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2522. const bool tracingFunc = PHASE_TRACE(AsmjsFunctionEntryPhase, functionBody);
  2523. if (tracingFunc)
  2524. {
  2525. if (AsmJsCallDepth)
  2526. {
  2527. Output::Print(_u("%*c"), AsmJsCallDepth, ' ');
  2528. }
  2529. Output::Print(_u("Executing function %s("), functionBody->GetDisplayName());
  2530. ++AsmJsCallDepth;
  2531. }
  2532. #endif
  2533. uintptr_t argAddress = (uintptr_t)m_inParams;
  2534. for (ArgSlot i = 0; i < argCount; i++)
  2535. {
  2536. #if _M_X64 && _WIN32
  2537. // 3rd Argument should be at the end of the homing area.
  2538. Assert(i != 3 || argAddress == (uintptr_t)m_inParams + homingAreaSize);
  2539. if (i < 3)
  2540. {
  2541. // for x64 we spill the first 3 floating point args below the rest of the arguments on the stack
  2542. // m_inParams will be from DynamicInterpreterThunk's frame. Floats are in InterpreterAsmThunk's frame. Stack will be set up like so:
  2543. // DIT arg2 <- first scriptArg, m_inParams points here
  2544. // DIT arg1
  2545. // padding
  2546. // IAT r9 home
  2547. // IAT r8 home
  2548. // IAT rdx home
  2549. // IAT rcx home
  2550. // IAT return address
  2551. // IAT push rbp
  2552. // IAT padding
  2553. // IAT xmm3 spill
  2554. // IAT xmm2 spill
  2555. // IAT xmm1 spill <- floatSpillAddress for arg1
  2556. #define FLOAT_SPILL_ADDRESS_OFFSET_WORDS 15
  2557. // floats are spilled as xmmwords
  2558. uintptr_t floatSpillAddress = (uintptr_t)m_inParams - MachPtr * (FLOAT_SPILL_ADDRESS_OFFSET_WORDS - 2*i);
  2559. if (info->GetArgType(i).isInt())
  2560. {
  2561. *intArg = *(int*)argAddress;
  2562. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2563. if (tracingFunc)
  2564. {
  2565. Output::Print(_u("%d, "), *intArg);
  2566. }
  2567. #endif
  2568. ++intArg;
  2569. homingAreaSize += MachPtr;
  2570. }
  2571. else if (info->GetArgType(i).isInt64())
  2572. {
  2573. *int64Arg = *(int64*)argAddress;
  2574. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2575. if (tracingFunc)
  2576. {
  2577. Output::Print(_u("%lld, "), *int64Arg);
  2578. }
  2579. #endif
  2580. ++int64Arg;
  2581. homingAreaSize += MachPtr;
  2582. }
  2583. else if (info->GetArgType(i).isFloat())
  2584. {
  2585. *floatArg = *(float*)floatSpillAddress;
  2586. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2587. if (tracingFunc)
  2588. {
  2589. Output::Print(_u("%.2f, "), *floatArg);
  2590. }
  2591. #endif
  2592. ++floatArg;
  2593. homingAreaSize += MachPtr;
  2594. }
  2595. else if (info->GetArgType(i).isDouble())
  2596. {
  2597. *doubleArg = *(double*)floatSpillAddress;
  2598. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2599. if (tracingFunc)
  2600. {
  2601. Output::Print(_u("%.2f, "), *doubleArg);
  2602. }
  2603. #endif
  2604. ++doubleArg;
  2605. homingAreaSize += MachPtr;
  2606. }
  2607. else
  2608. {
  2609. #ifdef ENABLE_WASM_SIMD
  2610. Assert(info->GetArgType(i).isSIMD());
  2611. *simdArg = *(AsmJsSIMDValue*)floatSpillAddress;
  2612. ++simdArg;
  2613. homingAreaSize += sizeof(AsmJsSIMDValue);
  2614. #else
  2615. Assert(UNREACHED);
  2616. #endif
  2617. }
  2618. if (Wasm::Simd::IsEnabled() && i == 2) // last argument ?
  2619. {
  2620. // If we have simd arguments, the homing area in m_inParams can be larger than 3 64-bit slots. This is because SIMD values are unboxed there too.
  2621. // After unboxing, the homing area is overwritten by rdx, r8 and r9, and we read/skip 64-bit slots from the homing area (argAddress += MachPtr).
  2622. // After the last argument of the 3 is read, we need to advance argAddress to skip over the possible extra space and to the start of the rest of the arguments.
  2623. argAddress = (uintptr_t)m_inParams + homingAreaSize;
  2624. }
  2625. else
  2626. {
  2627. argAddress += MachPtr;
  2628. }
  2629. }
  2630. else
  2631. #endif
  2632. if (info->GetArgType(i).isInt())
  2633. {
  2634. *intArg = *(int*)argAddress;
  2635. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2636. if (tracingFunc)
  2637. {
  2638. Output::Print(_u("%d, "), *intArg);
  2639. }
  2640. #endif
  2641. ++intArg;
  2642. argAddress += MachPtr;
  2643. }
  2644. else if (info->GetArgType(i).isInt64())
  2645. {
  2646. *int64Arg = *(int64*)argAddress;
  2647. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2648. if (tracingFunc)
  2649. {
  2650. Output::Print(_u("%lld, "), *int64Arg);
  2651. }
  2652. #endif
  2653. ++int64Arg;
  2654. argAddress += sizeof(int64);
  2655. }
  2656. else if (info->GetArgType(i).isFloat())
  2657. {
  2658. *floatArg = *(float*)argAddress;
  2659. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2660. if (tracingFunc)
  2661. {
  2662. Output::Print(_u("%.2f, "), *floatArg);
  2663. }
  2664. #endif
  2665. ++floatArg;
  2666. argAddress += MachPtr;
  2667. }
  2668. else if (info->GetArgType(i).isDouble())
  2669. {
  2670. Assert(info->GetArgType(i).isDouble());
  2671. *doubleArg = *(double*)argAddress;
  2672. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2673. if (tracingFunc)
  2674. {
  2675. Output::Print(_u("%.2f, "), *doubleArg);
  2676. }
  2677. #endif
  2678. ++doubleArg;
  2679. argAddress += sizeof(double);
  2680. }
  2681. #ifdef ENABLE_WASM_SIMD
  2682. else if (Wasm::Simd::IsEnabled() && info->GetArgType(i).isSIMD())
  2683. {
  2684. *simdArg = *(AsmJsSIMDValue*)argAddress;
  2685. ++simdArg;
  2686. argAddress += sizeof(AsmJsSIMDValue);
  2687. }
  2688. #endif
  2689. else
  2690. {
  2691. AssertMsg(UNREACHED, "Invalid function arg type.");
  2692. }
  2693. }
  2694. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2695. if (tracingFunc)
  2696. {
  2697. Output::Print(_u("){\n"));
  2698. Output::Flush();
  2699. }
  2700. #endif
  2701. }
  2702. #endif
  2703. ///----------------------------------------------------------------------------
  2704. ///
  2705. /// InterpreterStackFrame::Process
  2706. ///
  2707. /// Process() processes a single loop of execution for the current
  2708. /// JavascriptFunction being executed:
  2709. /// - Individual instructions are dispatched to specific handlers for different
  2710. /// OpCodes.
  2711. ///
  2712. ///----------------------------------------------------------------------------
  2713. #if ENABLE_PROFILE_INFO
  2714. #define INTERPRETERLOOPNAME ProcessProfiled
  2715. #define PROVIDE_INTERPRETERPROFILE
  2716. #include "InterpreterLoop.inl"
  2717. #undef PROVIDE_INTERPRETERPROFILE
  2718. #undef INTERPRETERLOOPNAME
  2719. #endif
  2720. #define INTERPRETERLOOPNAME ProcessUnprofiled
  2721. #include "InterpreterLoop.inl"
  2722. #undef INTERPRETERLOOPNAME
  2723. #if ENABLE_TTD_DIAGNOSTICS_TRACING
  2724. #define PROVIDE_INTERPRETER_STMTS
  2725. #define INTERPRETERLOOPNAME ProcessUnprofiled_PreviousStmtTracking
  2726. #include "InterpreterLoop.inl"
  2727. #undef INTERPRETERLOOPNAME
  2728. #undef PROVIDE_INTERPRETER_STMTS
  2729. #endif
  2730. #ifdef ASMJS_PLAT
  2731. #define INTERPRETERLOOPNAME ProcessAsmJs
  2732. #define INTERPRETER_ASMJS
  2733. #include "InterpreterProcessOpCodeAsmJs.h"
  2734. #include "InterpreterLoop.inl"
  2735. #undef INTERPRETER_ASMJS
  2736. #undef INTERPRETERLOOPNAME
  2737. #endif
  2738. // For now, always collect profile data when debugging,
  2739. // otherwise the backend will be confused if there's no profile data.
  2740. #ifdef ENABLE_SCRIPT_DEBUGGING
  2741. #define INTERPRETERLOOPNAME ProcessWithDebugging
  2742. #define PROVIDE_DEBUGGING
  2743. #if ENABLE_PROFILE_INFO
  2744. #define PROVIDE_INTERPRETERPROFILE
  2745. #endif
  2746. #include "InterpreterLoop.inl"
  2747. #if ENABLE_PROFILE_INFO
  2748. #undef PROVIDE_INTERPRETERPROFILE
  2749. #endif
  2750. #undef PROVIDE_DEBUGGING
  2751. #undef INTERPRETERLOOPNAME
  2752. #endif
  2753. #if ENABLE_TTD
  2754. #define PROVIDE_INTERPRETER_STMTS
  2755. #define INTERPRETERLOOPNAME ProcessWithDebugging_PreviousStmtTracking
  2756. #define PROVIDE_DEBUGGING
  2757. #if ENABLE_PROFILE_INFO
  2758. #define PROVIDE_INTERPRETERPROFILE
  2759. #endif
  2760. #include "InterpreterLoop.inl"
  2761. #if ENABLE_PROFILE_INFO
  2762. #undef PROVIDE_INTERPRETERPROFILE
  2763. #endif
  2764. #undef PROVIDE_DEBUGGING
  2765. #undef INTERPRETERLOOPNAME
  2766. #undef PROVIDE_INTERPRETER_STMTS
  2767. #endif
  2768. Var InterpreterStackFrame::Process()
  2769. {
  2770. #if ENABLE_PROFILE_INFO
  2771. class AutoRestore
  2772. {
  2773. private:
  2774. InterpreterStackFrame *const interpreterStackFrame;
  2775. const uint32 savedSwitchProfileModeOnLoopEndNumber;
  2776. const bool savedIsAutoProfiling;
  2777. const bool savedSwitchProfileMode;
  2778. public:
  2779. AutoRestore(InterpreterStackFrame *const interpreterStackFrame)
  2780. : interpreterStackFrame(interpreterStackFrame),
  2781. savedIsAutoProfiling(interpreterStackFrame->isAutoProfiling),
  2782. savedSwitchProfileMode(interpreterStackFrame->switchProfileMode),
  2783. savedSwitchProfileModeOnLoopEndNumber(interpreterStackFrame->switchProfileModeOnLoopEndNumber)
  2784. {
  2785. }
  2786. ~AutoRestore()
  2787. {
  2788. interpreterStackFrame->isAutoProfiling = savedIsAutoProfiling;
  2789. interpreterStackFrame->switchProfileMode = savedSwitchProfileMode;
  2790. interpreterStackFrame->switchProfileModeOnLoopEndNumber = savedSwitchProfileModeOnLoopEndNumber;
  2791. }
  2792. } autoRestore(this);
  2793. #endif
  2794. if (this->ehBailoutData && !this->TestFlags(InterpreterStackFrameFlags_FromBailOutInInlinee))
  2795. {
  2796. if (this->TestFlags(Js::InterpreterStackFrameFlags_FromBailOut) && !this->TestFlags(InterpreterStackFrameFlags_ProcessingBailOutFromEHCode))
  2797. {
  2798. this->OrFlags(Js::InterpreterStackFrameFlags_ProcessingBailOutFromEHCode);
  2799. EHBailoutData * topLevelEHBailoutData = this->ehBailoutData;
  2800. while (topLevelEHBailoutData->parent->nestingDepth != -1)
  2801. {
  2802. topLevelEHBailoutData->parent->child = topLevelEHBailoutData;
  2803. topLevelEHBailoutData = topLevelEHBailoutData->parent;
  2804. }
  2805. ProcessTryHandlerBailout(topLevelEHBailoutData, this->ehBailoutData->nestingDepth);
  2806. this->ClearFlags(Js::InterpreterStackFrameFlags_ProcessingBailOutFromEHCode);
  2807. this->ehBailoutData = nullptr;
  2808. }
  2809. }
  2810. #ifdef ASMJS_PLAT
  2811. if( GetFunctionBody()->GetIsAsmjsMode() )
  2812. {
  2813. FunctionBody *const functionBody = GetFunctionBody();
  2814. AsmJsFunctionInfo* asmInfo = functionBody->GetAsmJsFunctionInfo();
  2815. if (asmInfo)
  2816. {
  2817. AlignMemoryForAsmJs();
  2818. Var returnVar = ProcessAsmJs();
  2819. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2820. if( PHASE_TRACE( AsmjsFunctionEntryPhase, functionBody ) )
  2821. {
  2822. --AsmJsCallDepth;
  2823. if( AsmJsCallDepth )
  2824. {
  2825. Output::Print( _u("%*c}"), AsmJsCallDepth, ' ' );
  2826. }
  2827. else
  2828. {
  2829. Output::Print( _u("}") );
  2830. }
  2831. switch( asmInfo->GetReturnType().which() )
  2832. {
  2833. case AsmJsRetType::Void:
  2834. break;
  2835. case AsmJsRetType::Signed:
  2836. Output::Print( _u(" = %d"), m_localIntSlots[0] );
  2837. break;
  2838. case AsmJsRetType::Int64:
  2839. Output::Print( _u(" = %lld"), m_localInt64Slots[0] );
  2840. break;
  2841. case AsmJsRetType::Float:
  2842. Output::Print(_u(" = %.4f"), m_localFloatSlots[0]);
  2843. break;
  2844. case AsmJsRetType::Double:
  2845. Output::Print( _u(" = %.4f"), m_localDoubleSlots[0]);
  2846. break;
  2847. default:
  2848. break;
  2849. }
  2850. Output::Print( _u(";\n") );
  2851. Output::Flush();
  2852. }
  2853. #endif
  2854. return returnVar;
  2855. }
  2856. else
  2857. {
  2858. Assert(functionBody->GetAsmJsModuleInfo());
  2859. return ProcessAsmJsModule();
  2860. }
  2861. }
  2862. #endif
  2863. #if ENABLE_PROFILE_INFO
  2864. switchProfileMode = false;
  2865. switchProfileModeOnLoopEndNumber = 0u - 1;
  2866. #endif
  2867. #if ENABLE_PROFILE_INFO
  2868. FunctionBody *const functionBody = GetFunctionBody();
  2869. const ExecutionMode interpreterExecutionMode =
  2870. functionBody->GetInterpreterExecutionMode(TestFlags(InterpreterStackFrameFlags_FromBailOut));
  2871. if(interpreterExecutionMode == ExecutionMode::ProfilingInterpreter)
  2872. {
  2873. #if ENABLE_TTD
  2874. AssertMsg(!SHOULD_DO_TTD_STACK_STMT_OP(this->scriptContext), "We should have pinned into Interpreter mode in this case!!!");
  2875. #endif
  2876. isAutoProfiling = false;
  2877. return ProcessProfiled();
  2878. }
  2879. Assert(
  2880. interpreterExecutionMode == ExecutionMode::Interpreter ||
  2881. interpreterExecutionMode == ExecutionMode::AutoProfilingInterpreter);
  2882. isAutoProfiling = interpreterExecutionMode == ExecutionMode::AutoProfilingInterpreter;
  2883. Var result;
  2884. while(true)
  2885. {
  2886. Assert(!switchProfileMode);
  2887. #if ENABLE_TTD_DIAGNOSTICS_TRACING
  2888. if(this->scriptContext->ShouldPerformRecordOrReplayAction())
  2889. {
  2890. result = ProcessUnprofiled_PreviousStmtTracking();
  2891. }
  2892. else
  2893. {
  2894. result = ProcessUnprofiled();
  2895. }
  2896. #else
  2897. result = ProcessUnprofiled();
  2898. #endif
  2899. Assert(!(switchProfileMode && result));
  2900. if(switchProfileMode)
  2901. {
  2902. switchProfileMode = false;
  2903. }
  2904. else
  2905. {
  2906. break;
  2907. }
  2908. Assert(isAutoProfiling);
  2909. #if DBG_DUMP
  2910. if(PHASE_TRACE(InterpreterAutoProfilePhase, functionBody))
  2911. {
  2912. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2913. Output::Print(_u("InterpreterAutoProfile - Func %s - Started profiling\n"), functionBody->GetDebugNumberSet(debugStringBuffer));
  2914. Output::Flush();
  2915. }
  2916. #endif
  2917. Assert(!switchProfileMode);
  2918. result = ProcessProfiled();
  2919. Assert(!(switchProfileMode && result));
  2920. if(switchProfileMode)
  2921. {
  2922. switchProfileMode = false;
  2923. }
  2924. else
  2925. {
  2926. break;
  2927. }
  2928. Assert(isAutoProfiling);
  2929. #if DBG_DUMP
  2930. if(PHASE_TRACE(InterpreterAutoProfilePhase, functionBody))
  2931. {
  2932. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2933. Output::Print(_u("InterpreterAutoProfile - Func %s - Stopped profiling\n"), functionBody->GetDebugNumberSet(debugStringBuffer));
  2934. Output::Flush();
  2935. }
  2936. #endif
  2937. }
  2938. return result;
  2939. #else
  2940. #if ENABLE_TTD_DIAGNOSTICS_TRACING
  2941. if(this->scriptContext->ShouldPerformRecordOrReplayAction())
  2942. {
  2943. return ProcessUnprofiled_PreviousStmtTracking();
  2944. }
  2945. else
  2946. {
  2947. return ProcessUnprofiled();
  2948. }
  2949. #else
  2950. return ProcessUnprofiled();
  2951. #endif
  2952. #endif
  2953. }
  2954. template <class T>
  2955. void InterpreterStackFrame::OP_GetMethodProperty(unaligned T *playout)
  2956. {
  2957. Var varInstance = GetReg(playout->Instance);
  2958. OP_GetMethodProperty(varInstance, playout);
  2959. }
  2960. template <class T>
  2961. void InterpreterStackFrame::OP_GetLocalMethodProperty(unaligned T *playout)
  2962. {
  2963. OP_GetMethodProperty(this->localClosure, playout);
  2964. }
  2965. template <class T>
  2966. void InterpreterStackFrame::OP_GetMethodProperty(Var varInstance, unaligned T *playout)
  2967. {
  2968. #if ENABLE_COPYONACCESS_ARRAY
  2969. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(varInstance);
  2970. #endif
  2971. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  2972. RecyclableObject* obj = JavascriptOperators::TryFromVar<RecyclableObject>(varInstance);
  2973. if (obj)
  2974. {
  2975. ScriptFunction *fn = JavascriptOperators::TryFromVar<ScriptFunction>(obj);
  2976. if ((propertyId == PropertyIds::apply || propertyId == PropertyIds::call) && fn)
  2977. {
  2978. // If the property being loaded is "apply"/"call", make an optimistic assumption that apply/call is not overridden and
  2979. // undefer the function right here if it was defer parsed before. This is required so that the load of "apply"/"call"
  2980. // happens from the same "type". Otherwise, we will have a polymorphic cache for load of "apply"/"call".
  2981. if(fn->GetType()->GetEntryPoint() == JavascriptFunction::DeferredParsingThunk)
  2982. {
  2983. JavascriptFunction::DeferredParse(&fn);
  2984. }
  2985. }
  2986. }
  2987. InlineCache *inlineCache = this->GetInlineCache(playout->inlineCacheIndex);
  2988. PropertyValueInfo info;
  2989. PropertyValueInfo::SetCacheInfo(&info, GetFunctionBody(), inlineCache, playout->inlineCacheIndex, true);
  2990. Var aValue;
  2991. if (obj &&
  2992. CacheOperators::TryGetProperty<true, true, false, false, false, false, true, false, false, false>(
  2993. obj, false, obj, propertyId, &aValue, GetScriptContext(), nullptr, &info))
  2994. {
  2995. SetReg(playout->Value, aValue);
  2996. return;
  2997. }
  2998. OP_GetMethodProperty_NoFastPath(varInstance, playout);
  2999. }
  3000. template <class T>
  3001. _NOINLINE void InterpreterStackFrame::OP_GetMethodProperty_NoFastPath(Var instance, unaligned T *playout)
  3002. {
  3003. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3004. Var value = JavascriptOperators::PatchGetMethod<false>(
  3005. GetFunctionBody(),
  3006. GetInlineCache(playout->inlineCacheIndex),
  3007. playout->inlineCacheIndex,
  3008. instance,
  3009. propertyId
  3010. );
  3011. #ifdef TELEMETRY_INTERPRETER
  3012. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  3013. {
  3014. // `successful` will be true as PatchGetMethod throws an exception if not found.
  3015. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().GetMethodProperty(instance, propertyId, value, true);
  3016. }
  3017. #endif
  3018. SetReg(playout->Value, value);
  3019. }
  3020. template <class T>
  3021. void InterpreterStackFrame::OP_GetRootMethodProperty(unaligned T *playout)
  3022. {
  3023. Assert(playout->inlineCacheIndex >= this->m_functionBody->GetRootObjectLoadInlineCacheStart());
  3024. Js::Var instance = this->GetRootObject();
  3025. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3026. InlineCache *inlineCache = this->GetInlineCache(playout->inlineCacheIndex);
  3027. DynamicObject *obj = DynamicObject::UnsafeFromVar(instance);
  3028. PropertyValueInfo info;
  3029. PropertyValueInfo::SetCacheInfo(&info, GetFunctionBody(), inlineCache, playout->inlineCacheIndex, true);
  3030. Var aValue;
  3031. if (CacheOperators::TryGetProperty<true, true, false, false, false, false, true, false, false, false>(
  3032. obj, true, obj, propertyId, &aValue, GetScriptContext(), nullptr, &info))
  3033. {
  3034. SetReg(playout->Value, aValue);
  3035. return;
  3036. }
  3037. OP_GetRootMethodProperty_NoFastPath(playout);
  3038. }
  3039. template <class T>
  3040. _NOINLINE void InterpreterStackFrame::OP_GetRootMethodProperty_NoFastPath(unaligned T *playout)
  3041. {
  3042. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3043. Var rootInstance = this->GetRootObject();
  3044. Var value = JavascriptOperators::PatchGetRootMethod<false>(
  3045. GetFunctionBody(),
  3046. GetInlineCache(playout->inlineCacheIndex),
  3047. playout->inlineCacheIndex,
  3048. DynamicObject::UnsafeFromVar(rootInstance),
  3049. propertyId
  3050. );
  3051. #ifdef TELEMETRY_INTERPRETER
  3052. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  3053. {
  3054. // `successful` will be true as PatchGetMethod throws an exception if not found.
  3055. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().GetMethodProperty(rootInstance, propertyId, value, true);
  3056. }
  3057. #endif
  3058. SetReg(playout->Value, value);
  3059. }
  3060. template <class T>
  3061. void InterpreterStackFrame::OP_GetMethodPropertyScoped(unaligned T *playout)
  3062. {
  3063. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  3064. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  3065. threadContext->ClearImplicitCallFlags();
  3066. Var varInstance = GetReg(playout->Instance);
  3067. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3068. RecyclableObject* obj = NULL;
  3069. if (RecyclableObject::Is(varInstance))
  3070. {
  3071. obj = RecyclableObject::FromVar(varInstance);
  3072. }
  3073. InlineCache *inlineCache = this->GetInlineCache(playout->inlineCacheIndex);
  3074. PropertyValueInfo info;
  3075. PropertyValueInfo::SetCacheInfo(&info, GetFunctionBody(), inlineCache, playout->inlineCacheIndex, true);
  3076. Var aValue;
  3077. if (obj &&
  3078. CacheOperators::TryGetProperty<true, true, false, false, false, false, true, false, false, false>(
  3079. obj, false, obj, propertyId, &aValue, GetScriptContext(), nullptr, &info))
  3080. {
  3081. threadContext->CheckAndResetImplicitCallAccessorFlag();
  3082. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  3083. SetReg(playout->Value, aValue);
  3084. return;
  3085. }
  3086. OP_GetMethodPropertyScoped_NoFastPath(playout);
  3087. threadContext->CheckAndResetImplicitCallAccessorFlag();
  3088. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  3089. }
  3090. template <class T>
  3091. _NOINLINE void InterpreterStackFrame::OP_GetMethodPropertyScoped_NoFastPath(unaligned T *playout)
  3092. {
  3093. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3094. Js::Var instance = GetReg(playout->Instance);
  3095. Js::Var value = JavascriptOperators::PatchScopedGetMethod<false>(
  3096. GetFunctionBody(),
  3097. GetInlineCache(playout->inlineCacheIndex),
  3098. playout->inlineCacheIndex,
  3099. instance,
  3100. propertyId
  3101. );
  3102. SetReg(playout->Value, value);
  3103. #ifdef TELEMETRY_INTERPRETER
  3104. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  3105. {
  3106. // `successful` will be true as PatchGetMethod throws an exception if not found.
  3107. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().GetMethodProperty(instance, propertyId, value, true);
  3108. }
  3109. #endif
  3110. }
  3111. template <class T>
  3112. void InterpreterStackFrame::OP_ProfiledGetMethodProperty(unaligned T *playout)
  3113. {
  3114. ProfiledGetProperty<T, false, true, false>(playout, GetReg(playout->Instance));
  3115. }
  3116. template <class T>
  3117. void InterpreterStackFrame::OP_ProfiledGetLocalMethodProperty(unaligned T *playout)
  3118. {
  3119. ProfiledGetProperty<T, false, true, false>(playout, this->localClosure);
  3120. }
  3121. template <class T>
  3122. void InterpreterStackFrame::OP_ProfiledGetRootMethodProperty(unaligned T *playout)
  3123. {
  3124. ProfiledGetProperty<T, true, true, false>(playout, GetRootObject());
  3125. }
  3126. RecyclableObject *
  3127. InterpreterStackFrame::OP_CallGetFunc(Var target)
  3128. {
  3129. return JavascriptOperators::GetCallableObjectOrThrow(target, GetScriptContext());
  3130. }
  3131. void InterpreterStackFrame::OP_AsmStartCall( const unaligned OpLayoutStartCall * playout )
  3132. {
  3133. OP_StartCall( playout->ArgCount/sizeof(Var) );
  3134. m_outParams[0] = scriptContext->GetLibrary()->GetUndefined();
  3135. }
  3136. void InterpreterStackFrame::OP_StartCall(const unaligned OpLayoutStartCall * playout)
  3137. {
  3138. OP_StartCall(playout->ArgCount);
  3139. }
  3140. void InterpreterStackFrame::OP_StartCall(uint outParamCount)
  3141. {
  3142. // Save the outParams for the current callsite on the outparam stack
  3143. PushOut(m_outParams);
  3144. // Update outParams for the indicated callsite
  3145. m_outParams = m_outSp;
  3146. m_outSp += outParamCount;
  3147. AssertMsg(m_localSlots + this->m_functionBody->GetLocalsCount() < m_outSp &&
  3148. m_outSp <= (m_localSlots + this->m_functionBody->GetLocalsCount() + this->m_functionBody->GetOutParamMaxDepth()),
  3149. "out args Stack pointer not in range after Push");
  3150. }
  3151. #ifdef ASMJS_PLAT
  3152. void InterpreterStackFrame::OP_ProfiledCallAsmInternal(RegSlot funcReg, RegSlot returnReg, ProfileId profileId)
  3153. {
  3154. Var target = GetRegRawPtr(funcReg);
  3155. ScriptFunction* function = (ScriptFunction*)OP_CallGetFunc(target);
  3156. Js::FunctionBody * body = function->GetFunctionBody();
  3157. DynamicProfileInfo * dynamicProfileInfo = GetFunctionBody()->GetDynamicProfileInfo();
  3158. dynamicProfileInfo->RecordAsmJsCallSiteInfo(GetFunctionBody(), profileId, body);
  3159. return OP_CallAsmInternalCommon(function, returnReg);
  3160. }
  3161. void InterpreterStackFrame::OP_CallAsmInternal(RegSlot funcReg, RegSlot returnReg)
  3162. {
  3163. Var target = GetRegRawPtr(funcReg);
  3164. ScriptFunction* function = (ScriptFunction*)OP_CallGetFunc(target);
  3165. return OP_CallAsmInternalCommon(function, returnReg);
  3166. }
  3167. void InterpreterStackFrame::OP_CallAsmInternalCommon(ScriptFunction* function, RegSlot returnReg)
  3168. {
  3169. AsmJsScriptFunction* scriptFunc = AsmJsScriptFunction::FromVar(function);
  3170. AsmJsFunctionInfo* asmInfo = scriptFunc->GetFunctionBody()->GetAsmJsFunctionInfo();
  3171. uint alignedArgsSize = ::Math::Align<uint32>(asmInfo->GetArgByteSize(), 16);
  3172. #if _M_X64 && _WIN32
  3173. // convention is to always allocate spill space for rcx,rdx,r8,r9
  3174. if (alignedArgsSize < 0x20) alignedArgsSize = 0x20;
  3175. uint* argSizes = asmInfo->GetArgsSizesArray();
  3176. Assert(asmInfo->GetArgSizeArrayLength() >= 2);
  3177. byte* curOutParams = (byte*)m_outParams + sizeof(Var);
  3178. Assert(curOutParams + argSizes[0] + argSizes[1] + 16 <= (byte*)this->m_outParamsEnd);
  3179. // Prepare in advance the possible arguments that will need to be put in register
  3180. byte _declspec(align(16)) reg[3 * 16];
  3181. CompileAssert((FunctionBody::MinAsmJsOutParams() * sizeof(Var)) == (sizeof(Var) * 2 + sizeof(reg)));
  3182. js_memcpy_s(reg, 16, curOutParams, 16);
  3183. js_memcpy_s(reg + 16, 16, curOutParams + argSizes[0], 16);
  3184. js_memcpy_s(reg + 32, 16, curOutParams + argSizes[0] + argSizes[1], 16);
  3185. #else
  3186. byte* reg = nullptr;
  3187. #endif
  3188. ScriptContext * scriptContext = function->GetScriptContext();
  3189. Js::FunctionEntryPointInfo* entrypointInfo = (Js::FunctionEntryPointInfo*)function->GetEntryPointInfo();
  3190. PROBE_STACK_CALL(scriptContext, function, alignedArgsSize + Js::Constants::MinStackDefault);
  3191. switch (asmInfo->GetReturnType().which())
  3192. {
  3193. case AsmJsRetType::Void:
  3194. JavascriptFunction::CallAsmJsFunction<int>(function, entrypointInfo->jsMethod, m_outParams, alignedArgsSize, reg);
  3195. break;
  3196. case AsmJsRetType::Signed:
  3197. m_localIntSlots[returnReg] = JavascriptFunction::CallAsmJsFunction<int>(function, entrypointInfo->jsMethod, m_outParams, alignedArgsSize, reg);
  3198. break;
  3199. case AsmJsRetType::Int64:
  3200. m_localInt64Slots[returnReg] = JavascriptFunction::CallAsmJsFunction<int64>(function, entrypointInfo->jsMethod, m_outParams, alignedArgsSize, reg);
  3201. break;
  3202. case AsmJsRetType::Double:
  3203. m_localDoubleSlots[returnReg] = JavascriptFunction::CallAsmJsFunction<double>(function, entrypointInfo->jsMethod, m_outParams, alignedArgsSize, reg);
  3204. break;
  3205. case AsmJsRetType::Float:
  3206. m_localFloatSlots[returnReg] = JavascriptFunction::CallAsmJsFunction<float>(function, entrypointInfo->jsMethod, m_outParams, alignedArgsSize, reg);
  3207. break;
  3208. #ifdef ENABLE_WASM_SIMD
  3209. case AsmJsRetType::Float32x4:
  3210. case AsmJsRetType::Int32x4:
  3211. case AsmJsRetType::Bool32x4:
  3212. case AsmJsRetType::Bool16x8:
  3213. case AsmJsRetType::Bool8x16:
  3214. case AsmJsRetType::Float64x2:
  3215. case AsmJsRetType::Int16x8:
  3216. case AsmJsRetType::Int8x16:
  3217. case AsmJsRetType::Uint32x4:
  3218. case AsmJsRetType::Uint16x8:
  3219. case AsmJsRetType::Uint8x16:
  3220. #if _WIN32 //WASM.SIMD ToDo: Enable thunk for Xplat
  3221. #if _M_X64
  3222. X86SIMDValue simdVal;
  3223. simdVal.m128_value = JavascriptFunction::CallAsmJsFunction<__m128>(function, entrypointInfo->jsMethod, m_outParams, alignedArgsSize, reg);
  3224. m_localSimdSlots[returnReg] = X86SIMDValue::ToSIMDValue(simdVal);
  3225. #else
  3226. m_localSimdSlots[returnReg] = JavascriptFunction::CallAsmJsFunction<AsmJsSIMDValue>(function, entrypointInfo->jsMethod, m_outParams, alignedArgsSize, reg);
  3227. #endif
  3228. #endif
  3229. break;
  3230. #endif
  3231. default:
  3232. Assume(UNREACHED);
  3233. }
  3234. const ArgSlot nVarToPop = (asmInfo->GetArgByteSize() / sizeof(Var)) + 1;
  3235. PopOut(nVarToPop);
  3236. Assert(function);
  3237. }
  3238. #endif
  3239. template <class T>
  3240. void InterpreterStackFrame::OP_AsmCall(const unaligned T* playout)
  3241. {
  3242. Var target = GetRegRawPtr(playout->Function);
  3243. RecyclableObject * function = OP_CallGetFunc(target);
  3244. #if DBG
  3245. if (this->IsInDebugMode())
  3246. {
  3247. JavascriptFunction::CheckValidDebugThunk(scriptContext, function);
  3248. }
  3249. #endif
  3250. if (playout->Return == Js::Constants::NoRegister)
  3251. {
  3252. Arguments args(CallInfo(CallFlags_NotUsed, playout->ArgCount), m_outParams);
  3253. JavascriptFunction::CallFunction<true>(function, function->GetEntryPoint(), args);
  3254. }
  3255. else
  3256. {
  3257. Arguments args(CallInfo(CallFlags_Value, playout->ArgCount), m_outParams);
  3258. Var retVal = JavascriptFunction::CallFunction<true>(function, function->GetEntryPoint(), args);
  3259. SetRegRawPtr(playout->Return, retVal);
  3260. }
  3261. PopOut(playout->ArgCount);
  3262. }
  3263. template <class T>
  3264. void InterpreterStackFrame::OP_EnsureHeapAttached(const unaligned T* playout)
  3265. {
  3266. AsmJsModuleInfo::EnsureHeapAttached(this->function);
  3267. }
  3268. template <class T>
  3269. void InterpreterStackFrame::OP_CallCommon(const unaligned T * playout, RecyclableObject * function, unsigned flags, const Js::AuxArray<uint32> *spreadIndices)
  3270. {
  3271. // Always save and restore implicit call flags when calling out
  3272. // REVIEW: Can we avoid it if we don't collect dynamic profile info?
  3273. ThreadContext * threadContext = scriptContext->GetThreadContext();
  3274. Js::ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  3275. #ifdef ENABLE_SCRIPT_DEBUGGING
  3276. #if DBG
  3277. if (this->IsInDebugMode())
  3278. {
  3279. JavascriptFunction::CheckValidDebugThunk(scriptContext, function);
  3280. }
  3281. #endif
  3282. #endif
  3283. ArgSlot argCount = playout->ArgCount;
  3284. if (playout->Return == Js::Constants::NoRegister)
  3285. {
  3286. flags |= CallFlags_NotUsed;
  3287. Arguments args(CallInfo((CallFlags)flags, argCount), m_outParams);
  3288. AssertMsg(static_cast<unsigned>(args.Info.Flags) == flags, "Flags don't fit into the CallInfo field?");
  3289. argCount = args.GetArgCountWithExtraArgs();
  3290. if (spreadIndices != nullptr)
  3291. {
  3292. JavascriptFunction::CallSpreadFunction(function, args, spreadIndices);
  3293. }
  3294. else
  3295. {
  3296. JavascriptFunction::CallFunction<true>(function, function->GetEntryPoint(), args);
  3297. }
  3298. }
  3299. else
  3300. {
  3301. flags |= CallFlags_Value;
  3302. Arguments args(CallInfo((CallFlags)flags, argCount), m_outParams);
  3303. AssertMsg(static_cast<unsigned>(args.Info.Flags) == flags, "Flags don't fit into the CallInfo field?");
  3304. argCount = args.GetArgCountWithExtraArgs();
  3305. if (spreadIndices != nullptr)
  3306. {
  3307. SetReg((RegSlot)playout->Return, JavascriptFunction::CallSpreadFunction(function, args, spreadIndices));
  3308. }
  3309. else
  3310. {
  3311. SetReg((RegSlot)playout->Return, JavascriptFunction::CallFunction<true>(function, function->GetEntryPoint(), args));
  3312. }
  3313. }
  3314. threadContext->SetImplicitCallFlags(savedImplicitCallFlags);
  3315. PopOut(argCount);
  3316. }
  3317. template <class T>
  3318. void InterpreterStackFrame::OP_CallCommonI(const unaligned T * playout, RecyclableObject * function, unsigned flags)
  3319. {
  3320. OP_CallCommon(playout, function, flags); // CallCommon doesn't do anything with Member
  3321. }
  3322. #if ENABLE_PROFILE_INFO
  3323. template <class T>
  3324. void InterpreterStackFrame::OP_ProfileCallCommon(const unaligned T * playout, RecyclableObject * function, unsigned flags, ProfileId profileId, InlineCacheIndex inlineCacheIndex, const Js::AuxArray<uint32> *spreadIndices)
  3325. {
  3326. FunctionBody* functionBody = this->m_functionBody;
  3327. DynamicProfileInfo * dynamicProfileInfo = functionBody->GetDynamicProfileInfo();
  3328. FunctionInfo* functionInfo = function->GetTypeId() == TypeIds_Function?
  3329. JavascriptFunction::FromVar(function)->GetFunctionInfo() : nullptr;
  3330. bool isConstructorCall = (CallFlags_New & flags) == CallFlags_New;
  3331. dynamicProfileInfo->RecordCallSiteInfo(functionBody, profileId, functionInfo, functionInfo ? static_cast<JavascriptFunction*>(function) : nullptr, playout->ArgCount, isConstructorCall, inlineCacheIndex);
  3332. OP_CallCommon<T>(playout, function, flags, spreadIndices);
  3333. if (playout->Return != Js::Constants::NoRegister)
  3334. {
  3335. dynamicProfileInfo->RecordReturnTypeOnCallSiteInfo(functionBody, profileId, GetReg((RegSlot)playout->Return));
  3336. }
  3337. }
  3338. template <class T>
  3339. void InterpreterStackFrame::OP_ProfileReturnTypeCallCommon(const unaligned T * playout, RecyclableObject * function, unsigned flags, ProfileId profileId, const Js::AuxArray<uint32> *spreadIndices)
  3340. {
  3341. OP_CallCommon<T>(playout, function, flags, spreadIndices);
  3342. FunctionBody* functionBody = this->m_functionBody;
  3343. DynamicProfileInfo * dynamicProfileInfo = functionBody->GetDynamicProfileInfo();
  3344. if (playout->Return != Js::Constants::NoRegister)
  3345. {
  3346. dynamicProfileInfo->RecordReturnType(functionBody, profileId, GetReg((RegSlot)playout->Return));
  3347. }
  3348. }
  3349. #endif
  3350. template <class T>
  3351. void InterpreterStackFrame::OP_GetRootProperty(unaligned T* playout)
  3352. {
  3353. // Same fast path as in the backend.
  3354. Assert(playout->inlineCacheIndex >= this->m_functionBody->GetRootObjectLoadInlineCacheStart());
  3355. Js::Var instance = this->GetRootObject();
  3356. InlineCache *inlineCache = this->GetInlineCache(playout->inlineCacheIndex);
  3357. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3358. DynamicObject * obj = DynamicObject::UnsafeFromVar(instance);
  3359. PropertyValueInfo info;
  3360. PropertyValueInfo::SetCacheInfo(&info, GetFunctionBody(), inlineCache, playout->inlineCacheIndex, true);
  3361. Var value;
  3362. if(CacheOperators::TryGetProperty<true, false, false, false, false, false, true, false, false, false>(
  3363. obj, true, obj, propertyId, &value, GetScriptContext(), nullptr, &info))
  3364. {
  3365. SetReg(playout->Value, value);
  3366. return;
  3367. }
  3368. OP_GetRootProperty_NoFastPath(playout);
  3369. }
  3370. template <class T>
  3371. void InterpreterStackFrame::OP_GetRootPropertyForTypeOf(unaligned T* playout)
  3372. {
  3373. Var rootInstance = GetRootObject();
  3374. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3375. Var value = JavascriptOperators::PatchGetRootValueForTypeOf<false>(
  3376. GetFunctionBody(),
  3377. GetInlineCache(playout->inlineCacheIndex),
  3378. playout->inlineCacheIndex,
  3379. DynamicObject::UnsafeFromVar(rootInstance),
  3380. propertyId
  3381. );
  3382. SetReg(playout->Value, value);
  3383. #ifdef TELEMETRY_INTERPRETER
  3384. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  3385. {
  3386. // `successful` will be true as PatchGetRootValue throws an exception if not found.
  3387. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().GetProperty(rootInstance, propertyId, value, /*successful:*/true);
  3388. }
  3389. #endif
  3390. }
  3391. template <class T>
  3392. _NOINLINE void InterpreterStackFrame::OP_GetRootProperty_NoFastPath(unaligned T* playout)
  3393. {
  3394. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3395. Var rootInstance = this->GetRootObject();
  3396. Var value = JavascriptOperators::PatchGetRootValue<false>(
  3397. GetFunctionBody(),
  3398. GetInlineCache(playout->inlineCacheIndex),
  3399. playout->inlineCacheIndex,
  3400. DynamicObject::UnsafeFromVar(rootInstance),
  3401. propertyId
  3402. );
  3403. SetReg(playout->Value, value);
  3404. #ifdef TELEMETRY_INTERPRETER
  3405. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  3406. {
  3407. // `successful` will be true as PatchGetRootValue throws an exception if not found.
  3408. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().GetProperty(rootInstance, propertyId, value, /*successful:*/true);
  3409. }
  3410. #endif
  3411. }
  3412. #if ENABLE_PROFILE_INFO
  3413. template <class T>
  3414. void InterpreterStackFrame::UpdateFldInfoFlagsForGetSetInlineCandidate(unaligned T* playout, FldInfoFlags& fldInfoFlags, CacheType cacheType,
  3415. DynamicProfileInfo * dynamicProfileInfo, uint inlineCacheIndex, RecyclableObject * obj)
  3416. {
  3417. RecyclableObject *callee = nullptr;
  3418. //TODO: Setter case once we stop sharing inline caches for these callsites.
  3419. if ((cacheType & (CacheType_Getter | CacheType_Setter)) && GetInlineCache(inlineCacheIndex)->GetGetterSetter(obj->GetType(), &callee))
  3420. {
  3421. const auto functionBody = this->m_functionBody;
  3422. bool canInline = dynamicProfileInfo->RecordLdFldCallSiteInfo(functionBody, callee, false /*callApplyTarget*/);
  3423. if (canInline)
  3424. {
  3425. //updates this fldInfoFlags passed by reference.
  3426. fldInfoFlags = DynamicProfileInfo::MergeFldInfoFlags(fldInfoFlags, FldInfo_InlineCandidate);
  3427. }
  3428. }
  3429. }
  3430. template <class T>
  3431. void InterpreterStackFrame::UpdateFldInfoFlagsForCallApplyInlineCandidate(unaligned T* playout, FldInfoFlags& fldInfoFlags, CacheType cacheType,
  3432. DynamicProfileInfo * dynamicProfileInfo, uint inlineCacheIndex, RecyclableObject * obj)
  3433. {
  3434. RecyclableObject *callee = nullptr;
  3435. if (!(fldInfoFlags & FldInfo_Polymorphic) && GetInlineCache(inlineCacheIndex)->GetCallApplyTarget(obj, &callee))
  3436. {
  3437. const auto functionBody = this->m_functionBody;
  3438. bool canInline = dynamicProfileInfo->RecordLdFldCallSiteInfo(functionBody, callee, true /*callApplyTarget*/);
  3439. if (canInline)
  3440. {
  3441. //updates this fldInfoFlags passed by reference.
  3442. fldInfoFlags = DynamicProfileInfo::MergeFldInfoFlags(fldInfoFlags, FldInfo_InlineCandidate);
  3443. }
  3444. }
  3445. }
  3446. template <class T, bool Root, bool Method, bool CallApplyTarget>
  3447. void InterpreterStackFrame::ProfiledGetProperty(unaligned T* playout, const Var instance)
  3448. {
  3449. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3450. Var value = ProfilingHelpers::ProfiledLdFld<Root, Method, CallApplyTarget>(
  3451. instance,
  3452. propertyId,
  3453. GetInlineCache(playout->inlineCacheIndex),
  3454. playout->inlineCacheIndex,
  3455. GetFunctionBody(),
  3456. instance);
  3457. SetReg(playout->Value, value);
  3458. #ifdef TELEMETRY_INTERPRETER
  3459. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  3460. {
  3461. // `successful` will be true as PatchGetRootValue throws an exception if not found.
  3462. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().GetProperty(instance, propertyId, value, /*successful:*/true);
  3463. }
  3464. #endif
  3465. }
  3466. template <class T>
  3467. void InterpreterStackFrame::OP_ProfiledGetRootProperty(unaligned T* playout)
  3468. {
  3469. ProfiledGetProperty<T, true, false, false>(playout, GetRootObject());
  3470. }
  3471. template <class T>
  3472. void InterpreterStackFrame::OP_ProfiledGetRootPropertyForTypeOf(unaligned T* playout)
  3473. {
  3474. Var rootInstance = GetRootObject();
  3475. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3476. Var value = ProfilingHelpers::ProfiledLdFldForTypeOf<true, false, false>(
  3477. rootInstance,
  3478. propertyId,
  3479. GetInlineCache(playout->inlineCacheIndex),
  3480. playout->inlineCacheIndex,
  3481. GetFunctionBody());
  3482. SetReg(playout->Value, value);
  3483. #ifdef TELEMETRY_INTERPRETER
  3484. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  3485. {
  3486. // `successful` will be true as PatchGetRootValue throws an exception if not found.
  3487. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().GetProperty(rootInstance, propertyId, value, /*successful:*/true);
  3488. }
  3489. #endif
  3490. }
  3491. #endif
  3492. template <class T>
  3493. void InterpreterStackFrame::OP_GetPropertyForTypeOf(unaligned T* playout)
  3494. {
  3495. Var instance = GetReg(playout->Instance);
  3496. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3497. Var value = JavascriptOperators::PatchGetValueForTypeOf<false>(
  3498. GetFunctionBody(),
  3499. GetInlineCache(playout->inlineCacheIndex),
  3500. playout->inlineCacheIndex,
  3501. instance,
  3502. propertyId
  3503. );
  3504. SetReg(playout->Value, value);
  3505. #ifdef TELEMETRY_INTERPRETER
  3506. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  3507. {
  3508. // `successful` will be true as PatchGetRootValue throws an exception if not found.
  3509. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().GetProperty(instance, propertyId, value, /*successful:*/true);
  3510. }
  3511. #endif
  3512. }
  3513. template <class T>
  3514. void InterpreterStackFrame::OP_GetProperty(unaligned T* playout)
  3515. {
  3516. // Same fast path as in the backend.
  3517. Var instance = GetReg(playout->Instance);
  3518. OP_GetProperty(instance, playout);
  3519. }
  3520. template <class T>
  3521. void InterpreterStackFrame::OP_GetLocalProperty(unaligned T* playout)
  3522. {
  3523. // Same fast path as in the backend.
  3524. Var instance = this->localClosure;
  3525. OP_GetProperty(instance, playout);
  3526. }
  3527. template <class T>
  3528. void InterpreterStackFrame::OP_GetProperty(Var instance, unaligned T* playout)
  3529. {
  3530. InlineCache *inlineCache = GetInlineCache(playout->inlineCacheIndex);
  3531. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3532. RecyclableObject* obj = JavascriptOperators::TryFromVar<RecyclableObject>(instance);
  3533. if (obj)
  3534. {
  3535. PropertyValueInfo info;
  3536. PropertyValueInfo::SetCacheInfo(&info, GetFunctionBody(), inlineCache, playout->inlineCacheIndex, true);
  3537. Var value;
  3538. if (CacheOperators::TryGetProperty<true, false, false, false, false, false, true, false, false, false>(
  3539. obj, false, obj, propertyId, &value, GetScriptContext(), nullptr, &info))
  3540. {
  3541. SetReg(playout->Value, value);
  3542. return;
  3543. }
  3544. }
  3545. OP_GetProperty_NoFastPath(instance, playout);
  3546. }
  3547. template <class T>
  3548. void InterpreterStackFrame::OP_GetSuperProperty(unaligned T* playout)
  3549. {
  3550. // Same fast path as in the backend.
  3551. Var instance = GetReg(playout->Instance);
  3552. Var thisInstance = GetReg(playout->Value2);
  3553. InlineCache *inlineCache = GetInlineCache(playout->PropertyIdIndex);
  3554. PropertyId propertyId = GetPropertyIdFromCacheId(playout->PropertyIdIndex);
  3555. if (RecyclableObject::Is(instance) && RecyclableObject::Is(thisInstance))
  3556. {
  3557. RecyclableObject* superObj = RecyclableObject::FromVar(instance);
  3558. RecyclableObject* thisObj = RecyclableObject::FromVar(thisInstance);
  3559. PropertyValueInfo info;
  3560. PropertyValueInfo::SetCacheInfo(&info, GetFunctionBody(), inlineCache, playout->PropertyIdIndex, true);
  3561. Var value;
  3562. if (CacheOperators::TryGetProperty<true, false, false, false, false, false, true, false, false, false>(
  3563. thisObj, false, superObj, propertyId, &value, GetScriptContext(), nullptr, &info))
  3564. {
  3565. SetReg(playout->Value, value);
  3566. return;
  3567. }
  3568. }
  3569. SetReg(
  3570. playout->Value,
  3571. JavascriptOperators::PatchGetValueWithThisPtr<false>(
  3572. GetFunctionBody(),
  3573. GetInlineCache(playout->PropertyIdIndex),
  3574. playout->PropertyIdIndex,
  3575. GetReg(playout->Instance),
  3576. GetPropertyIdFromCacheId(playout->PropertyIdIndex),
  3577. GetReg(playout->Value2)));
  3578. }
  3579. template <class T>
  3580. _NOINLINE void InterpreterStackFrame::OP_GetProperty_NoFastPath(Var instance, unaligned T* playout)
  3581. {
  3582. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3583. Var value = JavascriptOperators::PatchGetValue<false>(
  3584. GetFunctionBody(),
  3585. GetInlineCache(playout->inlineCacheIndex),
  3586. playout->inlineCacheIndex,
  3587. instance,
  3588. propertyId
  3589. );
  3590. #ifdef TELEMETRY_INTERPRETER
  3591. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  3592. {
  3593. // `successful` will be true as PatchGetMethod throws an exception if not found.
  3594. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().GetProperty(instance, propertyId, value, true);
  3595. }
  3596. #endif
  3597. SetReg(playout->Value, value);
  3598. }
  3599. #if ENABLE_PROFILE_INFO
  3600. template <class T>
  3601. void InterpreterStackFrame::OP_ProfiledGetProperty(unaligned T* playout)
  3602. {
  3603. ProfiledGetProperty<T, false, false, false>(playout, GetReg(playout->Instance));
  3604. }
  3605. template <class T>
  3606. void InterpreterStackFrame::OP_ProfiledGetLocalProperty(unaligned T* playout)
  3607. {
  3608. ProfiledGetProperty<T, false, false, false>(playout, this->localClosure);
  3609. }
  3610. template <class T>
  3611. void InterpreterStackFrame::OP_ProfiledGetSuperProperty(unaligned T* playout)
  3612. {
  3613. SetReg(
  3614. playout->Value,
  3615. ProfilingHelpers::ProfiledLdFld<false, false, false>(
  3616. GetReg(playout->Instance),
  3617. GetPropertyIdFromCacheId(playout->PropertyIdIndex),
  3618. GetInlineCache(playout->PropertyIdIndex),
  3619. playout->PropertyIdIndex,
  3620. GetFunctionBody(),
  3621. GetReg(playout->Value2)));
  3622. }
  3623. template <class T>
  3624. void InterpreterStackFrame::OP_ProfiledGetPropertyForTypeOf(unaligned T* playout)
  3625. {
  3626. Var instance = GetReg(playout->Instance);
  3627. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3628. Var value = ProfilingHelpers::ProfiledLdFldForTypeOf<false, false, false>(
  3629. instance,
  3630. propertyId,
  3631. GetInlineCache(playout->inlineCacheIndex),
  3632. playout->inlineCacheIndex,
  3633. GetFunctionBody()
  3634. );
  3635. SetReg(playout->Value, value);
  3636. #ifdef TELEMETRY_INTERPRETER
  3637. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  3638. {
  3639. // `successful` will be true as PatchGetMethod throws an exception if not found.
  3640. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().GetProperty(instance, propertyId, value, true);
  3641. }
  3642. #endif
  3643. }
  3644. template <class T>
  3645. void InterpreterStackFrame::OP_ProfiledGetPropertyCallApplyTarget(unaligned T* playout)
  3646. {
  3647. ProfiledGetProperty<T, false, false, true>(playout, GetReg(playout->Instance));
  3648. }
  3649. #endif
  3650. template <typename T>
  3651. void InterpreterStackFrame::OP_GetPropertyScoped(const unaligned OpLayoutT_ElementP<T>* playout)
  3652. {
  3653. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  3654. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  3655. threadContext->ClearImplicitCallFlags();
  3656. // Get the property, using a scope stack rather than an individual instance.
  3657. // Use the cache
  3658. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3659. FrameDisplay *pScope = this->GetEnvForEvalCode();
  3660. InlineCache *inlineCache = this->GetInlineCache(playout->inlineCacheIndex);
  3661. ScriptContext* scriptContext = GetScriptContext();
  3662. int length = pScope->GetLength();
  3663. if ( 1 == length )
  3664. {
  3665. RecyclableObject *obj = RecyclableObject::FromVar(pScope->GetItem(0));
  3666. PropertyValueInfo info;
  3667. PropertyValueInfo::SetCacheInfo(&info, GetFunctionBody(), inlineCache, playout->inlineCacheIndex, true);
  3668. Var value;
  3669. if (CacheOperators::TryGetProperty<true, false, false, false, false, false, true, false, false, false>(
  3670. obj, false, obj, propertyId, &value, scriptContext, nullptr, &info))
  3671. {
  3672. threadContext->CheckAndResetImplicitCallAccessorFlag();
  3673. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  3674. SetReg(playout->Value, value);
  3675. return;
  3676. }
  3677. }
  3678. OP_GetPropertyScoped_NoFastPath(playout);
  3679. threadContext->CheckAndResetImplicitCallAccessorFlag();
  3680. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  3681. }
  3682. template <typename T>
  3683. void InterpreterStackFrame::OP_GetPropertyForTypeOfScoped(const unaligned OpLayoutT_ElementP<T>* playout)
  3684. {
  3685. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  3686. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  3687. threadContext->ClearImplicitCallFlags();
  3688. // Get the property, using a scope stack rather than an individual instance.
  3689. // Use the cache
  3690. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3691. FrameDisplay *pScope = this->GetEnvForEvalCode();
  3692. InlineCache *inlineCache = this->GetInlineCache(playout->inlineCacheIndex);
  3693. ScriptContext* scriptContext = GetScriptContext();
  3694. int length = pScope->GetLength();
  3695. if (1 == length)
  3696. {
  3697. DynamicObject *obj = (DynamicObject*)pScope->GetItem(0);
  3698. PropertyValueInfo info;
  3699. PropertyValueInfo::SetCacheInfo(&info, GetFunctionBody(), inlineCache, playout->inlineCacheIndex, true);
  3700. Var value;
  3701. if (CacheOperators::TryGetProperty<true, false, false, false, false, false, true, false, false, false>(
  3702. obj, false, obj, propertyId, &value, scriptContext, nullptr, &info))
  3703. {
  3704. threadContext->CheckAndResetImplicitCallAccessorFlag();
  3705. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  3706. SetReg(playout->Value, value);
  3707. return;
  3708. }
  3709. }
  3710. SetReg(
  3711. playout->Value,
  3712. JavascriptOperators::PatchGetPropertyForTypeOfScoped<false>(
  3713. GetFunctionBody(),
  3714. GetInlineCache(playout->inlineCacheIndex),
  3715. playout->inlineCacheIndex,
  3716. GetEnvForEvalCode(),
  3717. GetPropertyIdFromCacheId(playout->inlineCacheIndex),
  3718. GetReg(Js::FunctionBody::RootObjectRegSlot)));
  3719. threadContext->CheckAndResetImplicitCallAccessorFlag();
  3720. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  3721. }
  3722. template <typename T>
  3723. _NOINLINE void InterpreterStackFrame::OP_GetPropertyScoped_NoFastPath(const unaligned OpLayoutT_ElementP<T>* playout)
  3724. {
  3725. // Implicit root object as default instance
  3726. Var defaultInstance = GetReg(Js::FunctionBody::RootObjectRegSlot);
  3727. // PatchGetPropertyScoped doesn't update type and slotIndex if the scope is not an array of length 1.
  3728. SetReg(
  3729. playout->Value,
  3730. JavascriptOperators::PatchGetPropertyScoped<false>(
  3731. GetFunctionBody(),
  3732. GetInlineCache(playout->inlineCacheIndex),
  3733. playout->inlineCacheIndex,
  3734. GetEnvForEvalCode(),
  3735. GetPropertyIdFromCacheId(playout->inlineCacheIndex),
  3736. defaultInstance));
  3737. }
  3738. template <class T>
  3739. void InterpreterStackFrame::OP_SetPropertyScoped(unaligned T* playout, PropertyOperationFlags flags)
  3740. {
  3741. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  3742. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  3743. threadContext->ClearImplicitCallFlags();
  3744. // Set the property, using a scope stack rather than an individual instance.
  3745. // Use the cache
  3746. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3747. FrameDisplay *pScope = this->GetEnvForEvalCode();
  3748. InlineCache *inlineCache = GetInlineCache(playout->inlineCacheIndex);
  3749. ScriptContext* scriptContext = GetScriptContext();
  3750. Var value = GetReg(playout->Value);
  3751. int length = pScope->GetLength();
  3752. if ( 1 == length )
  3753. {
  3754. RecyclableObject* obj = RecyclableObject::FromVar(pScope->GetItem(0));
  3755. PropertyValueInfo info;
  3756. PropertyValueInfo::SetCacheInfo(&info, GetFunctionBody(), inlineCache, playout->inlineCacheIndex, true);
  3757. if (CacheOperators::TrySetProperty<true, false, false, false, false, true, false, false>(
  3758. obj, false, propertyId, value, scriptContext, flags, nullptr, &info))
  3759. {
  3760. threadContext->CheckAndResetImplicitCallAccessorFlag();
  3761. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  3762. return;
  3763. }
  3764. }
  3765. OP_SetPropertyScoped_NoFastPath(playout, flags);
  3766. threadContext->CheckAndResetImplicitCallAccessorFlag();
  3767. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  3768. }
  3769. template <class T>
  3770. _NOINLINE void InterpreterStackFrame::OP_SetPropertyScoped_NoFastPath(unaligned T* playout, PropertyOperationFlags flags)
  3771. {
  3772. // Implicit root object as default instance
  3773. Var defaultInstance = GetReg(Js::FunctionBody::RootObjectRegSlot);
  3774. // PatchSetPropertyScoped doesn't update type and slotIndex if the scope is not an array of length 1.
  3775. JavascriptOperators::PatchSetPropertyScoped<false>(
  3776. GetFunctionBody(),
  3777. GetInlineCache(playout->inlineCacheIndex),
  3778. playout->inlineCacheIndex,
  3779. GetEnvForEvalCode(),
  3780. GetPropertyIdFromCacheId(playout->inlineCacheIndex),
  3781. GetReg(playout->Value),
  3782. defaultInstance,
  3783. flags);
  3784. }
  3785. template <class T>
  3786. void InterpreterStackFrame::OP_SetPropertyScopedStrict(unaligned T* playout)
  3787. {
  3788. OP_SetPropertyScoped(playout, PropertyOperation_StrictMode);
  3789. }
  3790. template <class T>
  3791. void InterpreterStackFrame::OP_ConsoleSetPropertyScoped(unaligned T* playout)
  3792. {
  3793. OP_SetPropertyScoped(playout, PropertyOperation_AllowUndeclInConsoleScope);
  3794. }
  3795. template <class T>
  3796. void InterpreterStackFrame::OP_ConsoleSetPropertyScopedStrict(unaligned T* playout)
  3797. {
  3798. OP_SetPropertyScoped(playout, (PropertyOperationFlags)(PropertyOperation_StrictMode | PropertyOperation_AllowUndeclInConsoleScope));
  3799. }
  3800. template <class T>
  3801. inline bool InterpreterStackFrame::TrySetPropertyLocalFastPath(unaligned T* playout, PropertyId pid, RecyclableObject* instance, InlineCache*& inlineCache, PropertyOperationFlags flags)
  3802. {
  3803. inlineCache = this->GetInlineCache(playout->inlineCacheIndex);
  3804. PropertyValueInfo info;
  3805. PropertyValueInfo::SetCacheInfo(&info, GetFunctionBody(), inlineCache, playout->inlineCacheIndex, true);
  3806. return
  3807. CacheOperators::TrySetProperty<true, false, false, false, false, true, false, false>(
  3808. instance,
  3809. !!(flags & PropertyOperation_Root),
  3810. pid,
  3811. GetReg(playout->Value),
  3812. GetScriptContext(),
  3813. flags,
  3814. nullptr,
  3815. &info);
  3816. }
  3817. template <class T>
  3818. inline void InterpreterStackFrame::DoSetProperty(unaligned T* playout, Var instance, PropertyOperationFlags flags)
  3819. {
  3820. // Same fast path as in the backend.
  3821. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  3822. InlineCache *inlineCache;
  3823. if (!TaggedNumber::Is(instance)
  3824. && TrySetPropertyLocalFastPath(playout, propertyId, RecyclableObject::UnsafeFromVar(instance), inlineCache, flags))
  3825. {
  3826. if(GetJavascriptFunction()->GetConstructorCache()->NeedsUpdateAfterCtor())
  3827. {
  3828. // This function has only 'this' statements and is being used as a constructor. When the constructor exits, the
  3829. // function object's constructor cache will be updated with the type produced by the constructor. From that
  3830. // point on, when the same function object is used as a constructor, the a new object with the final type will
  3831. // be created. Whatever is stored in the inline cache currently will cause cache misses after the constructor
  3832. // cache update. So, just clear it now so that the caches won't be flagged as polymorphic.
  3833. inlineCache->RemoveFromInvalidationListAndClear(this->GetScriptContext()->GetThreadContext());
  3834. }
  3835. return;
  3836. }
  3837. DoSetProperty_NoFastPath(playout, instance, flags);
  3838. }
  3839. template <class T>
  3840. inline void InterpreterStackFrame::DoSetSuperProperty(unaligned T* playout, Var instance, PropertyOperationFlags flags)
  3841. {
  3842. DoSetSuperProperty_NoFastPath(playout, instance, m_functionBody->GetIsStrictMode() ?
  3843. (PropertyOperationFlags)(flags | PropertyOperation_StrictMode) : flags);
  3844. }
  3845. template <class T>
  3846. _NOINLINE void InterpreterStackFrame::DoSetProperty_NoFastPath(unaligned T* playout, Var instance, PropertyOperationFlags flags)
  3847. {
  3848. #if ENABLE_COPYONACCESS_ARRAY
  3849. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(instance);
  3850. #endif
  3851. InlineCache *const inlineCache = GetInlineCache(playout->inlineCacheIndex);
  3852. const auto PatchPutRootValue = &JavascriptOperators::PatchPutRootValueNoLocalFastPath<false, InlineCache>;
  3853. const auto PatchPutValue = &JavascriptOperators::PatchPutValueNoLocalFastPath<false, InlineCache>;
  3854. const auto PatchPut = flags & PropertyOperation_Root ? PatchPutRootValue : PatchPutValue;
  3855. PatchPut(
  3856. GetFunctionBody(),
  3857. inlineCache,
  3858. playout->inlineCacheIndex,
  3859. instance,
  3860. GetPropertyIdFromCacheId(playout->inlineCacheIndex),
  3861. GetReg(playout->Value),
  3862. flags);
  3863. if(!TaggedNumber::Is(instance) && GetJavascriptFunction()->GetConstructorCache()->NeedsUpdateAfterCtor())
  3864. {
  3865. // This function has only 'this' statements and is being used as a constructor. When the constructor exits, the
  3866. // function object's constructor cache will be updated with the type produced by the constructor. From that
  3867. // point on, when the same function object is used as a constructor, the a new object with the final type will
  3868. // be created. Whatever is stored in the inline cache currently will cause cache misses after the constructor
  3869. // cache update. So, just clear it now so that the caches won't be flagged as polymorphic.
  3870. inlineCache->RemoveFromInvalidationListAndClear(this->GetScriptContext()->GetThreadContext());
  3871. }
  3872. }
  3873. template <class T>
  3874. _NOINLINE void InterpreterStackFrame::DoSetSuperProperty_NoFastPath(unaligned T* playout, Var instance, PropertyOperationFlags flags)
  3875. {
  3876. #if ENABLE_COPYONACCESS_ARRAY
  3877. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(instance);
  3878. #endif
  3879. InlineCache *const inlineCache = GetInlineCache(playout->PropertyIdIndex);
  3880. JavascriptOperators::PatchPutValueWithThisPtrNoLocalFastPath<false, InlineCache>(
  3881. GetFunctionBody(),
  3882. inlineCache,
  3883. playout->PropertyIdIndex,
  3884. instance,
  3885. GetPropertyIdFromCacheId(playout->PropertyIdIndex),
  3886. GetReg(playout->Value),
  3887. GetReg(playout->Value2),
  3888. flags);
  3889. if (!TaggedNumber::Is(instance) && GetJavascriptFunction()->GetConstructorCache()->NeedsUpdateAfterCtor())
  3890. {
  3891. // This function has only 'this' statements and is being used as a constructor. When the constructor exits, the
  3892. // function object's constructor cache will be updated with the type produced by the constructor. From that
  3893. // point on, when the same function object is used as a constructor, the a new object with the final type will
  3894. // be created. Whatever is stored in the inline cache currently will cause cache misses after the constructor
  3895. // cache update. So, just clear it now so that the caches won't be flagged as polymorphic.
  3896. inlineCache->RemoveFromInvalidationListAndClear(this->GetScriptContext()->GetThreadContext());
  3897. }
  3898. }
  3899. #if ENABLE_PROFILE_INFO
  3900. template <class T, bool Root>
  3901. void InterpreterStackFrame::ProfiledSetProperty(unaligned T* playout, Var instance, PropertyOperationFlags flags)
  3902. {
  3903. Assert(!Root || flags & PropertyOperation_Root);
  3904. ProfilingHelpers::ProfiledStFld<Root>(
  3905. instance,
  3906. GetPropertyIdFromCacheId(playout->inlineCacheIndex),
  3907. GetInlineCache(playout->inlineCacheIndex),
  3908. playout->inlineCacheIndex,
  3909. GetReg(playout->Value),
  3910. flags,
  3911. GetJavascriptFunction(),
  3912. instance);
  3913. }
  3914. template <class T, bool Root>
  3915. void InterpreterStackFrame::ProfiledSetSuperProperty(unaligned T* playout, Var instance, Var thisInstance, PropertyOperationFlags flags)
  3916. {
  3917. Assert(!Root || flags & PropertyOperation_Root);
  3918. ProfilingHelpers::ProfiledStFld<Root>(
  3919. instance,
  3920. GetPropertyIdFromCacheId(playout->PropertyIdIndex),
  3921. GetInlineCache(playout->PropertyIdIndex),
  3922. playout->PropertyIdIndex,
  3923. GetReg(playout->Value),
  3924. m_functionBody->GetIsStrictMode() ?
  3925. (PropertyOperationFlags)(flags | PropertyOperation_StrictMode ) : flags,
  3926. GetJavascriptFunction(),
  3927. thisInstance);
  3928. }
  3929. #endif
  3930. template <class T>
  3931. void InterpreterStackFrame::OP_SetProperty(unaligned T* playout)
  3932. {
  3933. DoSetProperty(playout, GetReg(playout->Instance), PropertyOperation_None);
  3934. }
  3935. template <class T>
  3936. void InterpreterStackFrame::OP_SetLocalProperty(unaligned T* playout)
  3937. {
  3938. DoSetProperty(playout, this->localClosure, PropertyOperation_None);
  3939. }
  3940. template <class T>
  3941. void InterpreterStackFrame::OP_SetSuperProperty(unaligned T* playout)
  3942. {
  3943. DoSetSuperProperty(playout, GetReg(playout->Instance), PropertyOperation_None);
  3944. }
  3945. template <class T>
  3946. void InterpreterStackFrame::OP_ProfiledSetProperty(unaligned T* playout)
  3947. {
  3948. ProfiledSetProperty<T, false>(playout, GetReg(playout->Instance), PropertyOperation_None);
  3949. }
  3950. template <class T>
  3951. void InterpreterStackFrame::OP_ProfiledSetLocalProperty(unaligned T* playout)
  3952. {
  3953. ProfiledSetProperty<T, false>(playout, this->localClosure, PropertyOperation_None);
  3954. }
  3955. template <class T>
  3956. void InterpreterStackFrame::OP_ProfiledSetSuperProperty(unaligned T* playout)
  3957. {
  3958. ProfiledSetSuperProperty<T, false>(playout, GetReg(playout->Instance), GetReg(playout->Value2), PropertyOperation_None);
  3959. }
  3960. template <class T>
  3961. void InterpreterStackFrame::OP_SetRootProperty(unaligned T* playout)
  3962. {
  3963. DoSetProperty(playout, this->GetRootObject(), PropertyOperation_Root);
  3964. }
  3965. template <class T>
  3966. void InterpreterStackFrame::OP_ProfiledSetRootProperty(unaligned T* playout)
  3967. {
  3968. ProfiledSetProperty<T, true>(playout, this->GetRootObject(), PropertyOperation_Root);
  3969. }
  3970. template <class T>
  3971. void InterpreterStackFrame::OP_SetPropertyStrict(unaligned T* playout)
  3972. {
  3973. DoSetProperty(playout, GetReg(playout->Instance), PropertyOperation_StrictMode);
  3974. }
  3975. template <class T>
  3976. void InterpreterStackFrame::OP_ProfiledSetPropertyStrict(unaligned T* playout)
  3977. {
  3978. ProfiledSetProperty<T, false>(playout, GetReg(playout->Instance), PropertyOperation_StrictMode);
  3979. }
  3980. template <class T>
  3981. void InterpreterStackFrame::OP_SetRootPropertyStrict(unaligned T* playout)
  3982. {
  3983. DoSetProperty(playout, this->GetRootObject(), PropertyOperation_StrictModeRoot);
  3984. }
  3985. template <class T>
  3986. void InterpreterStackFrame::OP_ProfiledSetRootPropertyStrict(unaligned T* playout)
  3987. {
  3988. ProfiledSetProperty<T, true>(playout, this->GetRootObject(), PropertyOperation_StrictModeRoot);
  3989. }
  3990. #if ENABLE_PROFILE_INFO
  3991. template <bool doProfile>
  3992. Var InterpreterStackFrame::ProfiledDivide(Var aLeft, Var aRight, ScriptContext* scriptContext, ProfileId profileId)
  3993. {
  3994. Var result = JavascriptMath::Divide(aLeft, aRight,scriptContext);
  3995. if (doProfile)
  3996. {
  3997. Js::FunctionBody* body = this->m_functionBody;
  3998. body->GetDynamicProfileInfo()->RecordDivideResultType(body, profileId, result);
  3999. }
  4000. return result;
  4001. }
  4002. template <bool doProfile>
  4003. Var InterpreterStackFrame::ProfileModulus(Var aLeft, Var aRight, ScriptContext* scriptContext, ProfileId profileId)
  4004. {
  4005. // If both arguments are TaggedInt, then try to do integer division
  4006. // This case is not handled by the lowerer.
  4007. if (doProfile)
  4008. {
  4009. Js::FunctionBody* body = this->function->GetFunctionBody();
  4010. if(TaggedInt::IsPair(aLeft, aRight))
  4011. {
  4012. int nLeft = TaggedInt::ToInt32(aLeft);
  4013. int nRight = TaggedInt::ToInt32(aRight);
  4014. // nLeft is positive and nRight is +2^i
  4015. // Fast path for Power of 2 divisor
  4016. if (nLeft > 0 && ::Math::IsPow2(nRight))
  4017. {
  4018. body->GetDynamicProfileInfo()->RecordModulusOpType(body, profileId, /*isModByPowerOf2*/ true);
  4019. return TaggedInt::ToVarUnchecked(nLeft & (nRight - 1));
  4020. }
  4021. }
  4022. body->GetDynamicProfileInfo()->RecordModulusOpType(body, profileId, /*isModByPowerOf2*/ false);
  4023. }
  4024. return JavascriptMath::Modulus(aLeft, aRight,scriptContext);
  4025. }
  4026. template <bool doProfile>
  4027. Var InterpreterStackFrame::ProfiledSwitch(Var exp, ProfileId profileId)
  4028. {
  4029. if (doProfile)
  4030. {
  4031. Js::FunctionBody* body = this->m_functionBody;
  4032. body->GetDynamicProfileInfo()->RecordSwitchType(body, profileId, exp);
  4033. }
  4034. return exp;
  4035. }
  4036. #else
  4037. template <bool doProfile>
  4038. Var InterpreterStackFrame::ProfiledDivide(Var aLeft, Var aRight, ScriptContext* scriptContext, ProfileId profileId)
  4039. {
  4040. Assert(!doProfile);
  4041. return JavascriptMath::Divide(aLeft, aRight, scriptContext);
  4042. }
  4043. template <bool doProfile>
  4044. Var InterpreterStackFrame::ProfileModulus(Var aLeft, Var aRight, ScriptContext* scriptContext, ProfileId profileId)
  4045. {
  4046. Assert(!doProfile);
  4047. return JavascriptMath::Modulus(aLeft, aRight, scriptContext);
  4048. }
  4049. template <bool doProfile>
  4050. Var InterpreterStackFrame::ProfiledSwitch(Var exp, ProfileId profileId)
  4051. {
  4052. Assert(!doProfile);
  4053. return exp;
  4054. }
  4055. #endif
  4056. template <class T>
  4057. void InterpreterStackFrame::DoInitProperty(unaligned T* playout, Var instance)
  4058. {
  4059. // Same fast path as in the backend.
  4060. InlineCache *inlineCache = nullptr;
  4061. Assert(!TaggedNumber::Is(instance));
  4062. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  4063. if (TrySetPropertyLocalFastPath(playout, propertyId, RecyclableObject::UnsafeFromVar(instance), inlineCache))
  4064. {
  4065. return;
  4066. }
  4067. DoInitProperty_NoFastPath(playout, instance);
  4068. }
  4069. template <class T>
  4070. _NOINLINE void InterpreterStackFrame::DoInitProperty_NoFastPath(unaligned T* playout, Var instance)
  4071. {
  4072. JavascriptOperators::PatchInitValue<false>(
  4073. GetFunctionBody(),
  4074. GetInlineCache(playout->inlineCacheIndex),
  4075. playout->inlineCacheIndex,
  4076. RecyclableObject::FromVar(instance),
  4077. GetPropertyIdFromCacheId(playout->inlineCacheIndex),
  4078. GetReg(playout->Value));
  4079. }
  4080. template <class T>
  4081. void InterpreterStackFrame::OP_InitClassMember(const unaligned T * playout)
  4082. {
  4083. uint inlineCacheIndex = playout->inlineCacheIndex;
  4084. InlineCache * inlineCache = this->GetInlineCache(inlineCacheIndex);
  4085. Var instance = GetReg(playout->Instance);
  4086. PropertyOperationFlags flags = PropertyOperation_None;
  4087. Assert(!TaggedNumber::Is(instance));
  4088. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  4089. if (!TrySetPropertyLocalFastPath(playout, propertyId, RecyclableObject::UnsafeFromVar(instance), inlineCache, flags))
  4090. {
  4091. JavascriptOperators::OP_InitClassMember(instance, propertyId, GetReg(playout->Value));
  4092. }
  4093. }
  4094. template <class T>
  4095. void InterpreterStackFrame::OP_InitClassMemberGet(const unaligned T * playout)
  4096. {
  4097. JavascriptOperators::OP_InitClassMemberGet(
  4098. GetReg(playout->Instance),
  4099. m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex),
  4100. GetReg(playout->Value));
  4101. }
  4102. template <class T>
  4103. void InterpreterStackFrame::OP_InitClassMemberSet(const unaligned T * playout)
  4104. {
  4105. JavascriptOperators::OP_InitClassMemberSet(
  4106. GetReg(playout->Instance),
  4107. m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex),
  4108. GetReg(playout->Value));
  4109. }
  4110. template <class T>
  4111. void InterpreterStackFrame::OP_InitClassMemberSetComputedName(const unaligned T * playout)
  4112. {
  4113. JavascriptOperators::OP_InitClassMemberSetComputedName(
  4114. GetReg(playout->Instance),
  4115. GetReg(playout->Element),
  4116. GetReg(playout->Value),
  4117. m_functionBody->GetScriptContext());
  4118. }
  4119. template <class T>
  4120. void InterpreterStackFrame::OP_InitClassMemberGetComputedName(const unaligned T * playout)
  4121. {
  4122. JavascriptOperators::OP_InitClassMemberGetComputedName(
  4123. GetReg(playout->Instance),
  4124. GetReg(playout->Element),
  4125. GetReg(playout->Value),
  4126. m_functionBody->GetScriptContext());
  4127. }
  4128. template <class T>
  4129. void InterpreterStackFrame::OP_InitClassMemberComputedName(const unaligned T * playout)
  4130. {
  4131. JavascriptOperators::OP_InitClassMemberComputedName(
  4132. GetReg(playout->Instance),
  4133. GetReg(playout->Element),
  4134. GetReg(playout->Value),
  4135. m_functionBody->GetScriptContext());
  4136. }
  4137. template <class T>
  4138. void InterpreterStackFrame::DoInitLetFld(const unaligned T * playout, Var instance, PropertyOperationFlags flags)
  4139. {
  4140. uint inlineCacheIndex = playout->inlineCacheIndex;
  4141. InlineCache * inlineCache = this->GetInlineCache(inlineCacheIndex);
  4142. Assert(!TaggedNumber::Is(instance));
  4143. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  4144. if (!TrySetPropertyLocalFastPath(playout, propertyId, RecyclableObject::UnsafeFromVar(instance), inlineCache, flags))
  4145. {
  4146. JavascriptOperators::OP_InitLetProperty(instance, propertyId, GetReg(playout->Value));
  4147. }
  4148. }
  4149. template <class T>
  4150. void InterpreterStackFrame::DoInitConstFld(const unaligned T * playout, Var instance, PropertyOperationFlags flags)
  4151. {
  4152. uint inlineCacheIndex = playout->inlineCacheIndex;
  4153. InlineCache * inlineCache = this->GetInlineCache(inlineCacheIndex);
  4154. Assert(!TaggedNumber::Is(instance));
  4155. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  4156. if (!TrySetPropertyLocalFastPath(playout, propertyId, RecyclableObject::UnsafeFromVar(instance), inlineCache, flags))
  4157. {
  4158. JavascriptOperators::OP_InitConstProperty(instance, propertyId, GetReg(playout->Value));
  4159. }
  4160. }
  4161. template <class T>
  4162. void InterpreterStackFrame::OP_InitProperty(unaligned T* playout)
  4163. {
  4164. DoInitProperty(playout, GetReg(playout->Instance));
  4165. }
  4166. template <class T>
  4167. void InterpreterStackFrame::OP_InitLocalProperty(unaligned T* playout)
  4168. {
  4169. DoInitProperty(playout, this->localClosure);
  4170. }
  4171. template <class T>
  4172. void InterpreterStackFrame::OP_InitInnerFld(const unaligned T* playout)
  4173. {
  4174. DoInitProperty(playout, InnerScopeFromIndex(playout->scopeIndex));
  4175. }
  4176. template <class T>
  4177. void InterpreterStackFrame::OP_InitLetFld(const unaligned T * playout)
  4178. {
  4179. DoInitLetFld(playout, GetReg(playout->Instance));
  4180. }
  4181. template <class T>
  4182. void InterpreterStackFrame::OP_InitInnerLetFld(const unaligned T * playout)
  4183. {
  4184. DoInitLetFld(playout, InnerScopeFromIndex(playout->scopeIndex));
  4185. }
  4186. template <class T>
  4187. void InterpreterStackFrame::OP_InitLocalLetFld(const unaligned T * playout)
  4188. {
  4189. DoInitLetFld(playout, this->localClosure);
  4190. }
  4191. template <class T>
  4192. void InterpreterStackFrame::OP_InitConstFld(const unaligned T * playout)
  4193. {
  4194. DoInitConstFld(playout, GetReg(playout->Instance));
  4195. }
  4196. template <class T>
  4197. void InterpreterStackFrame::OP_InitRootProperty(unaligned T* playout)
  4198. {
  4199. Assert(playout->inlineCacheIndex >= this->m_functionBody->GetRootObjectLoadInlineCacheStart());
  4200. DoInitProperty(playout, this->GetRootObject());
  4201. }
  4202. template <class T>
  4203. void InterpreterStackFrame::OP_InitRootLetFld(const unaligned T * playout)
  4204. {
  4205. Assert(playout->inlineCacheIndex >= this->m_functionBody->GetRootObjectLoadInlineCacheStart());
  4206. DoInitLetFld(playout, this->GetRootObject(), PropertyOperation_Root);
  4207. }
  4208. template <class T>
  4209. void InterpreterStackFrame::OP_InitRootConstFld(const unaligned T * playout)
  4210. {
  4211. Assert(playout->inlineCacheIndex >= this->m_functionBody->GetRootObjectLoadInlineCacheStart());
  4212. DoInitConstFld(playout, this->GetRootObject(), PropertyOperation_Root);
  4213. }
  4214. template <class T>
  4215. void InterpreterStackFrame::OP_InitUndeclLetProperty(unaligned T* playout)
  4216. {
  4217. Var instance = InnerScopeFromIndex(playout->scopeIndex);
  4218. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  4219. JavascriptOperators::OP_InitLetProperty(instance, propertyId, this->scriptContext->GetLibrary()->GetUndeclBlockVar());
  4220. }
  4221. template <class T>
  4222. void InterpreterStackFrame::OP_InitUndeclLocalLetProperty(unaligned T* playout)
  4223. {
  4224. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  4225. JavascriptOperators::OP_InitLetProperty(this->localClosure, propertyId, this->scriptContext->GetLibrary()->GetUndeclBlockVar());
  4226. }
  4227. void InterpreterStackFrame::OP_InitUndeclRootLetProperty(uint propertyIdIndex)
  4228. {
  4229. Var instance = this->GetRootObject();
  4230. PropertyId propertyId = this->m_functionBody->GetReferencedPropertyId(propertyIdIndex);
  4231. JavascriptOperators::OP_InitUndeclRootLetProperty(instance, propertyId);
  4232. }
  4233. template <class T>
  4234. void InterpreterStackFrame::OP_InitUndeclConstProperty(unaligned T* playout)
  4235. {
  4236. Var instance = InnerScopeFromIndex(playout->scopeIndex);
  4237. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  4238. JavascriptOperators::OP_InitConstProperty(instance, propertyId, this->scriptContext->GetLibrary()->GetUndeclBlockVar());
  4239. }
  4240. template <class T>
  4241. void InterpreterStackFrame::OP_InitUndeclLocalConstProperty(unaligned T* playout)
  4242. {
  4243. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  4244. JavascriptOperators::OP_InitConstProperty(this->localClosure, propertyId, this->scriptContext->GetLibrary()->GetUndeclBlockVar());
  4245. }
  4246. void InterpreterStackFrame::OP_InitUndeclRootConstProperty(uint propertyIdIndex)
  4247. {
  4248. Var instance = this->GetRootObject();
  4249. PropertyId propertyId = this->m_functionBody->GetReferencedPropertyId(propertyIdIndex);
  4250. JavascriptOperators::OP_InitUndeclRootConstProperty(instance, propertyId);
  4251. }
  4252. template <class T>
  4253. void InterpreterStackFrame::OP_InitUndeclConsoleLetProperty(unaligned T* playout)
  4254. {
  4255. FrameDisplay* pScope = (FrameDisplay*)this->LdEnv();
  4256. AssertMsg(ConsoleScopeActivationObject::Is((DynamicObject*)pScope->GetItem(pScope->GetLength() - 1)), "How come we got this opcode without ConsoleScopeActivationObject?");
  4257. PropertyId propertyId = m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex);
  4258. JavascriptOperators::OP_InitLetProperty(pScope->GetItem(0), propertyId, this->scriptContext->GetLibrary()->GetUndeclBlockVar());
  4259. }
  4260. template <class T>
  4261. void InterpreterStackFrame::OP_InitUndeclConsoleConstProperty(unaligned T* playout)
  4262. {
  4263. FrameDisplay* pScope = (FrameDisplay*)this->LdEnv();
  4264. AssertMsg(ConsoleScopeActivationObject::Is((DynamicObject*)pScope->GetItem(pScope->GetLength() - 1)), "How come we got this opcode without ConsoleScopeActivationObject?");
  4265. PropertyId propertyId = m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex);
  4266. JavascriptOperators::OP_InitConstProperty(pScope->GetItem(0), propertyId, this->scriptContext->GetLibrary()->GetUndeclBlockVar());
  4267. }
  4268. #if ENABLE_PROFILE_INFO
  4269. template <class T>
  4270. void InterpreterStackFrame::ProfiledInitProperty(unaligned T* playout, Var instance)
  4271. {
  4272. ProfilingHelpers::ProfiledInitFld(
  4273. RecyclableObject::FromVar(instance),
  4274. GetPropertyIdFromCacheId(playout->inlineCacheIndex),
  4275. GetInlineCache(playout->inlineCacheIndex),
  4276. playout->inlineCacheIndex,
  4277. GetReg(playout->Value),
  4278. GetFunctionBody());
  4279. }
  4280. template <class T>
  4281. void InterpreterStackFrame::OP_ProfiledInitProperty(unaligned T* playout)
  4282. {
  4283. ProfiledInitProperty(playout, GetReg(playout->Instance));
  4284. }
  4285. template <class T>
  4286. void InterpreterStackFrame::OP_ProfiledInitLocalProperty(unaligned T* playout)
  4287. {
  4288. ProfiledInitProperty(playout, this->localClosure);
  4289. }
  4290. template <class T>
  4291. void InterpreterStackFrame::OP_ProfiledInitRootProperty(unaligned T* playout)
  4292. {
  4293. ProfiledInitProperty(playout, this->GetRootObject());
  4294. }
  4295. template <class T>
  4296. void InterpreterStackFrame::OP_ProfiledGetElementI(const unaligned OpLayoutDynamicProfile<T>* playout)
  4297. {
  4298. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  4299. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  4300. threadContext->ClearImplicitCallFlags();
  4301. SetReg(
  4302. playout->Value,
  4303. ProfilingHelpers::ProfiledLdElem(
  4304. GetReg(playout->Instance),
  4305. GetReg(playout->Element),
  4306. m_functionBody,
  4307. playout->profileId,
  4308. this->TestFlags(InterpreterStackFrameFlags_ProcessingBailOutOnArrayAccessHelperCall),
  4309. this->TestFlags(InterpreterStackFrameFlags_ProcessingBailOutOnArraySpecialization)));
  4310. this->ClearFlags(InterpreterStackFrameFlags_ProcessingBailOutOnArrayAccessHelperCall | InterpreterStackFrameFlags_ProcessingBailOutOnArraySpecialization);
  4311. threadContext->CheckAndResetImplicitCallAccessorFlag();
  4312. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  4313. }
  4314. #endif
  4315. template <typename T>
  4316. void InterpreterStackFrame::OP_GetElementI(const unaligned T* playout)
  4317. {
  4318. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  4319. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  4320. threadContext->ClearImplicitCallFlags();
  4321. // Same fast path as in the backend.
  4322. Var instance = GetReg(playout->Instance);
  4323. // Only enable fast path if the javascript array is not cross site
  4324. Var element;
  4325. #if ENABLE_PROFILE_INFO
  4326. if (!TaggedNumber::Is(instance) && VirtualTableInfo<JavascriptArray>::HasVirtualTable(instance))
  4327. {
  4328. element =
  4329. ProfilingHelpers::ProfiledLdElem_FastPath(
  4330. JavascriptArray::UnsafeFromVar(instance),
  4331. GetReg(playout->Element),
  4332. GetScriptContext());
  4333. }
  4334. else
  4335. #endif
  4336. {
  4337. element = JavascriptOperators::OP_GetElementI(instance, GetReg(playout->Element), GetScriptContext());
  4338. }
  4339. this->ClearFlags(InterpreterStackFrameFlags_ProcessingBailOutOnArrayAccessHelperCall);
  4340. threadContext->CheckAndResetImplicitCallAccessorFlag();
  4341. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  4342. SetReg(playout->Value, element);
  4343. }
  4344. template <typename T>
  4345. void InterpreterStackFrame::OP_SetElementI(const unaligned T* playout, PropertyOperationFlags flags)
  4346. {
  4347. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  4348. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  4349. threadContext->ClearImplicitCallFlags();
  4350. // Same fast path as in the backend.
  4351. Var instance = GetReg(playout->Instance);
  4352. const Var varIndex = GetReg(playout->Element);
  4353. const Var value = GetReg(playout->Value);
  4354. #if ENABLE_PROFILE_INFO
  4355. // Only enable fast path if the javascript array is not cross site
  4356. if (!TaggedNumber::Is(instance) &&
  4357. VirtualTableInfo<JavascriptArray>::HasVirtualTable(instance) &&
  4358. !JavascriptOperators::SetElementMayHaveImplicitCalls(GetScriptContext()))
  4359. {
  4360. ProfilingHelpers::ProfiledStElem_FastPath(
  4361. JavascriptArray::UnsafeFromVar(instance),
  4362. varIndex,
  4363. value,
  4364. GetScriptContext(),
  4365. flags);
  4366. }
  4367. else
  4368. #endif
  4369. {
  4370. JavascriptOperators::OP_SetElementI(instance, varIndex, value, GetScriptContext(), flags);
  4371. }
  4372. this->ClearFlags(InterpreterStackFrameFlags_ProcessingBailOutOnArrayAccessHelperCall);
  4373. threadContext->CheckAndResetImplicitCallAccessorFlag();
  4374. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  4375. }
  4376. #if ENABLE_PROFILE_INFO
  4377. template <typename T>
  4378. void InterpreterStackFrame::OP_ProfiledSetElementI(
  4379. const unaligned OpLayoutDynamicProfile<T>* playout,
  4380. PropertyOperationFlags flags)
  4381. {
  4382. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  4383. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  4384. threadContext->ClearImplicitCallFlags();
  4385. ProfilingHelpers::ProfiledStElem(
  4386. GetReg(playout->Instance),
  4387. GetReg(playout->Element),
  4388. GetReg(playout->Value),
  4389. m_functionBody,
  4390. playout->profileId,
  4391. flags,
  4392. this->TestFlags(InterpreterStackFrameFlags_ProcessingBailOutOnArrayAccessHelperCall),
  4393. this->TestFlags(InterpreterStackFrameFlags_ProcessingBailOutOnArraySpecialization));
  4394. this->ClearFlags(InterpreterStackFrameFlags_ProcessingBailOutOnArrayAccessHelperCall | InterpreterStackFrameFlags_ProcessingBailOutOnArraySpecialization);
  4395. threadContext->CheckAndResetImplicitCallAccessorFlag();
  4396. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  4397. }
  4398. #endif
  4399. template <typename T>
  4400. void InterpreterStackFrame::OP_SetElementIStrict(const unaligned T* playout)
  4401. {
  4402. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  4403. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  4404. threadContext->ClearImplicitCallFlags();
  4405. OP_SetElementI(playout, PropertyOperation_StrictMode);
  4406. threadContext->CheckAndResetImplicitCallAccessorFlag();
  4407. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  4408. }
  4409. #if ENABLE_PROFILE_INFO
  4410. template <typename T>
  4411. void InterpreterStackFrame::OP_ProfiledSetElementIStrict(const unaligned OpLayoutDynamicProfile<T>* playout)
  4412. {
  4413. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  4414. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  4415. threadContext->ClearImplicitCallFlags();
  4416. OP_ProfiledSetElementI(playout, PropertyOperation_StrictMode);
  4417. threadContext->CheckAndResetImplicitCallAccessorFlag();
  4418. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  4419. }
  4420. #endif
  4421. template <class T>
  4422. void InterpreterStackFrame::OP_LdArrayHeadSegment(const unaligned T* playout)
  4423. {
  4424. JavascriptArray* array = JavascriptArray::FromAnyArray(GetReg(playout->R1));
  4425. // The array is create by the built-in on the same script context
  4426. Assert(array->GetScriptContext() == GetScriptContext());
  4427. SetNonVarReg(playout->R0, array->GetHead());
  4428. }
  4429. template <class T>
  4430. void InterpreterStackFrame::OP_SetArraySegmentItem_CI4(const unaligned T* playout)
  4431. {
  4432. SparseArraySegment<Var> * segment = (SparseArraySegment<Var> *)GetNonVarReg(playout->Instance);
  4433. uint32 index = playout->Element;
  4434. Var value = GetReg(playout->Value);
  4435. Assert(segment->left == 0);
  4436. Assert(index < segment->length);
  4437. segment->elements[index] = value;
  4438. }
  4439. template <class T>
  4440. void InterpreterStackFrame::OP_NewScArray(const unaligned T * playout)
  4441. {
  4442. JavascriptArray *arr;
  4443. arr = scriptContext->GetLibrary()->CreateArrayLiteral(playout->C1);
  4444. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  4445. arr->CheckForceES5Array();
  4446. #endif
  4447. SetReg(playout->R0, arr);
  4448. }
  4449. #if ENABLE_PROFILE_INFO
  4450. template <bool Profiled, class T>
  4451. void InterpreterStackFrame::ProfiledNewScArray(const unaligned OpLayoutDynamicProfile<T> * playout)
  4452. {
  4453. if(!Profiled && !isAutoProfiling)
  4454. {
  4455. OP_NewScArray(playout);
  4456. return;
  4457. }
  4458. SetReg(
  4459. playout->R0,
  4460. ProfilingHelpers::ProfiledNewScArray(
  4461. playout->C1,
  4462. m_functionBody,
  4463. playout->profileId));
  4464. }
  4465. #else
  4466. template <bool Profiled, class T>
  4467. void InterpreterStackFrame::ProfiledNewScArray(const unaligned OpLayoutDynamicProfile<T> * playout)
  4468. {
  4469. Assert(!Profiled);
  4470. OP_NewScArray(playout);
  4471. }
  4472. #endif
  4473. void InterpreterStackFrame::OP_NewScIntArray(const unaligned OpLayoutAuxiliary * playout)
  4474. {
  4475. #if ENABLE_PROFILE_INFO
  4476. if(isAutoProfiling)
  4477. {
  4478. OP_ProfiledNewScIntArray(static_cast<const unaligned OpLayoutDynamicProfile<OpLayoutAuxiliary> *>(playout));
  4479. return;
  4480. }
  4481. #endif
  4482. const Js::AuxArray<int32> *ints = Js::ByteCodeReader::ReadAuxArray<int32>(playout->Offset, this->GetFunctionBody());
  4483. JavascriptNativeIntArray *arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(ints->count);
  4484. SparseArraySegment<int32> * segment = (SparseArraySegment<int32>*)arr->GetHead();
  4485. JavascriptOperators::AddIntsToArraySegment(segment, ints);
  4486. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  4487. arr->CheckForceES5Array();
  4488. #endif
  4489. SetReg(playout->R0, arr);
  4490. }
  4491. #if ENABLE_PROFILE_INFO
  4492. void InterpreterStackFrame::OP_ProfiledNewScIntArray(const unaligned OpLayoutDynamicProfile<OpLayoutAuxiliary> * playout)
  4493. {
  4494. const Js::AuxArray<int32> *ints = Js::ByteCodeReader::ReadAuxArray<int32>(playout->Offset, this->GetFunctionBody());
  4495. Js::ProfileId profileId = playout->profileId;
  4496. FunctionBody *functionBody = this->m_functionBody;
  4497. ArrayCallSiteInfo *arrayInfo = functionBody->GetDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, profileId);
  4498. Assert(arrayInfo);
  4499. JavascriptArray *arr;
  4500. if (arrayInfo && arrayInfo->IsNativeIntArray())
  4501. {
  4502. #if ENABLE_COPYONACCESS_ARRAY
  4503. JavascriptLibrary *lib = scriptContext->GetLibrary();
  4504. if (JavascriptLibrary::IsCopyOnAccessArrayCallSite(lib, arrayInfo, ints->count))
  4505. {
  4506. Assert(lib->cacheForCopyOnAccessArraySegments);
  4507. arr = scriptContext->GetLibrary()->CreateCopyOnAccessNativeIntArrayLiteral(arrayInfo, functionBody, ints);
  4508. }
  4509. else
  4510. #endif
  4511. {
  4512. arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(ints->count);
  4513. SparseArraySegment<int32> *segment = (SparseArraySegment<int32>*)arr->GetHead();
  4514. JavascriptOperators::AddIntsToArraySegment(segment, ints);
  4515. }
  4516. JavascriptNativeIntArray *intArray = reinterpret_cast<JavascriptNativeIntArray*>(arr);
  4517. Recycler *recycler = scriptContext->GetRecycler();
  4518. intArray->SetArrayCallSite(profileId, recycler->CreateWeakReferenceHandle(functionBody));
  4519. }
  4520. else if (arrayInfo && arrayInfo->IsNativeFloatArray())
  4521. {
  4522. arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(ints->count);
  4523. SparseArraySegment<double> * segment = (SparseArraySegment<double>*)arr->GetHead();
  4524. for (uint i = 0; i < ints->count; i++)
  4525. {
  4526. segment->elements[i] = (double)ints->elements[i];
  4527. }
  4528. JavascriptNativeFloatArray *floatArray = reinterpret_cast<JavascriptNativeFloatArray*>(arr);
  4529. Recycler *recycler = scriptContext->GetRecycler();
  4530. floatArray->SetArrayCallSite(profileId, recycler->CreateWeakReferenceHandle(functionBody));
  4531. }
  4532. else
  4533. {
  4534. arr = scriptContext->GetLibrary()->CreateArrayLiteral(ints->count);
  4535. SparseArraySegment<Var> * segment = (SparseArraySegment<Var>*)arr->GetHead();
  4536. for (uint i = 0; i < ints->count; i++)
  4537. {
  4538. segment->elements[i] = JavascriptNumber::ToVar(ints->elements[i], scriptContext);
  4539. }
  4540. }
  4541. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  4542. arr->CheckForceES5Array();
  4543. #endif
  4544. SetReg(playout->R0, arr);
  4545. }
  4546. #endif
  4547. void InterpreterStackFrame::OP_NewScFltArray(const unaligned OpLayoutAuxiliary * playout )
  4548. {
  4549. #if ENABLE_PROFILE_INFO
  4550. if(isAutoProfiling)
  4551. {
  4552. OP_ProfiledNewScFltArray(static_cast<const unaligned OpLayoutDynamicProfile<OpLayoutAuxiliary> *>(playout));
  4553. return;
  4554. }
  4555. #endif
  4556. const Js::AuxArray<double> *doubles = Js::ByteCodeReader::ReadAuxArray<double>(playout->Offset, this->GetFunctionBody());
  4557. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(doubles->count);
  4558. SparseArraySegment<double> * segment = (SparseArraySegment<double>*)arr->GetHead();
  4559. JavascriptOperators::AddFloatsToArraySegment(segment, doubles);
  4560. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  4561. arr->CheckForceES5Array();
  4562. #endif
  4563. SetReg(playout->R0, arr);
  4564. }
  4565. #if ENABLE_PROFILE_INFO
  4566. void InterpreterStackFrame::OP_ProfiledNewScFltArray(const unaligned OpLayoutDynamicProfile<OpLayoutAuxiliary> * playout)
  4567. {
  4568. const Js::AuxArray<double> *doubles = Js::ByteCodeReader::ReadAuxArray<double>(playout->Offset, this->GetFunctionBody());
  4569. Js::ProfileId profileId = playout->profileId;
  4570. FunctionBody *functionBody = this->m_functionBody;
  4571. ArrayCallSiteInfo *arrayInfo = functionBody->GetDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, profileId);
  4572. Assert(arrayInfo);
  4573. JavascriptArray *arr;
  4574. if (arrayInfo && arrayInfo->IsNativeFloatArray())
  4575. {
  4576. arrayInfo->SetIsNotNativeIntArray();
  4577. arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(doubles->count);
  4578. SparseArraySegment<double> * segment = (SparseArraySegment<double>*)arr->GetHead();
  4579. JavascriptOperators::AddFloatsToArraySegment(segment, doubles);
  4580. JavascriptNativeFloatArray *floatArray = reinterpret_cast<JavascriptNativeFloatArray*>(arr);
  4581. Recycler *recycler = scriptContext->GetRecycler();
  4582. floatArray->SetArrayCallSite(profileId, recycler->CreateWeakReferenceHandle(functionBody));
  4583. }
  4584. else
  4585. {
  4586. arr = scriptContext->GetLibrary()->CreateArrayLiteral(doubles->count);
  4587. SparseArraySegment<Var> * segment = (SparseArraySegment<Var>*)arr->GetHead();
  4588. for (uint i = 0; i < doubles->count; i++)
  4589. {
  4590. segment->elements[i] = JavascriptNumber::ToVarNoCheck(doubles->elements[i], scriptContext);
  4591. }
  4592. }
  4593. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  4594. arr->CheckForceES5Array();
  4595. #endif
  4596. SetReg(playout->R0, arr);
  4597. }
  4598. #endif
  4599. void InterpreterStackFrame::OP_SetArraySegmentVars(const unaligned OpLayoutAuxiliary * playout)
  4600. {
  4601. const Js::VarArray *vars = Js::ByteCodeReader::ReadAuxArray<Var>(playout->Offset, this->GetFunctionBody());
  4602. SparseArraySegment<Var> * segment =(SparseArraySegment<Var> *)GetNonVarReg(playout->R0);
  4603. JavascriptOperators::AddVarsToArraySegment(segment, vars);
  4604. }
  4605. template <class T>
  4606. void InterpreterStackFrame::OP_SetArrayItemC_CI4(const unaligned T* playout)
  4607. {
  4608. JavascriptArray* array = JavascriptArray::FromAnyArray(GetReg(playout->Instance));
  4609. uint32 index = playout->Element;
  4610. Var value = GetReg(playout->Value);
  4611. #if ENABLE_COPYONACCESS_ARRAY
  4612. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(value);
  4613. #endif
  4614. // The array is create by the built-in on the same script context
  4615. Assert(array->GetScriptContext() == GetScriptContext());
  4616. TypeId typeId = array->GetTypeId();
  4617. if (typeId == TypeIds_NativeIntArray)
  4618. {
  4619. JavascriptArray::OP_SetNativeIntElementC(reinterpret_cast<JavascriptNativeIntArray*>(array), index, value, array->GetScriptContext());
  4620. }
  4621. else if (typeId == TypeIds_NativeFloatArray)
  4622. {
  4623. JavascriptArray::OP_SetNativeFloatElementC(reinterpret_cast<JavascriptNativeFloatArray*>(array), index, value, array->GetScriptContext());
  4624. }
  4625. else
  4626. {
  4627. array->SetArrayLiteralItem(index, value);
  4628. }
  4629. }
  4630. template <class T>
  4631. void InterpreterStackFrame::OP_SetArrayItemI_CI4(const unaligned T* playout)
  4632. {
  4633. // Note that this code assumes that we only get here when we see an array literal,
  4634. // so we know that the instance is truly an array, and the index is a uint32.
  4635. // If/when we use this for cases like "a[0] = x", we'll at least have to check
  4636. // whether "a" is really an array.
  4637. JavascriptArray* array = JavascriptArray::FromAnyArray(GetReg(playout->Instance));
  4638. // The array is create by the built-in on the same script context
  4639. Assert(array->GetScriptContext() == GetScriptContext());
  4640. uint32 index = playout->Element;
  4641. Var value = GetReg(playout->Value);
  4642. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(array));
  4643. SparseArraySegment<Var>* lastUsedSeg = (SparseArraySegment<Var>*)array->GetLastUsedSegment();
  4644. if (index >= lastUsedSeg->left)
  4645. {
  4646. uint32 index2 = index - lastUsedSeg->left;
  4647. if (index2 < lastUsedSeg->size)
  4648. {
  4649. // Successful fastpath
  4650. array->DirectSetItemInLastUsedSegmentAt(index2, value);
  4651. return;
  4652. }
  4653. }
  4654. ScriptContext* scriptContext = array->GetScriptContext();
  4655. JavascriptOperators::SetItem(array, array, index, value, scriptContext);
  4656. }
  4657. #if ENABLE_PROFILE_INFO
  4658. Var InterpreterStackFrame::OP_ProfiledLdThis(Var thisVar, int moduleID, ScriptContext *scriptContext)
  4659. {
  4660. FunctionBody * functionBody = this->m_functionBody;
  4661. DynamicProfileInfo * dynamicProfileInfo = functionBody->GetDynamicProfileInfo();
  4662. TypeId typeId = JavascriptOperators::GetTypeId(thisVar);
  4663. if (JavascriptOperators::IsThisSelf(typeId))
  4664. {
  4665. Assert(typeId != TypeIds_GlobalObject || ((Js::GlobalObject*)thisVar)->ToThis() == thisVar);
  4666. Assert(typeId != TypeIds_ModuleRoot || JavascriptOperators::GetThisFromModuleRoot(thisVar) == thisVar);
  4667. // Record the fact that we saw a trivial LdThis.
  4668. dynamicProfileInfo->RecordThisInfo(thisVar, ThisType_Simple);
  4669. return thisVar;
  4670. }
  4671. thisVar = JavascriptOperators::OP_GetThis(thisVar, moduleID, scriptContext);
  4672. // Record the fact that we saw a LdThis that had to map its source to something else, or at least
  4673. // forced us to call a helper, e.g., a FastDOM object with an unrecognized type ID.
  4674. dynamicProfileInfo->RecordThisInfo(thisVar, ThisType_Mapped);
  4675. return thisVar;
  4676. }
  4677. Var InterpreterStackFrame::OP_ProfiledStrictLdThis(Var thisVar, ScriptContext* scriptContext)
  4678. {
  4679. FunctionBody * functionBody = this->m_functionBody;
  4680. DynamicProfileInfo * dynamicProfileInfo = functionBody->GetDynamicProfileInfo();
  4681. TypeId typeId = JavascriptOperators::GetTypeId(thisVar);
  4682. if (typeId == TypeIds_ActivationObject)
  4683. {
  4684. thisVar = scriptContext->GetLibrary()->GetUndefined();
  4685. dynamicProfileInfo->RecordThisInfo(thisVar, ThisType_Mapped);
  4686. return thisVar;
  4687. }
  4688. dynamicProfileInfo->RecordThisInfo(thisVar, ThisType_Simple);
  4689. return thisVar;
  4690. }
  4691. #endif
  4692. void InterpreterStackFrame::OP_InitCachedFuncs(const unaligned OpLayoutAuxNoReg * playout)
  4693. {
  4694. const FuncInfoArray *info = Js::ByteCodeReader::ReadAuxArray<FuncInfoEntry>(playout->Offset, this->GetFunctionBody());
  4695. JavascriptOperators::OP_InitCachedFuncs(this->localClosure, GetLocalFrameDisplay(), info, GetScriptContext());
  4696. }
  4697. Var InterpreterStackFrame::OP_GetCachedFunc(Var instance, int32 index)
  4698. {
  4699. ActivationObjectEx *obj = ActivationObjectEx::FromVar(instance);
  4700. FuncCacheEntry *entry = obj->GetFuncCacheEntry((uint)index);
  4701. return entry->func;
  4702. }
  4703. void InterpreterStackFrame::OP_CommitScope()
  4704. {
  4705. const Js::PropertyIdArray *propIds = this->m_functionBody->GetFormalsPropIdArray();
  4706. this->OP_CommitScopeHelper(propIds);
  4707. }
  4708. void InterpreterStackFrame::OP_CommitScopeHelper(const PropertyIdArray *propIds)
  4709. {
  4710. ActivationObjectEx *obj = ActivationObjectEx::FromVar(this->localClosure);
  4711. ScriptFunction *func = obj->GetParentFunc();
  4712. Assert(obj->GetParentFunc() == func);
  4713. if (func->GetCachedScope() == obj)
  4714. {
  4715. PropertyId firstVarSlot = ActivationObjectEx::GetFirstVarSlot(propIds);
  4716. Var undef = scriptContext->GetLibrary()->GetUndefined();
  4717. for (uint i = firstVarSlot; i < propIds->count; i++)
  4718. {
  4719. obj->SetSlot(SetSlotArguments(propIds->elements[i], i, undef));
  4720. }
  4721. obj->SetCommit(true);
  4722. }
  4723. }
  4724. Var InterpreterStackFrame::OP_NewScObjectSimple()
  4725. {
  4726. Var object = scriptContext->GetLibrary()->CreateObject(true);
  4727. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(object));
  4728. #if ENABLE_DEBUG_CONFIG_OPTIONS
  4729. if (Js::Configuration::Global.flags.IsEnabled(Js::autoProxyFlag))
  4730. {
  4731. object = JavascriptProxy::AutoProxyWrapper(object);
  4732. }
  4733. #endif
  4734. return object;
  4735. }
  4736. void InterpreterStackFrame::OP_NewScObjectLiteral(const unaligned OpLayoutAuxiliary * playout )
  4737. {
  4738. const Js::PropertyIdArray *propIds = Js::ByteCodeReader::ReadPropertyIdArray(playout->Offset, this->GetFunctionBody());
  4739. Var newObj = JavascriptOperators::NewScObjectLiteral(GetScriptContext(), propIds,
  4740. this->GetFunctionBody()->GetObjectLiteralTypeRef(playout->C1));
  4741. SetReg(playout->R0, newObj);
  4742. }
  4743. void InterpreterStackFrame::OP_NewScObjectLiteral_LS(const unaligned OpLayoutAuxiliary * playout, RegSlot& target)
  4744. {
  4745. const Js::PropertyIdArray *propIds = Js::ByteCodeReader::ReadPropertyIdArray(playout->Offset, this->GetFunctionBody());
  4746. target = playout->R0;
  4747. Var newObj = JavascriptOperators::NewScObjectLiteral(GetScriptContext(), propIds,
  4748. this->GetFunctionBody()->GetObjectLiteralTypeRef(playout->C1));
  4749. SetReg(playout->R0, newObj);
  4750. target = Js::Constants::NoRegister;
  4751. }
  4752. void InterpreterStackFrame::OP_LdPropIds(const unaligned OpLayoutAuxiliary * playout)
  4753. {
  4754. const Js::PropertyIdArray *propIds = Js::ByteCodeReader::ReadPropertyIdArray(playout->Offset, this->GetFunctionBody());
  4755. SetNonVarReg(playout->R0, (Var)propIds);
  4756. }
  4757. bool InterpreterStackFrame::IsCurrentLoopNativeAddr(void * codeAddr) const
  4758. {
  4759. if (this->GetCurrentLoopNum() == LoopHeader::NoLoop)
  4760. {
  4761. return false;
  4762. }
  4763. // TODO: Do more verification?
  4764. return true;
  4765. }
  4766. template <LayoutSize layoutSize, bool profiled>
  4767. const byte * InterpreterStackFrame::OP_ProfiledLoopBodyStart(const byte * ip)
  4768. {
  4769. uint32 loopId = m_reader.GetLayout<OpLayoutT_Unsigned1<LayoutSizePolicy<layoutSize>>>(ip)->C1;
  4770. return OP_ProfiledLoopBodyStart<layoutSize, profiled>(loopId);
  4771. }
  4772. #ifdef ASMJS_PLAT
  4773. template <LayoutSize layoutSize, bool profiled>
  4774. const byte * InterpreterStackFrame::OP_ProfiledWasmLoopBodyStart(const byte * ip)
  4775. {
  4776. uint32 loopId = m_reader.GetLayout<OpLayoutT_WasmLoopStart<LayoutSizePolicy<layoutSize>>>(ip)->loopId;
  4777. return OP_ProfiledLoopBodyStart<layoutSize, profiled>(loopId);
  4778. }
  4779. #endif
  4780. #if ENABLE_PROFILE_INFO
  4781. void InterpreterStackFrame::OP_RecordImplicitCall(uint loopNumber)
  4782. {
  4783. Assert(Js::DynamicProfileInfo::EnableImplicitCallFlags(GetFunctionBody()));
  4784. Assert(loopNumber < this->m_functionBody->GetLoopCount());
  4785. FunctionBody* functionBody = this->m_functionBody;
  4786. DynamicProfileInfo * dynamicProfileInfo = functionBody->GetDynamicProfileInfo();
  4787. ThreadContext * threadContext = scriptContext->GetThreadContext();
  4788. dynamicProfileInfo->RecordLoopImplicitCallFlags(functionBody, loopNumber, threadContext->GetImplicitCallFlags());
  4789. }
  4790. template <LayoutSize layoutSize, bool profiled>
  4791. const byte * InterpreterStackFrame::OP_ProfiledLoopStart(const byte * ip)
  4792. {
  4793. const uint32 C1 = m_reader.GetLayout<OpLayoutT_Unsigned1<LayoutSizePolicy<layoutSize>>>(ip)->C1;
  4794. if(!profiled && !isAutoProfiling)
  4795. {
  4796. return ip;
  4797. }
  4798. ThreadContext *const threadContext = GetScriptContext()->GetThreadContext();
  4799. threadContext->IncrementLoopDepth();
  4800. // Save the implicit call flags. The interpreter may switch to profiling mode during LoopBodyStart, so always do this.
  4801. Assert(Js::DynamicProfileInfo::EnableImplicitCallFlags(GetFunctionBody()));
  4802. this->savedLoopImplicitCallFlags[C1] = threadContext->GetImplicitCallFlags();
  4803. threadContext->SetImplicitCallFlags(ImplicitCall_None);
  4804. this->currentLoopCounter = 0;
  4805. if(!profiled)
  4806. {
  4807. return ip;
  4808. }
  4809. LayoutSize localLayoutSize;
  4810. OpCode peekOp = m_reader.PeekOp(ip, localLayoutSize);
  4811. Assert(peekOp != OpCode::LoopBodyStart);
  4812. if (peekOp == OpCode::ProfiledLoopBodyStart)
  4813. {
  4814. Assert(localLayoutSize == layoutSize);
  4815. ip += Js::OpCodeUtil::EncodedSize(peekOp, layoutSize);
  4816. // We are doing JIT loop body. Process the first ProfiledLoopBodyStart to avoid recording
  4817. // the implicit call before the first iteration
  4818. uint32 C2 = m_reader.GetLayout<OpLayoutT_Unsigned1<LayoutSizePolicy<layoutSize>>>(ip)->C1;
  4819. Assert(C1 == C2);
  4820. (this->*opProfiledLoopBodyStart)(C1, layoutSize, true /* isFirstIteration */);
  4821. return m_reader.GetIP();
  4822. }
  4823. return ip;
  4824. }
  4825. template <LayoutSize layoutSize, bool profiled>
  4826. const byte * InterpreterStackFrame::OP_ProfiledLoopEnd(const byte * ip)
  4827. {
  4828. uint32 loopNumber = m_reader.GetLayout<OpLayoutT_Unsigned1<LayoutSizePolicy<layoutSize>>>(ip)->C1;
  4829. if(!profiled && !isAutoProfiling)
  4830. {
  4831. return ip;
  4832. }
  4833. this->CheckIfLoopIsHot(this->currentLoopCounter);
  4834. Js::FunctionBody *fn = this->function->GetFunctionBody();
  4835. if (fn->HasDynamicProfileInfo())
  4836. {
  4837. fn->GetAnyDynamicProfileInfo()->SetLoopInterpreted(loopNumber);
  4838. // If the counter is 0, there is a high chance that some config disabled tracking that information. (ie: -off:jitloopbody)
  4839. // Assume it is valid for memop in this case.
  4840. if (this->currentLoopCounter >= (uint)CONFIG_FLAG(MinMemOpCount) ||
  4841. (this->currentLoopCounter == 0 && !this->m_functionBody->DoJITLoopBody())
  4842. )
  4843. {
  4844. // This flag becomes relevant only if the loop has been interpreted
  4845. fn->GetAnyDynamicProfileInfo()->SetMemOpMinReached(loopNumber);
  4846. }
  4847. }
  4848. this->currentLoopCounter = 0;
  4849. if (profiled)
  4850. {
  4851. Assert(Js::DynamicProfileInfo::EnableImplicitCallFlags(GetFunctionBody()));
  4852. OP_RecordImplicitCall(loopNumber);
  4853. if(switchProfileModeOnLoopEndNumber == loopNumber)
  4854. {
  4855. // Stop profiling since the jitted loop body would be exiting the loop
  4856. Assert(!switchProfileMode);
  4857. switchProfileMode = true;
  4858. switchProfileModeOnLoopEndNumber = 0u - 1;
  4859. }
  4860. }
  4861. // Restore the implicit call flags state and add with flags in the loop as well
  4862. ThreadContext *const threadContext = GetScriptContext()->GetThreadContext();
  4863. threadContext->AddImplicitCallFlags(this->savedLoopImplicitCallFlags[loopNumber]);
  4864. threadContext->DecrementLoopDepth();
  4865. return ip;
  4866. }
  4867. template <LayoutSize layoutSize, bool profiled>
  4868. const byte * InterpreterStackFrame::OP_ProfiledLoopBodyStart(uint loopId)
  4869. {
  4870. if (profiled || isAutoProfiling)
  4871. {
  4872. this->currentLoopCounter++;
  4873. }
  4874. if (profiled)
  4875. {
  4876. OP_RecordImplicitCall(loopId);
  4877. }
  4878. (this->*(profiled ? opProfiledLoopBodyStart : opLoopBodyStart))(loopId, layoutSize, false /* isFirstIteration */);
  4879. return m_reader.GetIP();
  4880. }
  4881. template<bool InterruptProbe, bool JITLoopBody>
  4882. void InterpreterStackFrame::ProfiledLoopBodyStart(uint32 loopNumber, LayoutSize layoutSize, bool isFirstIteration)
  4883. {
  4884. Assert(Js::DynamicProfileInfo::EnableImplicitCallFlags(GetFunctionBody()));
  4885. if (InterruptProbe)
  4886. {
  4887. this->DoInterruptProbe();
  4888. }
  4889. #if ENABLE_TTD
  4890. if(SHOULD_DO_TTD_STACK_STMT_OP(this->scriptContext))
  4891. {
  4892. this->scriptContext->GetThreadContext()->TTDExecutionInfo->UpdateLoopCountInfo();
  4893. }
  4894. #endif
  4895. if (!JITLoopBody || this->IsInCatchOrFinallyBlock())
  4896. {
  4897. // For functions having try-catch-finally, jit loop bodies for loops that are contained only in a try block,
  4898. // not even indirect containment in a Catch or Finally.
  4899. return;
  4900. }
  4901. LoopHeader const * loopHeader = DoLoopBodyStart(loopNumber, layoutSize, false, isFirstIteration);
  4902. Assert(loopHeader == nullptr || this->m_functionBody->GetLoopNumber(loopHeader) == loopNumber);
  4903. if (loopHeader != nullptr)
  4904. {
  4905. // We executed jitted loop body, no implicit call information available for this loop
  4906. uint currentOffset = m_reader.GetCurrentOffset();
  4907. if (!loopHeader->Contains(currentOffset) || (m_reader.PeekOp() == OpCode::ProfiledLoopEnd))
  4908. {
  4909. // Restore the outer loop's implicit call flags
  4910. scriptContext->GetThreadContext()->SetImplicitCallFlags(this->savedLoopImplicitCallFlags[loopNumber]);
  4911. }
  4912. else
  4913. {
  4914. // We bailout from the loop, just continue collect implicit call flags for this loop
  4915. }
  4916. }
  4917. }
  4918. #else
  4919. template <LayoutSize layoutSize, bool profiled>
  4920. const byte * InterpreterStackFrame::OP_ProfiledLoopStart(const byte * ip)
  4921. {
  4922. Assert(!profiled);
  4923. return ip;
  4924. }
  4925. template <LayoutSize layoutSize, bool profiled>
  4926. const byte * InterpreterStackFrame::OP_ProfiledLoopEnd(const byte * ip)
  4927. {
  4928. Assert(!profiled);
  4929. return ip;
  4930. }
  4931. template <LayoutSize layoutSize, bool profiled>
  4932. const byte * InterpreterStackFrame::OP_ProfiledLoopBodyStart(uint loopId)
  4933. {
  4934. Assert(!profiled);
  4935. (this->*opLoopBodyStart)(loopId, layoutSize, false /* isFirstIteration */);
  4936. return m_reader.GetIP();
  4937. }
  4938. #endif
  4939. template<bool InterruptProbe, bool JITLoopBody>
  4940. void InterpreterStackFrame::LoopBodyStart(uint32 loopNumber, LayoutSize layoutSize, bool isFirstIteration)
  4941. {
  4942. if (InterruptProbe)
  4943. {
  4944. this->DoInterruptProbe();
  4945. }
  4946. #if ENABLE_TTD
  4947. if(SHOULD_DO_TTD_STACK_STMT_OP(this->scriptContext))
  4948. {
  4949. this->scriptContext->GetThreadContext()->TTDExecutionInfo->UpdateLoopCountInfo();
  4950. }
  4951. #endif
  4952. if (!JITLoopBody || this->IsInCatchOrFinallyBlock())
  4953. {
  4954. // For functions having try-catch-finally, jit loop bodies for loops that are contained only in a try block,
  4955. // not even indirect containment in a Catch or Finally.
  4956. return;
  4957. }
  4958. DoLoopBodyStart(loopNumber, layoutSize, true, isFirstIteration);
  4959. }
  4960. LoopHeader const * InterpreterStackFrame::DoLoopBodyStart(uint32 loopNumber, LayoutSize layoutSize, const bool doProfileLoopCheck, const bool isFirstIteration)
  4961. {
  4962. #if ENABLE_PROFILE_INFO
  4963. class AutoRestoreLoopNumbers
  4964. {
  4965. private:
  4966. InterpreterStackFrame *const interpreterStackFrame;
  4967. uint32 loopNumber;
  4968. bool doProfileLoopCheck;
  4969. public:
  4970. AutoRestoreLoopNumbers(InterpreterStackFrame *const interpreterStackFrame, uint32 loopNumber, bool doProfileLoopCheck)
  4971. : interpreterStackFrame(interpreterStackFrame), loopNumber(loopNumber), doProfileLoopCheck(doProfileLoopCheck)
  4972. {
  4973. Assert(interpreterStackFrame->currentLoopNum == LoopHeader::NoLoop);
  4974. interpreterStackFrame->currentLoopNum = loopNumber;
  4975. interpreterStackFrame->m_functionBody->SetRecentlyBailedOutOfJittedLoopBody(false);
  4976. }
  4977. ~AutoRestoreLoopNumbers()
  4978. {
  4979. interpreterStackFrame->currentLoopNum = LoopHeader::NoLoop;
  4980. interpreterStackFrame->currentLoopCounter = 0;
  4981. Js::FunctionBody* fn = interpreterStackFrame->m_functionBody;
  4982. if (fn->RecentlyBailedOutOfJittedLoopBody())
  4983. {
  4984. if (doProfileLoopCheck && interpreterStackFrame->isAutoProfiling)
  4985. {
  4986. // Start profiling the loop after a bailout. Some bailouts require subsequent profile data collection such
  4987. // that the rejitted loop body would not bail out again for the same reason.
  4988. Assert(!interpreterStackFrame->switchProfileMode);
  4989. interpreterStackFrame->switchProfileMode = true;
  4990. Assert(interpreterStackFrame->switchProfileModeOnLoopEndNumber == 0u - 1);
  4991. interpreterStackFrame->switchProfileModeOnLoopEndNumber = loopNumber;
  4992. }
  4993. }
  4994. else
  4995. {
  4996. if (interpreterStackFrame->switchProfileModeOnLoopEndNumber == loopNumber)
  4997. {
  4998. // Stop profiling since the jitted loop body would be exiting the loop
  4999. Assert(!interpreterStackFrame->switchProfileMode);
  5000. interpreterStackFrame->switchProfileMode = true;
  5001. interpreterStackFrame->switchProfileModeOnLoopEndNumber = 0u - 1;
  5002. }
  5003. interpreterStackFrame->scriptContext->GetThreadContext()->DecrementLoopDepth();
  5004. }
  5005. }
  5006. };
  5007. #endif
  5008. Js::FunctionBody* fn = this->m_functionBody;
  5009. Assert(loopNumber < fn->GetLoopCount());
  5010. Assert(!this->IsInCatchOrFinallyBlock());
  5011. Js::LoopHeader *loopHeader = fn->GetLoopHeader(loopNumber);
  5012. loopHeader->isInTry = this->TestFlags(Js::InterpreterStackFrameFlags_WithinTryBlock);
  5013. loopHeader->isInTryFinally = this->TestFlags(Js::InterpreterStackFrameFlags_WithinTryFinallyBlock);
  5014. Js::LoopEntryPointInfo * entryPointInfo = loopHeader->GetCurrentEntryPointInfo();
  5015. if (fn->ForceJITLoopBody() && loopHeader->interpretCount == 0 &&
  5016. (entryPointInfo != NULL && entryPointInfo->IsNotScheduled()))
  5017. {
  5018. #if ENABLE_PROFILE_INFO
  5019. if (Js::DynamicProfileInfo::EnableImplicitCallFlags(GetFunctionBody()))
  5020. {
  5021. scriptContext->GetThreadContext()->AddImplicitCallFlags(this->savedLoopImplicitCallFlags[loopNumber]);
  5022. }
  5023. #endif
  5024. #if ENABLE_NATIVE_CODEGEN
  5025. GenerateLoopBody(scriptContext->GetNativeCodeGenerator(), fn, loopHeader, entryPointInfo, fn->GetLocalsCount(), this->m_localSlots);
  5026. #endif
  5027. }
  5028. #if ENABLE_NATIVE_CODEGEN
  5029. // If we have JITted the loop, call the JITted code
  5030. if (entryPointInfo != NULL && entryPointInfo->IsCodeGenDone())
  5031. {
  5032. #if DBG_DUMP
  5033. if (PHASE_TRACE1(Js::JITLoopBodyPhase) && CONFIG_FLAG(Verbose))
  5034. {
  5035. fn->DumpFunctionId(true);
  5036. Output::Print(_u(": %-20s LoopBody Execute Loop: %2d\n"), fn->GetDisplayName(), loopNumber);
  5037. Output::Flush();
  5038. }
  5039. loopHeader->nativeCount++;
  5040. #endif
  5041. #ifdef BGJIT_STATS
  5042. entryPointInfo->MarkAsUsed();
  5043. #endif
  5044. entryPointInfo->EnsureIsReadyToCall();
  5045. entryPointInfo->SetNativeEntryPointProcessed();
  5046. RegSlot envReg = this->m_functionBody->GetEnvRegister();
  5047. if (envReg != Constants::NoRegister)
  5048. {
  5049. this->SetNonVarReg(envReg, this->LdEnv());
  5050. }
  5051. RegSlot localClosureReg = this->m_functionBody->GetLocalClosureRegister();
  5052. RegSlot localFrameDisplayReg = this->m_functionBody->GetLocalFrameDisplayRegister();
  5053. RegSlot paramClosureReg = this->m_functionBody->GetParamClosureRegister();
  5054. if (entryPointInfo->HasJittedStackClosure())
  5055. {
  5056. // The jitted code is expecting the closure registers to point to known stack locations where
  5057. // the closures can be found and possibly boxed.
  5058. // In a jitted loop body, those locations are the local closure fields on the interpreter instance.
  5059. if (localClosureReg != Constants::NoRegister)
  5060. {
  5061. this->SetNonVarReg(localClosureReg, &this->localClosure);
  5062. }
  5063. if (localFrameDisplayReg != Constants::NoRegister)
  5064. {
  5065. this->SetNonVarReg(localFrameDisplayReg, &this->localFrameDisplay);
  5066. }
  5067. if (paramClosureReg != Constants::NoRegister)
  5068. {
  5069. this->SetNonVarReg(paramClosureReg, &this->paramClosure);
  5070. }
  5071. }
  5072. else
  5073. {
  5074. // In non-stack-closure jitted code, the closure registers are expected to hold the addresses
  5075. // of the actual structures.
  5076. if (localClosureReg != Constants::NoRegister)
  5077. {
  5078. this->SetNonVarReg(localClosureReg, this->localClosure);
  5079. }
  5080. if (localFrameDisplayReg != Constants::NoRegister)
  5081. {
  5082. this->SetNonVarReg(localFrameDisplayReg, this->localFrameDisplay);
  5083. }
  5084. if (paramClosureReg != Constants::NoRegister)
  5085. {
  5086. this->SetNonVarReg(paramClosureReg, this->paramClosure);
  5087. }
  5088. }
  5089. uint32 innerScopeCount = this->m_functionBody->GetInnerScopeCount();
  5090. for (uint32 i = 0; i < innerScopeCount; i++)
  5091. {
  5092. // As with the function-level scope, transfer the inner scopes from the interpreter's side storage
  5093. // to their dedicated register slots.
  5094. SetNonVarReg(this->m_functionBody->GetFirstInnerScopeRegister() + i, InnerScopeFromIndex(i));
  5095. }
  5096. uint newOffset = 0;
  5097. if (fn->GetIsAsmJsFunction())
  5098. {
  5099. AutoRestoreLoopNumbers autoRestore(this, loopNumber, doProfileLoopCheck);
  5100. newOffset = this->CallAsmJsLoopBody(entryPointInfo->jsMethod);
  5101. }
  5102. else
  5103. {
  5104. AutoRestoreLoopNumbers autoRestore(this, loopNumber, doProfileLoopCheck);
  5105. newOffset = this->CallLoopBody(entryPointInfo->jsMethod);
  5106. }
  5107. if (envReg != Constants::NoRegister)
  5108. {
  5109. SetNonVarReg(envReg, nullptr);
  5110. }
  5111. if (localClosureReg != Constants::NoRegister)
  5112. {
  5113. SetNonVarReg(localClosureReg, nullptr);
  5114. }
  5115. if (localFrameDisplayReg != Constants::NoRegister)
  5116. {
  5117. SetNonVarReg(localFrameDisplayReg, nullptr);
  5118. }
  5119. if (paramClosureReg != Constants::NoRegister)
  5120. {
  5121. SetNonVarReg(paramClosureReg, nullptr);
  5122. }
  5123. for (uint32 i = 0; i < innerScopeCount; i++)
  5124. {
  5125. // Get the (possibly updated) scopes from their registers and put them back in side storage.
  5126. // (Getting the updated values may not be necessary, actually, but it can't hurt.)
  5127. // Then null out the registers.
  5128. RegSlot reg = this->m_functionBody->GetFirstInnerScopeRegister() + i;
  5129. SetInnerScopeFromIndex(i, GetNonVarReg(reg));
  5130. SetNonVarReg(reg, nullptr);
  5131. }
  5132. Assert(Js::OpCodeUtil::GetOpCodeLayout(OpCode::ProfiledLoopBodyStart) == Js::OpLayoutType::Unsigned1);
  5133. Assert(Js::OpCodeUtil::GetOpCodeLayout(OpCode::LoopBodyStart) == Js::OpLayoutType::Unsigned1);
  5134. Assert(Js::OpCodeUtil::EncodedSize(Js::OpCode::LoopBodyStart, layoutSize) == Js::OpCodeUtil::EncodedSize(Js::OpCode::ProfiledLoopBodyStart, layoutSize));
  5135. uint byteCodeSize = Js::OpCodeUtil::EncodedSize(Js::OpCode::LoopBodyStart, layoutSize);
  5136. if (layoutSize == SmallLayout)
  5137. {
  5138. byteCodeSize += sizeof(OpLayoutUnsigned1_Small);
  5139. }
  5140. else if (layoutSize == MediumLayout)
  5141. {
  5142. byteCodeSize += sizeof(OpLayoutUnsigned1_Medium);
  5143. }
  5144. else
  5145. {
  5146. byteCodeSize += sizeof(OpLayoutUnsigned1_Large);
  5147. }
  5148. if (newOffset == loopHeader->startOffset || newOffset == m_reader.GetCurrentOffset() - byteCodeSize)
  5149. {
  5150. // If we bail out back the start of the loop, or start of this LoopBodyStart just skip and interpret the loop
  5151. // instead of trying to start the loop body again
  5152. // Increment the interpret count of the loop
  5153. loopHeader->interpretCount++;
  5154. }
  5155. else
  5156. {
  5157. this->CheckIfLoopIsHot(loopHeader->profiledLoopCounter);
  5158. if (newOffset >= loopHeader->endOffset)
  5159. {
  5160. // Reset the totalJittedLoopIterations for the next invocation of this loop entry point
  5161. entryPointInfo->totalJittedLoopIterations =
  5162. static_cast<uint8>(
  5163. min(
  5164. static_cast<uint>(static_cast<uint8>(CONFIG_FLAG(MinBailOutsBeforeRejit))) *
  5165. (Js::LoopEntryPointInfo::GetDecrLoopCountPerBailout() - 1),
  5166. entryPointInfo->totalJittedLoopIterations));
  5167. entryPointInfo->jittedLoopIterationsSinceLastBailout = 0;
  5168. }
  5169. m_reader.SetCurrentOffset(newOffset);
  5170. }
  5171. return loopHeader;
  5172. }
  5173. #endif
  5174. // Increment the interpret count of the loop
  5175. loopHeader->interpretCount += !isFirstIteration;
  5176. const uint loopInterpretCount = GetFunctionBody()->GetLoopInterpretCount(loopHeader);
  5177. if (loopHeader->interpretCount > loopInterpretCount)
  5178. {
  5179. if (this->scriptContext->GetConfig()->IsNoNative())
  5180. {
  5181. return nullptr;
  5182. }
  5183. if (!fn->DoJITLoopBody())
  5184. {
  5185. return nullptr;
  5186. }
  5187. #if ENABLE_NATIVE_CODEGEN
  5188. #if ENABLE_OOP_NATIVE_CODEGEN
  5189. // If for some reason OOP JIT isn't connected (e.g. it crashed), don't attempt to JIT a loop body
  5190. if (JITManager::GetJITManager()->IsOOPJITEnabled() && !JITManager::GetJITManager()->IsConnected())
  5191. {
  5192. return nullptr;
  5193. }
  5194. #endif
  5195. // If the job is not scheduled then we need to schedule it now.
  5196. // It is possible a job was scheduled earlier and we find ourselves looking at the same entry point
  5197. // again. For example, if the function with the loop was JITed and bailed out then as we finish
  5198. // the call in the interpreter we might encounter a loop for which we had scheduled a JIT job before
  5199. // the function was initially scheduled. In such cases, that old JIT job will complete. If it completes
  5200. // successfully then we can go ahead and use it. If it fails then it will eventually revert to the
  5201. // NotScheduled state. Since transitions from NotScheduled can only occur on the main thread,
  5202. // by checking the state we are safe from racing with the JIT thread when looking at the other fields
  5203. // of the entry point.
  5204. if (entryPointInfo != NULL && entryPointInfo->IsNotScheduled())
  5205. {
  5206. GenerateLoopBody(scriptContext->GetNativeCodeGenerator(), fn, loopHeader, entryPointInfo, fn->GetLocalsCount(), this->m_localSlots);
  5207. }
  5208. #endif
  5209. }
  5210. #if ENABLE_PROFILE_INFO
  5211. else if(
  5212. doProfileLoopCheck &&
  5213. isAutoProfiling &&
  5214. loopHeader->interpretCount > fn->GetLoopProfileThreshold(loopInterpretCount))
  5215. {
  5216. // Start profiling the loop so that the jitted loop body will have some profile data to use
  5217. Assert(!switchProfileMode);
  5218. switchProfileMode = true;
  5219. Assert(switchProfileModeOnLoopEndNumber == 0u - 1);
  5220. switchProfileModeOnLoopEndNumber = loopNumber;
  5221. }
  5222. #endif
  5223. return nullptr;
  5224. }
  5225. void
  5226. InterpreterStackFrame::CheckIfLoopIsHot(uint profiledLoopCounter)
  5227. {
  5228. Js::FunctionBody *fn = this->function->GetFunctionBody();
  5229. if (!fn->GetHasHotLoop() && profiledLoopCounter > (uint)CONFIG_FLAG(JitLoopBodyHotLoopThreshold))
  5230. {
  5231. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  5232. if(PHASE_TRACE(Js::JITLoopBodyPhase, fn))
  5233. {
  5234. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  5235. Output::Print(
  5236. _u("Speculate Jit set for this function with loopbody: function: %s (%s)\n"),
  5237. fn->GetDisplayName(),
  5238. fn->GetDebugNumberSet(debugStringBuffer));
  5239. Output::Flush();
  5240. }
  5241. #endif
  5242. fn->SetHasHotLoop();
  5243. }
  5244. }
  5245. bool InterpreterStackFrame::CheckAndResetImplicitCall(DisableImplicitFlags prevDisableImplicitFlags, ImplicitCallFlags savedImplicitCallFlags)
  5246. {
  5247. ImplicitCallFlags curImplicitCallFlags = this->scriptContext->GetThreadContext()->GetImplicitCallFlags();
  5248. if (curImplicitCallFlags > ImplicitCall_None)
  5249. {
  5250. //error implicit bit is set , reparse without asmjs
  5251. this->scriptContext->GetThreadContext()->SetDisableImplicitFlags(prevDisableImplicitFlags);
  5252. this->scriptContext->GetThreadContext()->SetImplicitCallFlags(savedImplicitCallFlags);
  5253. return true;
  5254. }
  5255. return false;
  5256. }
  5257. uint
  5258. InterpreterStackFrame::CallLoopBody(JavascriptMethod address)
  5259. {
  5260. #ifdef _M_IX86
  5261. void *savedEsp = NULL;
  5262. __asm
  5263. {
  5264. // Save ESP
  5265. mov savedEsp, esp
  5266. // 8-byte align frame to improve floating point perf of our JIT'd code.
  5267. and esp, -8
  5268. // Add an extra 4-bytes to the stack since we'll be pushing 3 arguments
  5269. push eax
  5270. }
  5271. #endif
  5272. #if defined(_M_ARM32_OR_ARM64)
  5273. // For ARM we need to make sure that pipeline is synchronized with memory/cache for newly jitted code.
  5274. // Note: this does not seem to affect perf, but if it was, we could add a boolean isCalled to EntryPointInfo
  5275. // and do ISB only for 1st time this entry point is called (potential working set regression though).
  5276. _InstructionSynchronizationBarrier();
  5277. #endif
  5278. uint newOffset = ::Math::PointerCastToIntegral<uint>(
  5279. CALL_ENTRYPOINT_NOASSERT(address, function, CallInfo(CallFlags_InternalFrame, 1), this));
  5280. #ifdef _M_IX86
  5281. _asm
  5282. {
  5283. // Restore ESP
  5284. mov esp, savedEsp
  5285. }
  5286. #endif
  5287. return newOffset;
  5288. }
  5289. uint
  5290. InterpreterStackFrame::CallAsmJsLoopBody(JavascriptMethod address)
  5291. {
  5292. #ifdef _M_IX86
  5293. void *savedEsp = NULL;
  5294. __asm
  5295. {
  5296. // Save ESP
  5297. mov savedEsp, esp
  5298. // Add an extra 4-bytes to the stack since we'll be pushing 3 arguments
  5299. push eax
  5300. }
  5301. #endif
  5302. #if defined(_M_ARM32_OR_ARM64)
  5303. // For ARM we need to make sure that pipeline is synchronized with memory/cache for newly jitted code.
  5304. // Note: this does not seem to affect perf, but if it was, we could add a boolean isCalled to EntryPointInfo
  5305. // and do ISB only for 1st time this entry point is called (potential working set regression though).
  5306. _InstructionSynchronizationBarrier();
  5307. #endif
  5308. uint newOffset = ::Math::PointerCastToIntegral<uint>(
  5309. CALL_ENTRYPOINT_NOASSERT(address, function, CallInfo(CallFlags_InternalFrame, 1), this));
  5310. #ifdef _M_IX86
  5311. _asm
  5312. {
  5313. // Restore ESP
  5314. mov esp, savedEsp
  5315. }
  5316. #endif
  5317. return newOffset;
  5318. }
  5319. template <class T>
  5320. void InterpreterStackFrame::OP_NewScObjectNoCtorFull(const unaligned T* playout)
  5321. {
  5322. Var function = GetReg(playout->R1);
  5323. Var newObj = JavascriptOperators::NewScObjectNoCtorFull(function, GetScriptContext());
  5324. SetReg(playout->R0, newObj);
  5325. }
  5326. ///----------------------------------------------------------------------------
  5327. ///
  5328. /// InterpreterStackFrame::OP_NewScObject
  5329. ///
  5330. /// OP_NewScObject() allocates a new DynamicObject and initializes it with an
  5331. /// optional "constructor" function.
  5332. ///
  5333. /// NOTE: The return register must be carefully chosen to ensure proper
  5334. /// behavior:
  5335. /// 1. OpCode::NewInstance should never specify "R0" as the register to
  5336. /// store the new instance, because it will get whacked from the
  5337. /// "constructor" function's return value:
  5338. ///
  5339. /// var a1 = Date(); <-- a1 = string returned from Date() function
  5340. /// var a2 = new Date(); <-- a2 = instance return from NewInstance.
  5341. /// Date()'s return value is thrown away.
  5342. ///
  5343. /// 2. If an exception is thrown during construction, the destination
  5344. /// variable / field should __not__ be modified. Therefore, the destination
  5345. /// register should always be a temporary and never a valid local variable.
  5346. /// After successfully returning from the constructor function, the new
  5347. /// instance is valid and may be stored in its final destination variable /
  5348. /// field.
  5349. ///
  5350. /// OPCODE NewObject:
  5351. /// T1 = new DynamicObject(Function.Prototype)
  5352. /// OutArg[0] = T1
  5353. /// Call(Function, ArgCount)
  5354. /// Local[Return] = T1
  5355. ///
  5356. /// - R0: Destination "local" register
  5357. /// - R1: Optional constructor JavascriptFunction instance or 'null'
  5358. ///
  5359. ///----------------------------------------------------------------------------
  5360. template <class T, bool Profiled, bool ICIndex>
  5361. void InterpreterStackFrame::OP_NewScObject_Impl(const unaligned T* playout, InlineCacheIndex inlineCacheIndex, const Js::AuxArray<uint32> *spreadIndices)
  5362. {
  5363. if (ICIndex)
  5364. {
  5365. Assert(inlineCacheIndex != Js::Constants::NoInlineCacheIndex);
  5366. }
  5367. Var newVarInstance =
  5368. #if ENABLE_PROFILE_INFO
  5369. Profiled ?
  5370. ProfiledNewScObject_Helper(
  5371. GetReg(playout->Function),
  5372. playout->ArgCount,
  5373. static_cast<const unaligned OpLayoutDynamicProfile<T> *>(playout)->profileId,
  5374. inlineCacheIndex,
  5375. spreadIndices) :
  5376. #endif
  5377. NewScObject_Helper(GetReg(playout->Function), playout->ArgCount, spreadIndices);
  5378. SetReg((RegSlot)playout->Return, newVarInstance);
  5379. }
  5380. template <class T, bool Profiled>
  5381. void InterpreterStackFrame::OP_NewScObjArray_Impl(const unaligned T* playout, const Js::AuxArray<uint32> *spreadIndices)
  5382. {
  5383. // Always profile this operation when auto-profiling so that array type changes are tracked
  5384. #if ENABLE_PROFILE_INFO
  5385. if (!Profiled && !isAutoProfiling)
  5386. #else
  5387. Assert(!Profiled);
  5388. #endif
  5389. {
  5390. OP_NewScObject_Impl<T, Profiled, false>(playout, Js::Constants::NoInlineCacheIndex, spreadIndices);
  5391. return;
  5392. }
  5393. #if ENABLE_PROFILE_INFO
  5394. Arguments args(CallInfo(CallFlags_New, playout->ArgCount), m_outParams);
  5395. uint32 spreadSize = 0;
  5396. if (spreadIndices != nullptr)
  5397. {
  5398. spreadSize = JavascriptFunction::GetSpreadSize(args, spreadIndices, scriptContext);
  5399. // Allocate room on the stack for the spread args.
  5400. Arguments outArgs(CallInfo(CallFlags_New, 0), nullptr);
  5401. outArgs.Info.Count = spreadSize;
  5402. const unsigned STACK_ARGS_ALLOCA_THRESHOLD = 8; // Number of stack args we allow before using _alloca
  5403. Var stackArgs[STACK_ARGS_ALLOCA_THRESHOLD];
  5404. size_t outArgsSize = 0;
  5405. if (outArgs.Info.Count > STACK_ARGS_ALLOCA_THRESHOLD)
  5406. {
  5407. PROBE_STACK(scriptContext, outArgs.Info.Count * sizeof(Var) + Js::Constants::MinStackDefault); // args + function call
  5408. outArgsSize = outArgs.Info.Count * sizeof(Var);
  5409. outArgs.Values = (Var*)_alloca(outArgsSize);
  5410. ZeroMemory(outArgs.Values, outArgsSize);
  5411. }
  5412. else
  5413. {
  5414. outArgs.Values = stackArgs;
  5415. outArgsSize = STACK_ARGS_ALLOCA_THRESHOLD * sizeof(Var);
  5416. ZeroMemory(outArgs.Values, outArgsSize); // We may not use all of the elements
  5417. }
  5418. JavascriptFunction::SpreadArgs(args, outArgs, spreadIndices, scriptContext);
  5419. SetReg(
  5420. (RegSlot)playout->Return,
  5421. ProfilingHelpers::ProfiledNewScObjArray(
  5422. GetReg(playout->Function),
  5423. outArgs,
  5424. function,
  5425. static_cast<const unaligned OpLayoutDynamicProfile2<T> *>(playout)->profileId,
  5426. static_cast<const unaligned OpLayoutDynamicProfile2<T> *>(playout)->profileId2));
  5427. }
  5428. else
  5429. {
  5430. SetReg(
  5431. (RegSlot)playout->Return,
  5432. ProfilingHelpers::ProfiledNewScObjArray(
  5433. GetReg(playout->Function),
  5434. args,
  5435. function,
  5436. static_cast<const unaligned OpLayoutDynamicProfile2<T> *>(playout)->profileId,
  5437. static_cast<const unaligned OpLayoutDynamicProfile2<T> *>(playout)->profileId2));
  5438. }
  5439. PopOut(playout->ArgCount);
  5440. #endif
  5441. }
  5442. void InterpreterStackFrame::OP_NewScObject_A_Impl(const unaligned OpLayoutAuxiliary * playout, RegSlot *target)
  5443. {
  5444. const Js::VarArrayVarCount * vars = Js::ByteCodeReader::ReadVarArrayVarCount(playout->Offset, this->GetFunctionBody());
  5445. int count = Js::TaggedInt::ToInt32(vars->count);
  5446. // Push the parameters to stack
  5447. for (int i=0;i<count; i++)
  5448. {
  5449. SetOut( (ArgSlot)(i+1), vars->elements[i]);
  5450. }
  5451. Var newVarInstance = NewScObject_Helper(GetReg((RegSlot)playout->C1), (ArgSlot)count+1);
  5452. SetReg((RegSlot)playout->R0, newVarInstance);
  5453. }
  5454. Var InterpreterStackFrame::NewScObject_Helper(Var target, ArgSlot ArgCount, const Js::AuxArray<uint32> *spreadIndices)
  5455. {
  5456. Arguments args(CallInfo(CallFlags_New, ArgCount), m_outParams);
  5457. Var newVarInstance = JavascriptOperators::NewScObject(target, args, GetScriptContext(), spreadIndices);
  5458. PopOut(ArgCount);
  5459. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(newVarInstance));
  5460. #if ENABLE_DEBUG_CONFIG_OPTIONS
  5461. if (Js::Configuration::Global.flags.IsEnabled(Js::autoProxyFlag))
  5462. {
  5463. newVarInstance = JavascriptProxy::AutoProxyWrapper(newVarInstance);
  5464. // this might come from a different scriptcontext.
  5465. newVarInstance = CrossSite::MarshalVar(GetScriptContext(), newVarInstance);
  5466. }
  5467. #endif
  5468. #ifdef ENABLE_BASIC_TELEMETRY
  5469. {
  5470. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().NewScriptObject( target, args, newVarInstance );
  5471. }
  5472. #endif
  5473. return newVarInstance;
  5474. }
  5475. #if ENABLE_PROFILE_INFO
  5476. Var InterpreterStackFrame::ProfiledNewScObject_Helper(Var target, ArgSlot ArgCount, ProfileId profileId, InlineCacheIndex inlineCacheIndex, const Js::AuxArray<uint32> *spreadIndices)
  5477. {
  5478. Arguments args(CallInfo(CallFlags_New, ArgCount), m_outParams);
  5479. Var newVarInstance =
  5480. ProfilingHelpers::ProfiledNewScObject(
  5481. target,
  5482. args,
  5483. GetFunctionBody(),
  5484. profileId,
  5485. inlineCacheIndex,
  5486. spreadIndices);
  5487. PopOut(ArgCount);
  5488. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(newVarInstance));
  5489. #if ENABLE_DEBUG_CONFIG_OPTIONS
  5490. if (Js::Configuration::Global.flags.IsEnabled(Js::autoProxyFlag))
  5491. {
  5492. newVarInstance = JavascriptProxy::AutoProxyWrapper(newVarInstance);
  5493. // this might come from a different scriptcontext.
  5494. newVarInstance = CrossSite::MarshalVar(GetScriptContext(), newVarInstance);
  5495. }
  5496. #endif
  5497. #ifdef TELEMETRY_PROFILED
  5498. {
  5499. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().NewScriptObject( target, args, newVarInstance );
  5500. }
  5501. #endif
  5502. return newVarInstance;
  5503. }
  5504. #endif
  5505. template <typename T>
  5506. void InterpreterStackFrame::OP_LdElementUndefined(const unaligned OpLayoutT_ElementU<T>* playout)
  5507. {
  5508. if (this->m_functionBody->IsEval())
  5509. {
  5510. JavascriptOperators::OP_LoadUndefinedToElementDynamic(GetReg(playout->Instance),
  5511. this->m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetScriptContext());
  5512. }
  5513. else
  5514. {
  5515. JavascriptOperators::OP_LoadUndefinedToElement(GetReg(playout->Instance),
  5516. this->m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex));
  5517. }
  5518. }
  5519. template <typename T>
  5520. void InterpreterStackFrame::OP_LdLocalElementUndefined(const unaligned OpLayoutT_ElementRootU<T>* playout)
  5521. {
  5522. if (this->m_functionBody->IsEval())
  5523. {
  5524. JavascriptOperators::OP_LoadUndefinedToElementDynamic(this->localClosure,
  5525. this->m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetScriptContext());
  5526. }
  5527. else
  5528. {
  5529. JavascriptOperators::OP_LoadUndefinedToElement(this->localClosure,
  5530. this->m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex));
  5531. }
  5532. }
  5533. template <typename T>
  5534. void InterpreterStackFrame::OP_LdElementUndefinedScoped(const unaligned OpLayoutT_ElementScopedU<T>* playout)
  5535. {
  5536. // Implicit root object as default instance
  5537. JavascriptOperators::OP_LoadUndefinedToElementScoped(GetEnvForEvalCode(),
  5538. this->m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetReg(Js::FunctionBody::RootObjectRegSlot), GetScriptContext());
  5539. }
  5540. void InterpreterStackFrame::OP_ChkUndecl(Var aValue)
  5541. {
  5542. if (this->scriptContext->IsUndeclBlockVar(aValue))
  5543. {
  5544. JavascriptError::ThrowReferenceError(scriptContext, JSERR_UseBeforeDeclaration);
  5545. }
  5546. }
  5547. void InterpreterStackFrame::OP_ChkNewCallFlag()
  5548. {
  5549. if (!(this->m_callFlags & CallFlags_New) && !this->TestFlags(InterpreterStackFrameFlags_FromBailOutInInlinee))
  5550. {
  5551. JavascriptError::ThrowTypeError(scriptContext, JSERR_ClassConstructorCannotBeCalledWithoutNew);
  5552. }
  5553. }
  5554. void InterpreterStackFrame::OP_EnsureNoRootProperty(uint propertyIdIndex)
  5555. {
  5556. Var instance = this->GetRootObject();
  5557. JavascriptOperators::OP_EnsureNoRootProperty(instance, this->m_functionBody->GetReferencedPropertyId(propertyIdIndex));
  5558. }
  5559. void InterpreterStackFrame::OP_EnsureNoRootRedeclProperty(uint propertyIdIndex)
  5560. {
  5561. Var instance = this->GetRootObject();
  5562. JavascriptOperators::OP_EnsureNoRootRedeclProperty(instance, this->m_functionBody->GetReferencedPropertyId(propertyIdIndex));
  5563. }
  5564. void InterpreterStackFrame::OP_ScopedEnsureNoRedeclProperty(Var aValue, uint propertyIdIndex, Var aValue2)
  5565. {
  5566. Js::PropertyId propertyId = this->m_functionBody->GetReferencedPropertyId(propertyIdIndex);
  5567. JavascriptOperators::OP_ScopedEnsureNoRedeclProperty((FrameDisplay*)aValue, propertyId, aValue2);
  5568. }
  5569. Var InterpreterStackFrame::OP_InitUndecl()
  5570. {
  5571. return this->scriptContext->GetLibrary()->GetUndeclBlockVar();
  5572. }
  5573. void InterpreterStackFrame::OP_InitUndeclSlot(Var aValue, int32 slot)
  5574. {
  5575. this->OP_StSlot(aValue, slot, this->scriptContext->GetLibrary()->GetUndeclBlockVar());
  5576. }
  5577. void InterpreterStackFrame::OP_TryCatch(const unaligned OpLayoutBr* playout)
  5578. {
  5579. Js::JavascriptExceptionObject* exception = NULL;
  5580. try
  5581. {
  5582. this->nestedTryDepth++;
  5583. // mark the stackFrame as 'in try block'
  5584. this->OrFlags(InterpreterStackFrameFlags_WithinTryBlock);
  5585. Js::JavascriptExceptionOperators::AutoCatchHandlerExists autoCatchHandlerExists(scriptContext);
  5586. #ifdef ENABLE_SCRIPT_DEBUGGING
  5587. if (this->IsInDebugMode())
  5588. {
  5589. #if ENABLE_TTD
  5590. if(SHOULD_DO_TTD_STACK_STMT_OP(this->scriptContext))
  5591. {
  5592. this->ProcessWithDebugging_PreviousStmtTracking();
  5593. }
  5594. else
  5595. {
  5596. this->ProcessWithDebugging();
  5597. }
  5598. #else
  5599. this->ProcessWithDebugging();
  5600. #endif
  5601. this->TrySetRetOffset();
  5602. }
  5603. else
  5604. #endif
  5605. {
  5606. this->Process();
  5607. this->TrySetRetOffset();
  5608. }
  5609. }
  5610. catch (const Js::JavascriptException& err)
  5611. {
  5612. // We are using C++ exception handling which does not unwind the stack in the catch block.
  5613. // For stack overflow and OOM exceptions, we cannot run user code here because the stack is not unwind.
  5614. exception = err.GetAndClear();
  5615. }
  5616. if (--this->nestedTryDepth == -1)
  5617. {
  5618. // unmark the stackFrame as 'in try block'
  5619. this->ClearFlags(InterpreterStackFrameFlags_WithinTryBlock);
  5620. }
  5621. // Now that the stack is unwound, let's run the catch block.
  5622. if (exception)
  5623. {
  5624. if (exception->IsGeneratorReturnException())
  5625. {
  5626. // Generator return scenario, so no need to go into the catch block and we must rethrow to propagate the exception to down level
  5627. JavascriptExceptionOperators::DoThrow(exception, scriptContext);
  5628. }
  5629. exception = exception->CloneIfStaticExceptionObject(scriptContext);
  5630. // We've got a JS exception. Grab the exception object and assign it to the
  5631. // catch object's location, then call the handler (i.e., we consume the Catch op here).
  5632. Var catchObject = exception->GetThrownObject(scriptContext);
  5633. m_reader.SetCurrentRelativeOffset((const byte *)(playout + 1), playout->RelativeJumpOffset);
  5634. LayoutSize layoutSize;
  5635. OpCode catchOp = m_reader.ReadOp(layoutSize);
  5636. #ifdef BYTECODE_BRANCH_ISLAND
  5637. if (catchOp == Js::OpCode::BrLong)
  5638. {
  5639. Assert(layoutSize == SmallLayout);
  5640. auto playoutBrLong = m_reader.BrLong();
  5641. m_reader.SetCurrentRelativeOffset((const byte *)(playoutBrLong + 1), playoutBrLong->RelativeJumpOffset);
  5642. catchOp = m_reader.ReadOp(layoutSize);
  5643. }
  5644. #endif
  5645. AssertMsg(catchOp == OpCode::Catch, "Catch op not found at catch offset");
  5646. RegSlot reg = layoutSize == SmallLayout ? m_reader.Reg1_Small()->R0 :
  5647. layoutSize == MediumLayout ? m_reader.Reg1_Medium()->R0 : m_reader.Reg1_Large()->R0;
  5648. SetReg(reg, catchObject);
  5649. ResetOut();
  5650. this->nestedCatchDepth++;
  5651. // mark the stackFrame as 'in catch block'
  5652. this->OrFlags(InterpreterStackFrameFlags_WithinCatchBlock);
  5653. this->ProcessCatch();
  5654. if (--this->nestedCatchDepth == -1)
  5655. {
  5656. // unmark the stackFrame as 'in catch block'
  5657. this->ClearFlags(InterpreterStackFrameFlags_WithinCatchBlock);
  5658. }
  5659. }
  5660. }
  5661. void InterpreterStackFrame::ProcessCatch()
  5662. {
  5663. #if ENABLE_TTD
  5664. //Clear any previous Exception Info
  5665. if(SHOULD_DO_TTD_STACK_STMT_OP(this->scriptContext))
  5666. {
  5667. this->scriptContext->GetThreadContext()->TTDExecutionInfo->ProcessCatchInfoForLastExecutedStatements();
  5668. }
  5669. #endif
  5670. #ifdef ENABLE_SCRIPT_DEBUGGING
  5671. if (this->IsInDebugMode())
  5672. {
  5673. this->DebugProcess();
  5674. }
  5675. else
  5676. #endif
  5677. {
  5678. this->Process();
  5679. }
  5680. }
  5681. int InterpreterStackFrame::ProcessFinally()
  5682. {
  5683. this->nestedFinallyDepth++;
  5684. int newOffset = 0;
  5685. #ifdef ENABLE_SCRIPT_DEBUGGING
  5686. if (this->IsInDebugMode())
  5687. {
  5688. newOffset = ::Math::PointerCastToIntegral<int>(this->DebugProcess());
  5689. }
  5690. else
  5691. #endif
  5692. {
  5693. newOffset = ::Math::PointerCastToIntegral<int>(this->Process());
  5694. }
  5695. return newOffset;
  5696. }
  5697. void InterpreterStackFrame::ProcessTryHandlerBailout(EHBailoutData * ehBailoutData, uint32 tryNestingDepth)
  5698. {
  5699. int catchOffset = ehBailoutData->catchOffset;
  5700. int finallyOffset = ehBailoutData->finallyOffset;
  5701. Js::JavascriptExceptionObject* exception = NULL;
  5702. if (catchOffset != 0 || finallyOffset != 0)
  5703. {
  5704. try
  5705. {
  5706. this->nestedTryDepth++;
  5707. // mark the stackFrame as 'in try block'
  5708. this->OrFlags(InterpreterStackFrameFlags_WithinTryBlock);
  5709. if (finallyOffset != 0)
  5710. {
  5711. this->OrFlags(InterpreterStackFrameFlags_WithinTryFinallyBlock);
  5712. }
  5713. if (tryNestingDepth != 0)
  5714. {
  5715. this->ProcessTryHandlerBailout(ehBailoutData->child, --tryNestingDepth);
  5716. }
  5717. if (catchOffset != 0)
  5718. {
  5719. Js::JavascriptExceptionOperators::AutoCatchHandlerExists autoCatchHandlerExists(scriptContext);
  5720. }
  5721. #ifdef ENABLE_SCRIPT_DEBUGGING
  5722. if (this->IsInDebugMode())
  5723. {
  5724. #if ENABLE_TTD
  5725. if(SHOULD_DO_TTD_STACK_STMT_OP(this->scriptContext))
  5726. {
  5727. this->ProcessWithDebugging_PreviousStmtTracking();
  5728. }
  5729. else
  5730. {
  5731. this->ProcessWithDebugging();
  5732. }
  5733. #else
  5734. this->ProcessWithDebugging();
  5735. #endif
  5736. this->TrySetRetOffset();
  5737. }
  5738. else
  5739. #endif
  5740. {
  5741. this->Process();
  5742. this->TrySetRetOffset();
  5743. }
  5744. }
  5745. catch (const Js::JavascriptException& err)
  5746. {
  5747. // We are using C++ exception handling which does not unwind the stack in the catch block.
  5748. // For stack overflow and OOM exceptions, we cannot run user code here because the stack is not unwind.
  5749. exception = err.GetAndClear();
  5750. }
  5751. }
  5752. else if (ehBailoutData->ht == HandlerType::HT_Catch)
  5753. {
  5754. this->nestedCatchDepth++;
  5755. // mark the stackFrame as 'in catch block'
  5756. this->OrFlags(InterpreterStackFrameFlags_WithinCatchBlock);
  5757. if (tryNestingDepth != 0)
  5758. {
  5759. this->ProcessTryHandlerBailout(ehBailoutData->child, --tryNestingDepth);
  5760. }
  5761. this->ProcessCatch();
  5762. if (--this->nestedCatchDepth == -1)
  5763. {
  5764. // unmark the stackFrame as 'in catch block'
  5765. this->ClearFlags(InterpreterStackFrameFlags_WithinCatchBlock);
  5766. }
  5767. return;
  5768. }
  5769. else
  5770. {
  5771. Assert(ehBailoutData->ht == HandlerType::HT_Finally);
  5772. this->nestedFinallyDepth++;
  5773. // mark the stackFrame as 'in finally block'
  5774. this->OrFlags(InterpreterStackFrameFlags_WithinFinallyBlock);
  5775. if (tryNestingDepth != 0)
  5776. {
  5777. this->ProcessTryHandlerBailout(ehBailoutData->child, --tryNestingDepth);
  5778. }
  5779. Js::JavascriptExceptionObject * exceptionObj = this->scriptContext->GetThreadContext()->GetPendingFinallyException();
  5780. this->scriptContext->GetThreadContext()->SetPendingFinallyException(nullptr);
  5781. int finallyEndOffset = this->ProcessFinally();
  5782. if (--this->nestedFinallyDepth == -1)
  5783. {
  5784. // unmark the stackFrame as 'in finally block'
  5785. this->ClearFlags(InterpreterStackFrameFlags_WithinFinallyBlock);
  5786. }
  5787. // Finally exited with LeaveNull, We don't throw for early returns
  5788. if (finallyEndOffset == 0 && exceptionObj)
  5789. {
  5790. JavascriptExceptionOperators::DoThrow(const_cast<Js::JavascriptExceptionObject *>(exceptionObj), scriptContext);
  5791. }
  5792. if (finallyEndOffset != 0)
  5793. {
  5794. m_reader.SetCurrentOffset(finallyEndOffset);
  5795. }
  5796. return;
  5797. }
  5798. if (--this->nestedTryDepth == -1)
  5799. {
  5800. // unmark the stackFrame as 'in try block'
  5801. this->ClearFlags(InterpreterStackFrameFlags_WithinTryBlock | InterpreterStackFrameFlags_WithinTryFinallyBlock);
  5802. }
  5803. // Now that the stack is unwound, let's run the catch block.
  5804. if (exception)
  5805. {
  5806. if (exception->IsGeneratorReturnException())
  5807. {
  5808. // Generator return scenario, so no need to go into the catch block and we must rethrow to propagate the exception to down level
  5809. JavascriptExceptionOperators::DoThrow(exception, scriptContext);
  5810. }
  5811. if (catchOffset != 0)
  5812. {
  5813. exception = exception->CloneIfStaticExceptionObject(scriptContext);
  5814. // We've got a JS exception. Grab the exception object and assign it to the
  5815. // catch object's location, then call the handler (i.e., we consume the Catch op here).
  5816. Var catchObject = exception->GetThrownObject(scriptContext);
  5817. m_reader.SetCurrentOffset(catchOffset);
  5818. LayoutSize layoutSize;
  5819. OpCode catchOp = m_reader.ReadOp(layoutSize);
  5820. #ifdef BYTECODE_BRANCH_ISLAND
  5821. if (catchOp == Js::OpCode::BrLong)
  5822. {
  5823. Assert(layoutSize == SmallLayout);
  5824. auto playoutBrLong = m_reader.BrLong();
  5825. m_reader.SetCurrentRelativeOffset((const byte *)(playoutBrLong + 1), playoutBrLong->RelativeJumpOffset);
  5826. catchOp = m_reader.ReadOp(layoutSize);
  5827. }
  5828. #endif
  5829. AssertMsg(catchOp == OpCode::Catch, "Catch op not found at catch offset");
  5830. RegSlot reg = layoutSize == SmallLayout ? m_reader.Reg1_Small()->R0 :
  5831. layoutSize == MediumLayout ? m_reader.Reg1_Medium()->R0 : m_reader.Reg1_Large()->R0;
  5832. SetReg(reg, catchObject);
  5833. ResetOut();
  5834. this->nestedCatchDepth++;
  5835. // mark the stackFrame as 'in catch block'
  5836. this->OrFlags(InterpreterStackFrameFlags_WithinCatchBlock);
  5837. this->ProcessCatch();
  5838. if (--this->nestedCatchDepth == -1)
  5839. {
  5840. // unmark the stackFrame as 'in catch block'
  5841. this->ClearFlags(InterpreterStackFrameFlags_WithinCatchBlock);
  5842. }
  5843. }
  5844. else
  5845. {
  5846. Assert(finallyOffset != 0);
  5847. exception = exception->CloneIfStaticExceptionObject(scriptContext);
  5848. m_reader.SetCurrentOffset(finallyOffset);
  5849. ResetOut();
  5850. this->nestedFinallyDepth++;
  5851. // mark the stackFrame as 'in finally block'
  5852. this->OrFlags(InterpreterStackFrameFlags_WithinFinallyBlock);
  5853. LayoutSize layoutSize;
  5854. OpCode finallyOp = m_reader.ReadOp(layoutSize);
  5855. #ifdef BYTECODE_BRANCH_ISLAND
  5856. if (finallyOp == Js::OpCode::BrLong)
  5857. {
  5858. Assert(layoutSize == SmallLayout);
  5859. auto playoutBrLong = m_reader.BrLong();
  5860. m_reader.SetCurrentRelativeOffset((const byte *)(playoutBrLong + 1), playoutBrLong->RelativeJumpOffset);
  5861. finallyOp = m_reader.ReadOp(layoutSize);
  5862. }
  5863. #endif
  5864. Assert(finallyOp == Js::OpCode::Finally);
  5865. int finallyEndOffset = this->ProcessFinally();
  5866. if (--this->nestedFinallyDepth == -1)
  5867. {
  5868. // unmark the stackFrame as 'in finally block'
  5869. this->ClearFlags(InterpreterStackFrameFlags_WithinFinallyBlock);
  5870. }
  5871. if (finallyEndOffset == 0)
  5872. {
  5873. JavascriptExceptionOperators::DoThrow(exception, scriptContext);
  5874. }
  5875. m_reader.SetCurrentOffset(finallyEndOffset);
  5876. }
  5877. }
  5878. else
  5879. {
  5880. if (finallyOffset != 0)
  5881. {
  5882. int currOffset = m_reader.GetCurrentOffset();
  5883. m_reader.SetCurrentOffset(finallyOffset);
  5884. this->nestedFinallyDepth++;
  5885. // mark the stackFrame as 'in finally block'
  5886. this->OrFlags(InterpreterStackFrameFlags_WithinFinallyBlock);
  5887. LayoutSize layoutSize;
  5888. OpCode finallyOp = m_reader.ReadOp(layoutSize);
  5889. #ifdef BYTECODE_BRANCH_ISLAND
  5890. if (finallyOp == Js::OpCode::BrLong)
  5891. {
  5892. Assert(layoutSize == SmallLayout);
  5893. auto playoutBrLong = m_reader.BrLong();
  5894. m_reader.SetCurrentRelativeOffset((const byte *)(playoutBrLong + 1), playoutBrLong->RelativeJumpOffset);
  5895. finallyOp = m_reader.ReadOp(layoutSize);
  5896. }
  5897. #endif
  5898. Assert(finallyOp == Js::OpCode::Finally);
  5899. int finallyEndOffset = this->ProcessFinally();
  5900. if (--this->nestedFinallyDepth == -1)
  5901. {
  5902. // unmark the stackFrame as 'in finally block'
  5903. this->ClearFlags(InterpreterStackFrameFlags_WithinFinallyBlock);
  5904. }
  5905. if (finallyEndOffset == 0)
  5906. {
  5907. m_reader.SetCurrentOffset(currOffset);
  5908. }
  5909. }
  5910. }
  5911. }
  5912. void InterpreterStackFrame::TrySetRetOffset()
  5913. {
  5914. Assert(this->TestFlags(Js::InterpreterStackFrameFlags_WithinTryBlock));
  5915. // It may happen that a JITted loop body returned the offset of RET. If the loop body was
  5916. // called from a try, the interpreter "Process()" should also just return.
  5917. if (this->retOffset != 0)
  5918. {
  5919. m_reader.SetCurrentOffset(this->retOffset);
  5920. }
  5921. }
  5922. bool InterpreterStackFrame::IsInCatchOrFinallyBlock()
  5923. {
  5924. return this->TestFlags(Js::InterpreterStackFrameFlags_WithinCatchBlock) ||
  5925. this->TestFlags(Js::InterpreterStackFrameFlags_WithinFinallyBlock);
  5926. }
  5927. void InterpreterStackFrame::OP_BeginBodyScope()
  5928. {
  5929. // Currently we are using the closures created for the param scope.
  5930. // This marks the beginning of the body scope, so let's create new closures for the body scope.
  5931. FunctionBody *executeFunction = this->function->GetFunctionBody();
  5932. Assert(!this->IsParamScopeDone() && !executeFunction->IsParamAndBodyScopeMerged());
  5933. // Save the current closure. We have to use this while copying the initial value of body symbols
  5934. // from the corresponding symbols in the param.
  5935. this->SetParamClosure(this->GetLocalClosure());
  5936. this->SetNonVarReg(executeFunction->GetParamClosureRegister(), nullptr);
  5937. this->SetIsParamScopeDone(true);
  5938. // Create a new local closure for the body when either body scope has scope slots allocated or
  5939. // eval is present which can leak declarations.
  5940. if (executeFunction->scopeSlotArraySize > 0 || executeFunction->HasScopeObject())
  5941. {
  5942. this->InitializeClosures();
  5943. }
  5944. }
  5945. void InterpreterStackFrame::OP_ResumeCatch()
  5946. {
  5947. this->OrFlags(InterpreterStackFrameFlags_WithinCatchBlock);
  5948. #ifdef ENABLE_SCRIPT_DEBUGGING
  5949. if (this->IsInDebugMode())
  5950. {
  5951. this->DebugProcess();
  5952. }
  5953. else
  5954. #endif
  5955. {
  5956. this->Process();
  5957. }
  5958. this->ClearFlags(InterpreterStackFrameFlags_WithinCatchBlock);
  5959. }
  5960. /// ---------------------------------------------------------------------------------------------------
  5961. /// The behavior we want is the following:
  5962. /// - If the control leaves the user's try without throwing, execute the finally and continue
  5963. /// after the end of the try.
  5964. /// - If the user code throws, catch this exception and then execute this finally while unwinding to
  5965. /// the handler (if any).
  5966. /// ---------------------------------------------------------------------------------------------------
  5967. void InterpreterStackFrame::ProcessTryFinally(const byte* ip, Js::JumpOffset jumpOffset, Js::RegSlot regException, Js::RegSlot regOffset, bool hasYield)
  5968. {
  5969. Js::JavascriptExceptionObject* pExceptionObject = nullptr;
  5970. bool skipFinallyBlock = false;
  5971. try
  5972. {
  5973. Js::Var result = nullptr;
  5974. this->nestedTryDepth++;
  5975. // mark the stackFrame as 'in try block'
  5976. this->OrFlags(InterpreterStackFrameFlags_WithinTryBlock | InterpreterStackFrameFlags_WithinTryFinallyBlock);
  5977. if (shouldCacheSP)
  5978. {
  5979. CacheSp();
  5980. }
  5981. #ifdef ENABLE_SCRIPT_DEBUGGING
  5982. if (this->IsInDebugMode())
  5983. {
  5984. #if ENABLE_TTD
  5985. if(SHOULD_DO_TTD_STACK_STMT_OP(this->scriptContext))
  5986. {
  5987. result = this->ProcessWithDebugging_PreviousStmtTracking();
  5988. }
  5989. else
  5990. {
  5991. result = this->ProcessWithDebugging();
  5992. }
  5993. #else
  5994. result = this->ProcessWithDebugging();
  5995. #endif
  5996. }
  5997. else
  5998. #endif
  5999. {
  6000. result = this->Process();
  6001. }
  6002. if (result == nullptr)
  6003. {
  6004. Assert(hasYield);
  6005. skipFinallyBlock = true;
  6006. }
  6007. }
  6008. catch (const Js::JavascriptException& err)
  6009. {
  6010. pExceptionObject = err.GetAndClear();
  6011. }
  6012. if (--this->nestedTryDepth == -1)
  6013. {
  6014. // unmark the stackFrame as 'in try block'
  6015. this->ClearFlags(InterpreterStackFrameFlags_WithinTryBlock | InterpreterStackFrameFlags_WithinTryFinallyBlock);
  6016. }
  6017. shouldCacheSP = !skipFinallyBlock;
  6018. if (skipFinallyBlock)
  6019. {
  6020. // A leave occurred due to a yield
  6021. return;
  6022. }
  6023. // Save the current IP so execution can continue there if the finally doesn't
  6024. // take control of the flow.
  6025. int newOffset = 0;
  6026. int currOffset = m_reader.GetCurrentOffset();
  6027. if (hasYield)
  6028. {
  6029. // save the exception if there is one to a register in case we yield during the finally block
  6030. // and need to get that exception object back upon resume in OP_ResumeFinally
  6031. SetNonVarReg(regException, pExceptionObject);
  6032. SetNonVarReg(regOffset, reinterpret_cast<Js::Var>(currOffset));
  6033. }
  6034. if (pExceptionObject && !pExceptionObject->IsGeneratorReturnException())
  6035. {
  6036. // Clone static exception object early in case finally block overwrites it
  6037. pExceptionObject = pExceptionObject->CloneIfStaticExceptionObject(scriptContext);
  6038. }
  6039. #ifdef ENABLE_SCRIPT_DEBUGGING
  6040. if (pExceptionObject && this->IsInDebugMode() &&
  6041. pExceptionObject != scriptContext->GetThreadContext()->GetPendingSOErrorObject())
  6042. {
  6043. // Swallowing an exception that has triggered a finally is not implemented
  6044. // (This appears to be the same behavior as ie8)
  6045. pExceptionObject->SetDebuggerSkip(false);
  6046. }
  6047. #endif
  6048. // Call into the finally by setting the IP, consuming the Finally, and letting the interpreter recurse.
  6049. m_reader.SetCurrentRelativeOffset(ip, jumpOffset);
  6050. RestoreSp();
  6051. // mark the stackFrame as 'in finally block'
  6052. this->OrFlags(InterpreterStackFrameFlags_WithinFinallyBlock);
  6053. LayoutSize layoutSize;
  6054. OpCode finallyOp = m_reader.ReadOp(layoutSize);
  6055. #ifdef BYTECODE_BRANCH_ISLAND
  6056. if (finallyOp == Js::OpCode::BrLong)
  6057. {
  6058. Assert(layoutSize == SmallLayout);
  6059. auto playoutBrLong = m_reader.BrLong();
  6060. m_reader.SetCurrentRelativeOffset((const byte *)(playoutBrLong + 1), playoutBrLong->RelativeJumpOffset);
  6061. finallyOp = m_reader.ReadOp(layoutSize);
  6062. }
  6063. #endif
  6064. AssertMsg(finallyOp == OpCode::Finally, "Finally op not found at catch offset");
  6065. newOffset = this->ProcessFinally();
  6066. if (--this->nestedFinallyDepth == -1)
  6067. {
  6068. // unmark the stackFrame as 'in finally block'
  6069. this->ClearFlags(InterpreterStackFrameFlags_WithinFinallyBlock);
  6070. }
  6071. bool endOfFinallyBlock = newOffset == 0;
  6072. if (endOfFinallyBlock)
  6073. {
  6074. // Finally completed without taking over the flow. Resume where we left off before calling it.
  6075. m_reader.SetCurrentOffset(currOffset);
  6076. }
  6077. else
  6078. {
  6079. // Finally seized the flow with a jump out of its scope. Resume at the jump target and
  6080. // force the runtime to return to this frame without executing the catch.
  6081. m_reader.SetCurrentOffset(newOffset);
  6082. return;
  6083. }
  6084. if (pExceptionObject && (endOfFinallyBlock || !pExceptionObject->IsGeneratorReturnException()))
  6085. {
  6086. JavascriptExceptionOperators::DoThrow(pExceptionObject, scriptContext);
  6087. }
  6088. }
  6089. void InterpreterStackFrame::OP_TryFinally(const unaligned OpLayoutBr* playout)
  6090. {
  6091. ProcessTryFinally((const byte*)(playout + 1), playout->RelativeJumpOffset);
  6092. }
  6093. void InterpreterStackFrame::OP_TryFinallyWithYield(const byte* ip, Js::JumpOffset jumpOffset, Js::RegSlot regException, Js::RegSlot regOffset)
  6094. {
  6095. ProcessTryFinally(ip, jumpOffset, regException, regOffset, true);
  6096. }
  6097. void InterpreterStackFrame::OP_ResumeFinally(const byte* ip, Js::JumpOffset jumpOffset, RegSlot exceptionRegSlot, RegSlot offsetRegSlot)
  6098. {
  6099. this->OrFlags(InterpreterStackFrameFlags_WithinFinallyBlock);
  6100. int newOffset = 0;
  6101. #ifdef ENABLE_SCRIPT_DEBUGGING
  6102. if (this->IsInDebugMode())
  6103. {
  6104. newOffset = ::Math::PointerCastToIntegral<int>(this->DebugProcess());
  6105. }
  6106. else
  6107. #endif
  6108. {
  6109. newOffset = ::Math::PointerCastToIntegral<int>(this->Process());
  6110. }
  6111. this->ClearFlags(InterpreterStackFrameFlags_WithinFinallyBlock);
  6112. bool endOfFinallyBlock = newOffset == 0;
  6113. if (endOfFinallyBlock)
  6114. {
  6115. // Finally completed without taking over the flow. Resume where we left off before calling it.
  6116. int currOffset = ::Math::PointerCastToIntegral<int>(GetNonVarReg(offsetRegSlot));
  6117. m_reader.SetCurrentOffset(currOffset);
  6118. }
  6119. else
  6120. {
  6121. // Finally seized the flow with a jump out of its scope. Resume at the jump target and
  6122. // force the runtime to return to this frame without executing the catch.
  6123. m_reader.SetCurrentOffset(newOffset);
  6124. return;
  6125. }
  6126. Js::JavascriptExceptionObject* exceptionObj = (Js::JavascriptExceptionObject*)GetNonVarReg(exceptionRegSlot);
  6127. if (exceptionObj && (endOfFinallyBlock || !exceptionObj->IsGeneratorReturnException()))
  6128. {
  6129. JavascriptExceptionOperators::DoThrow(exceptionObj, scriptContext);
  6130. }
  6131. }
  6132. template <typename T>
  6133. void InterpreterStackFrame::OP_IsInst(const unaligned T* playout)
  6134. {
  6135. Var instance = GetReg(playout->R1);
  6136. Var function = GetReg(playout->R2);
  6137. IsInstInlineCache *inlineCache = this->GetIsInstInlineCache(playout->inlineCacheIndex);
  6138. ScriptContext* scriptContext = GetScriptContext();
  6139. Var result = JavascriptOperators::OP_IsInst(instance, function, scriptContext, inlineCache);
  6140. #ifdef ENABLE_BASIC_TELEMETRY
  6141. {
  6142. this->scriptContext->GetTelemetry().GetOpcodeTelemetry().IsInstanceOf(instance, function, result);
  6143. }
  6144. #endif
  6145. SetReg(playout->R0, result);
  6146. }
  6147. template <typename T>
  6148. void InterpreterStackFrame::OP_ApplyArgs(const unaligned OpLayoutT_Reg5<T> * playout)
  6149. {
  6150. // Always save and restore implicit call flags when calling out
  6151. // REVIEW: Can we avoid it if we don't collect dynamic profile info?
  6152. ThreadContext * threadContext = scriptContext->GetThreadContext();
  6153. Js::ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  6154. // Currently ApplyArgs is equivalent to CallFldVoid (where we don't use the return value)
  6155. Var v=GetNonVarReg(playout->R4);
  6156. JavascriptOperators::OP_ApplyArgs(GetReg(playout->R1),GetReg(playout->R2),
  6157. (void**)GetNonVarReg(playout->R3),*((CallInfo*)&v),GetScriptContext());
  6158. threadContext->SetImplicitCallFlags(savedImplicitCallFlags);
  6159. }
  6160. void InterpreterStackFrame::OP_SpreadArrayLiteral(const unaligned OpLayoutReg2Aux * playout)
  6161. {
  6162. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  6163. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  6164. threadContext->ClearImplicitCallFlags();
  6165. Var instance = GetReg(playout->R1);
  6166. #if ENABLE_COPYONACCESS_ARRAY
  6167. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(instance);
  6168. #endif
  6169. const Js::AuxArray<uint32> *spreadIndices = m_reader.ReadAuxArray<uint32>(playout->Offset, this->GetFunctionBody());
  6170. ScriptContext* scriptContext = GetScriptContext();
  6171. Var result = JavascriptArray::SpreadArrayArgs(instance, spreadIndices, scriptContext);
  6172. threadContext->CheckAndResetImplicitCallAccessorFlag();
  6173. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  6174. SetReg(playout->R0, result);
  6175. }
  6176. FrameDisplay *
  6177. InterpreterStackFrame::OP_LdInnerFrameDisplay(void *argHead, void *argEnv, ScriptContext *scriptContext)
  6178. {
  6179. JavascriptOperators::CheckInnerFrameDisplayArgument(argHead);
  6180. return OP_LdFrameDisplay(argHead, argEnv, scriptContext);
  6181. }
  6182. FrameDisplay *
  6183. InterpreterStackFrame::OP_LdInnerFrameDisplayNoParent(void *argHead, ScriptContext *scriptContext)
  6184. {
  6185. JavascriptOperators::CheckInnerFrameDisplayArgument(argHead);
  6186. return OP_LdFrameDisplayNoParent<true>(argHead, scriptContext);
  6187. }
  6188. FrameDisplay *
  6189. InterpreterStackFrame::OP_LdFrameDisplay(void *argHead, void *argEnv, ScriptContext *scriptContext)
  6190. {
  6191. FrameDisplay *frameDisplay;
  6192. bool strict = this->m_functionBody->GetIsStrictMode();
  6193. if (strict)
  6194. {
  6195. frameDisplay = JavascriptOperators::OP_LdStrictFrameDisplay(argHead, argEnv, scriptContext);
  6196. }
  6197. else
  6198. {
  6199. frameDisplay = JavascriptOperators::OP_LdFrameDisplay(argHead, argEnv, scriptContext);
  6200. }
  6201. return frameDisplay;
  6202. }
  6203. FrameDisplay *
  6204. InterpreterStackFrame::OP_LdFrameDisplaySetLocal(void *argHead, void *argEnv, ScriptContext *scriptContext)
  6205. {
  6206. FrameDisplay *frameDisplay = OP_LdFrameDisplay(argHead, argEnv, scriptContext);
  6207. this->SetLocalFrameDisplay(frameDisplay);
  6208. return frameDisplay;
  6209. }
  6210. FrameDisplay *
  6211. InterpreterStackFrame::NewFrameDisplay(void *argHead, void *argEnv)
  6212. {
  6213. FrameDisplay *frameDisplay;
  6214. bool strict = this->m_functionBody->GetIsStrictMode();
  6215. if (!this->m_functionBody->DoStackFrameDisplay() || !this->GetLocalFrameDisplay())
  6216. {
  6217. // Null local frame display probably indicates that we bailed out of an inlinee.
  6218. // Once we support stack closures in inlined functions, we can just assert that this value
  6219. // is never null if we should be allocating on the stack.
  6220. return this->OP_LdFrameDisplaySetLocal(argHead, argEnv, this->GetScriptContext());
  6221. }
  6222. frameDisplay = this->GetLocalFrameDisplay();
  6223. Assert(frameDisplay != nullptr);
  6224. frameDisplay->SetTag(true);
  6225. frameDisplay->SetStrictMode(strict);
  6226. frameDisplay->SetLength(this->m_functionBody->GetEnvDepth() + 1);
  6227. Assert(frameDisplay->GetLength() == ((FrameDisplay*)argEnv)->GetLength() + 1);
  6228. for (uint i = 0; i < ((FrameDisplay*)argEnv)->GetLength(); i++)
  6229. {
  6230. frameDisplay->SetItem(i + 1, ((FrameDisplay*)argEnv)->GetItem(i));
  6231. }
  6232. frameDisplay->SetItem(0, argHead);
  6233. return frameDisplay;
  6234. }
  6235. template<bool innerFD>
  6236. FrameDisplay *
  6237. InterpreterStackFrame::OP_LdFrameDisplayNoParent(void *argHead, ScriptContext *scriptContext)
  6238. {
  6239. FrameDisplay *frameDisplay;
  6240. bool strict = this->m_functionBody->GetIsStrictMode();
  6241. Var argEnv = nullptr;
  6242. if (innerFD && this->m_functionBody->GetLocalFrameDisplayRegister() != Constants::NoRegister)
  6243. {
  6244. argEnv = this->GetLocalFrameDisplay();
  6245. }
  6246. if (argEnv == nullptr && this->m_functionBody->GetEnvRegister() != Constants::NoRegister)
  6247. {
  6248. argEnv = this->LdEnv();
  6249. }
  6250. if (argEnv == nullptr)
  6251. {
  6252. if (strict)
  6253. {
  6254. frameDisplay = JavascriptOperators::OP_LdStrictFrameDisplayNoParent(argHead, scriptContext);
  6255. }
  6256. else
  6257. {
  6258. frameDisplay = JavascriptOperators::OP_LdFrameDisplayNoParent(argHead, scriptContext);
  6259. }
  6260. }
  6261. else
  6262. {
  6263. if (strict)
  6264. {
  6265. frameDisplay = JavascriptOperators::OP_LdStrictFrameDisplay(argHead, argEnv, scriptContext);
  6266. }
  6267. else
  6268. {
  6269. frameDisplay = JavascriptOperators::OP_LdFrameDisplay(argHead, argEnv, scriptContext);
  6270. }
  6271. }
  6272. return frameDisplay;
  6273. }
  6274. FrameDisplay *
  6275. InterpreterStackFrame::OP_LdFuncExprFrameDisplaySetLocal(void *argHead1, void *argHead2, ScriptContext *scriptContext)
  6276. {
  6277. FrameDisplay *frameDisplay = OP_LdFrameDisplayNoParent<false>(argHead2, scriptContext);
  6278. frameDisplay = OP_LdFrameDisplay(argHead1, frameDisplay, scriptContext);
  6279. this->SetLocalFrameDisplay(frameDisplay);
  6280. return frameDisplay;
  6281. }
  6282. FrameDisplay* InterpreterStackFrame::GetLocalFrameDisplay() const
  6283. {
  6284. Assert(this->localFrameDisplay == nullptr || this->IsClosureInitDone() || this->localFrameDisplay->GetLength() == 0);
  6285. return this->localFrameDisplay;
  6286. }
  6287. void InterpreterStackFrame::SetLocalFrameDisplay(FrameDisplay* frameDisplay)
  6288. {
  6289. this->localFrameDisplay = frameDisplay;
  6290. }
  6291. Var InterpreterStackFrame::GetLocalClosure() const
  6292. {
  6293. return this->localClosure;
  6294. }
  6295. void InterpreterStackFrame::SetLocalClosure(Var closure)
  6296. {
  6297. this->localClosure = closure;
  6298. }
  6299. Var InterpreterStackFrame::GetParamClosure() const
  6300. {
  6301. return this->paramClosure;
  6302. }
  6303. void InterpreterStackFrame::SetParamClosure(Var closure)
  6304. {
  6305. this->paramClosure = closure;
  6306. }
  6307. void
  6308. InterpreterStackFrame::OP_NewInnerScopeSlots(uint innerScopeIndex, uint count, int scopeIndex, ScriptContext *scriptContext, FunctionBody *functionBody)
  6309. {
  6310. Field(Var)* slotArray =
  6311. JavascriptOperators::OP_NewScopeSlotsWithoutPropIds(count, scopeIndex, scriptContext, functionBody);
  6312. this->SetInnerScopeFromIndex(innerScopeIndex, slotArray);
  6313. }
  6314. template <typename T>
  6315. void InterpreterStackFrame::OP_CloneInnerScopeSlots(const unaligned OpLayoutT_Unsigned1<T> *playout)
  6316. {
  6317. uint innerScopeIndex = playout->C1;
  6318. Field(Var) * slotArray;
  6319. slotArray = (Field(Var)*)this->InnerScopeFromIndex(innerScopeIndex);
  6320. slotArray = JavascriptOperators::OP_CloneScopeSlots(slotArray, scriptContext);
  6321. this->SetInnerScopeFromIndex(innerScopeIndex, slotArray);
  6322. }
  6323. template <typename T>
  6324. void InterpreterStackFrame::OP_CloneBlockScope(const unaligned OpLayoutT_Unsigned1<T> *playout)
  6325. {
  6326. uint innerScopeIndex = playout->C1;
  6327. Var scope = this->InnerScopeFromIndex(innerScopeIndex);
  6328. BlockActivationObject* blockScope = BlockActivationObject::FromVar(scope);
  6329. scope = JavascriptOperators::OP_CloneBlockScope(blockScope, scriptContext);
  6330. this->SetInnerScopeFromIndex(innerScopeIndex, scope);
  6331. }
  6332. Field(Var)*
  6333. InterpreterStackFrame::NewScopeSlots(unsigned int size, ScriptContext *scriptContext, Var scope)
  6334. {
  6335. Field(Var)* slotArray = JavascriptOperators::OP_NewScopeSlots(size, scriptContext, scope);
  6336. this->SetLocalClosure(slotArray);
  6337. return slotArray;
  6338. }
  6339. Field(Var)*
  6340. InterpreterStackFrame::NewScopeSlots()
  6341. {
  6342. Field(Var)* slotArray;
  6343. FunctionBody * functionBody = this->m_functionBody;
  6344. uint scopeSlotCount = this->IsParamScopeDone() ? functionBody->scopeSlotArraySize : functionBody->paramScopeSlotArraySize;
  6345. Assert(scopeSlotCount != 0);
  6346. if (!functionBody->DoStackScopeSlots())
  6347. {
  6348. return this->NewScopeSlots(
  6349. scopeSlotCount + ScopeSlots::FirstSlotIndex, this->GetScriptContext(), (Var)functionBody->GetFunctionInfo());
  6350. }
  6351. slotArray = (Field(Var)*)this->GetLocalClosure();
  6352. Assert(slotArray != nullptr);
  6353. ScopeSlots scopeSlots(slotArray);
  6354. scopeSlots.SetCount(scopeSlotCount);
  6355. scopeSlots.SetScopeMetadata((Var)functionBody->GetFunctionInfo());
  6356. Var undef = functionBody->GetScriptContext()->GetLibrary()->GetUndefined();
  6357. for (unsigned int i = 0; i < scopeSlotCount; i++)
  6358. {
  6359. scopeSlots.Set(i, undef);
  6360. }
  6361. return slotArray;
  6362. }
  6363. Var
  6364. InterpreterStackFrame::NewScopeObject()
  6365. {
  6366. Var scopeObject;
  6367. if (m_functionBody->HasCachedScopePropIds())
  6368. {
  6369. const Js::PropertyIdArray *propIds = this->m_functionBody->GetFormalsPropIdArray();
  6370. JavascriptFunction* funcExpr = this->GetFunctionExpression();
  6371. PropertyId objectId = ActivationObjectEx::GetLiteralObjectRef(propIds);
  6372. scopeObject = JavascriptOperators::OP_InitCachedScope(funcExpr, propIds,
  6373. this->GetFunctionBody()->GetObjectLiteralTypeRef(objectId),
  6374. propIds->hasNonSimpleParams, GetScriptContext());
  6375. }
  6376. else
  6377. {
  6378. scopeObject = JavascriptOperators::OP_NewScopeObject(GetScriptContext());
  6379. }
  6380. this->SetLocalClosure(scopeObject);
  6381. return scopeObject;
  6382. }
  6383. FrameDisplay *
  6384. InterpreterStackFrame::GetFrameDisplayForNestedFunc() const
  6385. {
  6386. if (this->localFrameDisplay == nullptr)
  6387. {
  6388. return (FrameDisplay*)LdEnv();
  6389. }
  6390. return this->localFrameDisplay;
  6391. }
  6392. template <class T>
  6393. void InterpreterStackFrame::OP_NewStackScFunc(const unaligned T * playout)
  6394. {
  6395. uint funcIndex = playout->SlotIndex;
  6396. FrameDisplay *frameDisplay = this->GetFrameDisplayForNestedFunc();
  6397. SetRegAllowStackVarEnableOnly(playout->Value,
  6398. StackScriptFunction::OP_NewStackScFunc(frameDisplay,
  6399. this->m_functionBody->GetNestedFuncReference(funcIndex),
  6400. this->GetStackNestedFunction(funcIndex)));
  6401. }
  6402. template <class T>
  6403. void InterpreterStackFrame::OP_NewInnerStackScFunc(const unaligned T * playout)
  6404. {
  6405. uint funcIndex = playout->SlotIndex;
  6406. FrameDisplay *frameDisplay = (FrameDisplay*)GetNonVarReg(playout->Instance);
  6407. SetRegAllowStackVarEnableOnly(playout->Value,
  6408. StackScriptFunction::OP_NewStackScFunc(frameDisplay,
  6409. this->m_functionBody->GetNestedFuncReference(funcIndex),
  6410. this->GetStackNestedFunction(funcIndex)));
  6411. }
  6412. template <class T>
  6413. void InterpreterStackFrame::OP_DeleteFld(const unaligned T * playout)
  6414. {
  6415. Var result = JavascriptOperators::OP_DeleteProperty(GetReg(playout->Instance), m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetScriptContext());
  6416. SetReg(playout->Value, result);
  6417. }
  6418. template <class T>
  6419. void InterpreterStackFrame::OP_DeleteLocalFld(const unaligned T * playout)
  6420. {
  6421. Var result = JavascriptOperators::OP_DeleteProperty(this->localClosure, m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetScriptContext());
  6422. SetReg(playout->Instance, result);
  6423. }
  6424. template <class T>
  6425. void InterpreterStackFrame::OP_DeleteRootFld(const unaligned T * playout)
  6426. {
  6427. Var result = JavascriptOperators::OP_DeleteRootProperty(GetReg(playout->Instance), m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetScriptContext());
  6428. SetReg(playout->Value, result);
  6429. }
  6430. template <class T>
  6431. void InterpreterStackFrame::OP_DeleteFldStrict(const unaligned T * playout)
  6432. {
  6433. Var result = JavascriptOperators::OP_DeleteProperty(GetReg(playout->Instance), m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetScriptContext(), PropertyOperation_StrictMode);
  6434. SetReg(playout->Value, result);
  6435. }
  6436. template <class T>
  6437. void InterpreterStackFrame::OP_DeleteRootFldStrict(const unaligned T * playout)
  6438. {
  6439. Var result = JavascriptOperators::OP_DeleteRootProperty(GetReg(playout->Instance), m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetScriptContext(), PropertyOperation_StrictMode);
  6440. SetReg(playout->Value, result);
  6441. }
  6442. template <typename T>
  6443. void InterpreterStackFrame::OP_ScopedDeleteFld(const unaligned OpLayoutT_ElementScopedC<T> * playout)
  6444. {
  6445. // Implicit root object as default instance
  6446. Var result = JavascriptOperators::OP_DeletePropertyScoped(GetEnvForEvalCode(),
  6447. m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex),
  6448. GetReg(Js::FunctionBody::RootObjectRegSlot), GetScriptContext());
  6449. SetReg(playout->Value, result);
  6450. }
  6451. template <typename T>
  6452. void InterpreterStackFrame::OP_ScopedDeleteFldStrict(const unaligned OpLayoutT_ElementScopedC<T> * playout)
  6453. {
  6454. // Implicit root object as default instance
  6455. Var result = JavascriptOperators::OP_DeletePropertyScoped(GetEnvForEvalCode(),
  6456. m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex),
  6457. GetReg(Js::FunctionBody::RootObjectRegSlot), GetScriptContext(), PropertyOperation_StrictMode);
  6458. SetReg(playout->Value, result);
  6459. }
  6460. template <class T>
  6461. void InterpreterStackFrame::OP_ScopedLdInst(const unaligned T * playout)
  6462. {
  6463. Var thisVar = nullptr;
  6464. Var rootObject = GetFunctionBody()->GetRootObject();
  6465. Var result = JavascriptOperators::OP_GetInstanceScoped(GetEnvForEvalCode(),
  6466. m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), rootObject, &thisVar, GetScriptContext());
  6467. SetReg(playout->Value, result);
  6468. SetReg(playout->Value2, thisVar);
  6469. }
  6470. template <typename T>
  6471. void InterpreterStackFrame::OP_ScopedInitFunc(const unaligned OpLayoutT_ElementScopedC<T> * playout)
  6472. {
  6473. JavascriptOperators::OP_InitFuncScoped(GetEnvForEvalCode(),
  6474. m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex),
  6475. GetReg(playout->Value), GetReg(Js::FunctionBody::RootObjectRegSlot), GetScriptContext());
  6476. }
  6477. template <class T>
  6478. void InterpreterStackFrame::OP_ClearAttributes(const unaligned T * playout)
  6479. {
  6480. JavascriptOperators::OP_ClearAttributes(GetReg(playout->Instance), m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex));
  6481. }
  6482. template <class T>
  6483. void InterpreterStackFrame::OP_InitGetFld(const unaligned T * playout)
  6484. {
  6485. JavascriptOperators::OP_InitGetter(GetReg(playout->Instance), m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetReg(playout->Value));
  6486. }
  6487. template <class T>
  6488. void InterpreterStackFrame::OP_InitSetFld(const unaligned T * playout)
  6489. {
  6490. JavascriptOperators::OP_InitSetter(GetReg(playout->Instance), m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetReg(playout->Value));
  6491. }
  6492. template <class T>
  6493. void InterpreterStackFrame::OP_InitSetElemI(const unaligned T * playout)
  6494. {
  6495. JavascriptOperators::OP_InitElemSetter(
  6496. GetReg(playout->Instance),
  6497. GetReg(playout->Element),
  6498. GetReg(playout->Value),
  6499. m_functionBody->GetScriptContext()
  6500. );
  6501. }
  6502. template <class T>
  6503. void InterpreterStackFrame::OP_InitGetElemI(const unaligned T * playout)
  6504. {
  6505. JavascriptOperators::OP_InitElemGetter(
  6506. GetReg(playout->Instance),
  6507. GetReg(playout->Element),
  6508. GetReg(playout->Value),
  6509. m_functionBody->GetScriptContext()
  6510. );
  6511. }
  6512. template <class T>
  6513. void InterpreterStackFrame::OP_InitComputedProperty(const unaligned T * playout)
  6514. {
  6515. JavascriptOperators::OP_InitComputedProperty(
  6516. GetReg(playout->Instance),
  6517. GetReg(playout->Element),
  6518. GetReg(playout->Value),
  6519. m_functionBody->GetScriptContext()
  6520. );
  6521. }
  6522. template <class T>
  6523. void InterpreterStackFrame::OP_InitProto(const unaligned T * playout)
  6524. {
  6525. JavascriptOperators::OP_InitProto(GetReg(playout->Instance), m_functionBody->GetReferencedPropertyId(playout->PropertyIdIndex), GetReg(playout->Value));
  6526. }
  6527. void InterpreterStackFrame::DoInterruptProbe()
  6528. {
  6529. PROBE_STACK(scriptContext, 0);
  6530. }
  6531. void InterpreterStackFrame::InitializeStackFunctions(StackScriptFunction * scriptFunctions)
  6532. {
  6533. this->stackNestedFunctions = scriptFunctions;
  6534. FunctionBody * functionBody = this->m_functionBody;
  6535. uint nestedCount = functionBody->GetNestedCount();
  6536. for (uint i = 0; i < nestedCount; i++)
  6537. {
  6538. StackScriptFunction * stackScriptFunction = scriptFunctions + i;
  6539. FunctionProxy* nestedProxy = functionBody->GetNestedFunctionProxy(i);
  6540. ScriptFunctionType* type = nestedProxy->EnsureDeferredPrototypeType();
  6541. new (stackScriptFunction)StackScriptFunction(nestedProxy, type);
  6542. }
  6543. }
  6544. StackScriptFunction * InterpreterStackFrame::GetStackNestedFunction(uint index)
  6545. {
  6546. Assert(index < this->m_functionBody->GetNestedCount());
  6547. // Re-check if we have disable stack nested function
  6548. if (this->m_functionBody->DoStackNestedFunc())
  6549. {
  6550. return this->stackNestedFunctions + index;
  6551. }
  6552. return nullptr;
  6553. }
  6554. void InterpreterStackFrame::SetExecutingStackFunction(ScriptFunction * scriptFunction)
  6555. {
  6556. Assert(ThreadContext::IsOnStack(this->function));
  6557. Assert(this->m_functionBody == scriptFunction->GetFunctionBody());
  6558. this->function = scriptFunction;
  6559. }
  6560. DWORD_PTR InterpreterStackFrame::GetStackAddress() const
  6561. {
  6562. return m_stackAddress;
  6563. }
  6564. void* InterpreterStackFrame::GetAddressOfReturnAddress() const
  6565. {
  6566. return this->addressOfReturnAddress;
  6567. }
  6568. template <class T>
  6569. const byte * InterpreterStackFrame::OP_Br(const unaligned T * playout)
  6570. {
  6571. return m_reader.SetCurrentRelativeOffset((const byte *)(playout + 1), playout->RelativeJumpOffset);
  6572. }
  6573. template <class T>
  6574. void InterpreterStackFrame::OP_InitClass(const unaligned OpLayoutT_Class<T> * playout)
  6575. {
  6576. JavascriptOperators::OP_InitClass(GetReg(playout->Constructor), playout->Extends != Js::Constants::NoRegister ? GetReg(playout->Extends) : NULL, GetScriptContext());
  6577. }
  6578. #ifdef ENABLE_SCRIPT_DEBUGGING
  6579. template <class T>
  6580. void InterpreterStackFrame::OP_EmitTmpRegCount(const unaligned OpLayoutT_Unsigned1<T> * playout)
  6581. {
  6582. this->scriptContext->GetDebugContext()->GetProbeContainer()->SetCurrentTmpRegCount(playout->C1);
  6583. }
  6584. #endif
  6585. Var InterpreterStackFrame::OP_LdHomeObj(ScriptContext * scriptContext)
  6586. {
  6587. return JavascriptOperators::OP_LdHomeObj(function, scriptContext);
  6588. }
  6589. Var InterpreterStackFrame::OP_LdFuncObj(ScriptContext * scriptContext)
  6590. {
  6591. return JavascriptOperators::OP_LdFuncObj(function, scriptContext);
  6592. }
  6593. Var InterpreterStackFrame::OP_ImportCall(Var specifier, ScriptContext *scriptContext)
  6594. {
  6595. return JavascriptOperators::OP_ImportCall(function, specifier, scriptContext);
  6596. }
  6597. void InterpreterStackFrame::ValidateRegValue(Var value, bool allowStackVar, bool allowStackVarOnDisabledStackNestedFunc) const
  6598. {
  6599. #if DBG
  6600. if (value != nullptr && !TaggedNumber::Is(value))
  6601. {
  6602. if (!allowStackVar || !this->m_functionBody->DoStackNestedFunc())
  6603. {
  6604. Assert(!ThreadContext::IsOnStack(value)
  6605. || (allowStackVar && allowStackVarOnDisabledStackNestedFunc && StackScriptFunction::IsBoxed(value)));
  6606. }
  6607. Assert(!CrossSite::NeedMarshalVar(value, GetScriptContext()));
  6608. }
  6609. #endif
  6610. }
  6611. template <typename RegSlotType>
  6612. Var InterpreterStackFrame::GetReg(RegSlotType localRegisterID) const
  6613. {
  6614. Var value = m_localSlots[localRegisterID];
  6615. ValidateRegValue(value);
  6616. return value;
  6617. }
  6618. template <typename RegSlotType>
  6619. void InterpreterStackFrame::SetReg(RegSlotType localRegisterID, Var value)
  6620. {
  6621. Assert(localRegisterID == 0 || localRegisterID >= m_functionBody->GetConstantCount());
  6622. ValidateRegValue(value);
  6623. m_localSlots[localRegisterID] = value;
  6624. #if ENABLE_OBJECT_SOURCE_TRACKING
  6625. if(value != nullptr && DynamicType::Is(Js::JavascriptOperators::GetTypeId(value)))
  6626. {
  6627. static_cast<DynamicObject*>(value)->SetDiagOriginInfoAsNeeded();
  6628. }
  6629. #endif
  6630. #if ENABLE_VALUE_TRACE
  6631. if(this->function->GetScriptContext()->ShouldPerformRecordOrReplayAction())
  6632. {
  6633. this->function->GetScriptContext()->GetThreadContext()->TTDExecutionInfo->GetTraceLogger()->WriteTraceValue(value);
  6634. }
  6635. #endif
  6636. }
  6637. template <typename T>
  6638. T InterpreterStackFrame::GetRegRaw(RegSlot localRegisterID) const
  6639. {
  6640. return (T)m_localIntSlots[localRegisterID];
  6641. }
  6642. // specialized version for doubles
  6643. template <>
  6644. double VECTORCALL InterpreterStackFrame::GetRegRaw(RegSlot localRegisterID) const
  6645. {
  6646. return (double)m_localDoubleSlots[localRegisterID];
  6647. }
  6648. template <>
  6649. float VECTORCALL InterpreterStackFrame::GetRegRaw(RegSlot localRegisterID) const
  6650. {
  6651. return (float)m_localFloatSlots[localRegisterID];
  6652. }
  6653. template <>
  6654. int64 InterpreterStackFrame::GetRegRaw(RegSlot localRegisterID) const
  6655. {
  6656. return m_localInt64Slots[localRegisterID];
  6657. }
  6658. template <typename T>
  6659. void InterpreterStackFrame::SetRegRaw(RegSlot localRegisterID, T bValue)
  6660. {
  6661. m_localIntSlots[localRegisterID] = (int)bValue;
  6662. }
  6663. template <>
  6664. void InterpreterStackFrame::SetRegRaw(RegSlot localRegisterID, float bValue)
  6665. {
  6666. m_localFloatSlots[localRegisterID] = (float)bValue;
  6667. }
  6668. template <>
  6669. void InterpreterStackFrame::SetRegRaw(RegSlot localRegisterID, double bValue)
  6670. {
  6671. m_localDoubleSlots[localRegisterID] = bValue;
  6672. }
  6673. template <>
  6674. void InterpreterStackFrame::SetRegRaw(RegSlot localRegisterID, int64 bValue)
  6675. {
  6676. m_localInt64Slots[localRegisterID] = bValue;
  6677. }
  6678. template <typename RegSlotType>
  6679. int InterpreterStackFrame::GetRegRawInt(RegSlotType localRegisterID) const
  6680. {
  6681. return m_localIntSlots[localRegisterID];
  6682. }
  6683. template <typename RegSlotType>
  6684. double InterpreterStackFrame::GetRegRawDouble(RegSlotType localRegisterID) const
  6685. {
  6686. return m_localDoubleSlots[localRegisterID];
  6687. }
  6688. template <typename RegSlotType>
  6689. float InterpreterStackFrame::GetRegRawFloat(RegSlotType localRegisterID) const
  6690. {
  6691. return m_localFloatSlots[localRegisterID];
  6692. }
  6693. template <typename RegSlotType>
  6694. void InterpreterStackFrame::SetRegRawInt(RegSlotType localRegisterID, int bValue)
  6695. {
  6696. m_localIntSlots[localRegisterID] = bValue;
  6697. }
  6698. template <typename RegSlotType>
  6699. int64 InterpreterStackFrame::GetRegRawInt64(RegSlotType localRegisterID) const
  6700. {
  6701. return m_localInt64Slots[localRegisterID];
  6702. }
  6703. template <typename RegSlotType>
  6704. void* InterpreterStackFrame::GetRegRawPtr(RegSlotType localRegisterID) const
  6705. {
  6706. #if TARGET_32
  6707. return (void*)m_localIntSlots[localRegisterID];
  6708. #elif TARGET_64
  6709. return (void*)m_localInt64Slots[localRegisterID];
  6710. #endif
  6711. }
  6712. template <typename RegSlotType>
  6713. void InterpreterStackFrame::SetRegRawPtr(RegSlotType localRegisterID, void* val)
  6714. {
  6715. #if TARGET_32
  6716. m_localIntSlots[localRegisterID] = (int32)val;
  6717. #elif TARGET_64
  6718. m_localInt64Slots[localRegisterID] = (int64)val;
  6719. #endif
  6720. }
  6721. template <typename RegSlotType>
  6722. void InterpreterStackFrame::SetRegRawInt64(RegSlotType localRegisterID, int64 bValue)
  6723. {
  6724. m_localInt64Slots[localRegisterID] = bValue;
  6725. }
  6726. template <typename RegSlotType>
  6727. void InterpreterStackFrame::SetRegRawDouble(RegSlotType localRegisterID, double bValue)
  6728. {
  6729. m_localDoubleSlots[localRegisterID] = bValue;
  6730. }
  6731. template <typename RegSlotType>
  6732. void InterpreterStackFrame::SetRegRawFloat(RegSlotType localRegisterID, float bValue)
  6733. {
  6734. m_localFloatSlots[localRegisterID] = bValue;
  6735. }
  6736. template <typename RegSlotType>
  6737. Var InterpreterStackFrame::GetRegAllowStackVar(RegSlotType localRegisterID) const
  6738. {
  6739. Var value = m_localSlots[localRegisterID];
  6740. ValidateRegValue(value, true);
  6741. return value;
  6742. }
  6743. template <typename RegSlotType>
  6744. void InterpreterStackFrame::SetRegAllowStackVar(RegSlotType localRegisterID, Var value)
  6745. {
  6746. Assert(localRegisterID == 0 || localRegisterID >= m_functionBody->GetConstantCount());
  6747. ValidateRegValue(value, true);
  6748. m_localSlots[localRegisterID] = value;
  6749. #if ENABLE_OBJECT_SOURCE_TRACKING
  6750. if(value != nullptr && DynamicType::Is(Js::JavascriptOperators::GetTypeId(value)))
  6751. {
  6752. static_cast<DynamicObject*>(value)->SetDiagOriginInfoAsNeeded();
  6753. }
  6754. #endif
  6755. #if ENABLE_VALUE_TRACE
  6756. if(this->function->GetScriptContext()->ShouldPerformRecordOrReplayAction())
  6757. {
  6758. this->function->GetScriptContext()->GetThreadContext()->TTDExecutionInfo->GetTraceLogger()->WriteTraceValue(value);
  6759. }
  6760. #endif
  6761. }
  6762. template <typename RegSlotType>
  6763. Var InterpreterStackFrame::GetRegAllowStackVarEnableOnly(RegSlotType localRegisterID) const
  6764. {
  6765. Var value = m_localSlots[localRegisterID];
  6766. ValidateRegValue(value, true, false);
  6767. return value;
  6768. }
  6769. template <typename RegSlotType>
  6770. void InterpreterStackFrame::SetRegAllowStackVarEnableOnly(RegSlotType localRegisterID, Var value)
  6771. {
  6772. Assert(localRegisterID == 0 || localRegisterID >= m_functionBody->GetConstantCount());
  6773. ValidateRegValue(value, true, false);
  6774. m_localSlots[localRegisterID] = value;
  6775. #if ENABLE_OBJECT_SOURCE_TRACKING
  6776. if(value != nullptr && DynamicType::Is(Js::JavascriptOperators::GetTypeId(value)))
  6777. {
  6778. static_cast<DynamicObject*>(value)->SetDiagOriginInfoAsNeeded();
  6779. }
  6780. #endif
  6781. #if ENABLE_VALUE_TRACE
  6782. if(this->function->GetScriptContext()->ShouldPerformRecordOrReplayAction())
  6783. {
  6784. this->function->GetScriptContext()->GetThreadContext()->TTDExecutionInfo->GetTraceLogger()->WriteTraceValue(value);
  6785. }
  6786. #endif
  6787. }
  6788. template <>
  6789. AsmJsSIMDValue InterpreterStackFrame::GetRegRaw(RegSlot localRegisterID) const
  6790. {
  6791. return (AsmJsSIMDValue)m_localSimdSlots[localRegisterID];
  6792. }
  6793. template<>
  6794. void InterpreterStackFrame::SetRegRaw(RegSlot localRegisterID, AsmJsSIMDValue bValue)
  6795. {
  6796. m_localSimdSlots[localRegisterID] = bValue;
  6797. }
  6798. template <typename RegSlotType>
  6799. AsmJsSIMDValue InterpreterStackFrame::GetRegRawSimd(RegSlotType localRegisterID) const
  6800. {
  6801. return m_localSimdSlots[localRegisterID];
  6802. }
  6803. template <typename RegSlotType>
  6804. void InterpreterStackFrame::SetRegRawSimd(RegSlotType localRegisterID, AsmJsSIMDValue bValue)
  6805. {
  6806. m_localSimdSlots[localRegisterID] = bValue;
  6807. }
  6808. int InterpreterStackFrame::OP_GetMemorySize()
  6809. {
  6810. #ifdef ENABLE_WASM
  6811. return (int)GetWebAssemblyMemory()->GetCurrentMemoryPages();
  6812. #else
  6813. Assert(UNREACHED);
  6814. return 0;
  6815. #endif
  6816. }
  6817. int InterpreterStackFrame::OP_GrowMemory(int32 delta)
  6818. {
  6819. #ifdef ENABLE_WASM
  6820. return GetWebAssemblyMemory()->GrowInternal((uint32)delta);
  6821. #else
  6822. Assert(UNREACHED);
  6823. return 0;
  6824. #endif
  6825. }
  6826. template <typename T, InterpreterStackFrame::AsmJsMathPtr<T> func> T InterpreterStackFrame::OP_UnsignedDivRemCheck(T aLeft, T aRight, ScriptContext* scriptContext)
  6827. {
  6828. if (aRight == 0)
  6829. {
  6830. JavascriptError::ThrowWebAssemblyRuntimeError(scriptContext, WASMERR_DivideByZero);
  6831. }
  6832. return func(aLeft, aRight);
  6833. }
  6834. template <typename T, InterpreterStackFrame::AsmJsMathPtr<T> func> T InterpreterStackFrame::OP_DivOverflow(T aLeft, T aRight, ScriptContext* scriptContext)
  6835. {
  6836. if (aRight == 0)
  6837. {
  6838. JavascriptError::ThrowWebAssemblyRuntimeError(scriptContext, WASMERR_DivideByZero);
  6839. }
  6840. if (aLeft == SignedTypeTraits<T>::MinValue && aRight == -1)
  6841. {
  6842. JavascriptError::ThrowWebAssemblyRuntimeError(scriptContext, VBSERR_Overflow);
  6843. }
  6844. return func(aLeft, aRight);
  6845. }
  6846. template <typename T, InterpreterStackFrame::AsmJsMathPtr<T> func> T InterpreterStackFrame::OP_RemOverflow(T aLeft, T aRight, ScriptContext* scriptContext)
  6847. {
  6848. if (aRight == 0)
  6849. {
  6850. JavascriptError::ThrowWebAssemblyRuntimeError(scriptContext, WASMERR_DivideByZero);
  6851. }
  6852. if (aLeft == SignedTypeTraits<T>::MinValue && aRight == -1)
  6853. {
  6854. return 0;
  6855. }
  6856. return func(aLeft, aRight);
  6857. }
  6858. void InterpreterStackFrame::OP_Unreachable()
  6859. {
  6860. JavascriptError::ThrowUnreachable(scriptContext);
  6861. }
  6862. template <class T>
  6863. void InterpreterStackFrame::OP_SimdLdArrGeneric(const unaligned T* playout)
  6864. {
  6865. Assert(playout->ViewType < Js::ArrayBufferView::TYPE_COUNT);
  6866. const uint64 index = ((uint64)(uint32)GetRegRawInt(playout->SlotIndex) + playout->Offset /* WASM only */) & (int64)(int)ArrayBufferView::ViewMask[playout->ViewType];
  6867. ArrayBufferBase* arr =
  6868. #ifdef ENABLE_WASM_SIMD
  6869. (m_functionBody->IsWasmFunction()) ?
  6870. m_wasmMemory->GetBuffer() :
  6871. #endif
  6872. GetAsmJsBuffer();
  6873. BYTE* buffer = arr->GetBuffer();
  6874. uint8 dataWidth = playout->DataWidth;
  6875. RegSlot dstReg = playout->Value;
  6876. if (index + dataWidth > arr->GetByteLength())
  6877. {
  6878. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgumentOutOfRange, _u("Simd typed array access"));
  6879. }
  6880. AsmJsSIMDValue *data = (AsmJsSIMDValue*)(buffer + index);
  6881. AsmJsSIMDValue value;
  6882. value = SIMDUtils::SIMDLdData(data, dataWidth);
  6883. SetRegRawSimd(dstReg, value);
  6884. }
  6885. template <class T>
  6886. void InterpreterStackFrame::OP_SimdLdArrConstIndex(const unaligned T* playout)
  6887. {
  6888. Assert(playout->ViewType < Js::ArrayBufferView::TYPE_COUNT);
  6889. const uint64 index = (uint32)playout->SlotIndex;
  6890. JavascriptArrayBuffer* arr = GetAsmJsBuffer();
  6891. BYTE* buffer = arr->GetBuffer();
  6892. uint8 dataWidth = playout->DataWidth;
  6893. RegSlot dstReg = playout->Value;
  6894. if (index + dataWidth > arr->GetByteLength())
  6895. {
  6896. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgumentOutOfRange, _u("Simd typed array access"));
  6897. }
  6898. AsmJsSIMDValue *data = (AsmJsSIMDValue*)(buffer + index);
  6899. AsmJsSIMDValue value;
  6900. value = SIMDUtils::SIMDLdData(data, dataWidth);
  6901. SetRegRawSimd(dstReg, value);
  6902. }
  6903. template <class T>
  6904. void InterpreterStackFrame::OP_SimdStArrGeneric(const unaligned T* playout)
  6905. {
  6906. Assert(playout->ViewType < Js::ArrayBufferView::TYPE_COUNT);
  6907. const uint64 index = ((uint64)(uint32)GetRegRawInt(playout->SlotIndex) + playout->Offset /* WASM only */) & (int64)(int)ArrayBufferView::ViewMask[playout->ViewType];
  6908. ArrayBufferBase* arr =
  6909. #ifdef ENABLE_WASM_SIMD
  6910. (m_functionBody->IsWasmFunction()) ?
  6911. m_wasmMemory->GetBuffer() :
  6912. #endif
  6913. GetAsmJsBuffer();
  6914. BYTE* buffer = arr->GetBuffer();
  6915. uint8 dataWidth = playout->DataWidth;
  6916. RegSlot srcReg = playout->Value;
  6917. if (index + dataWidth > arr->GetByteLength())
  6918. {
  6919. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgumentOutOfRange, _u("Simd typed array access"));
  6920. }
  6921. AsmJsSIMDValue *data = (AsmJsSIMDValue*)(buffer + index);
  6922. AsmJsSIMDValue value = GetRegRawSimd(srcReg);
  6923. SIMDUtils::SIMDStData(data, value, dataWidth);
  6924. }
  6925. template <class T>
  6926. void InterpreterStackFrame::OP_SimdStArrConstIndex(const unaligned T* playout)
  6927. {
  6928. Assert(playout->ViewType < Js::ArrayBufferView::TYPE_COUNT);
  6929. const uint64 index = (uint32)playout->SlotIndex;
  6930. JavascriptArrayBuffer* arr = GetAsmJsBuffer();
  6931. BYTE* buffer = arr->GetBuffer();
  6932. uint8 dataWidth = playout->DataWidth;
  6933. RegSlot srcReg = playout->Value;
  6934. if (index + dataWidth > arr->GetByteLength())
  6935. {
  6936. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgumentOutOfRange, _u("Simd typed array access"));
  6937. }
  6938. AsmJsSIMDValue *data = (AsmJsSIMDValue*)(buffer + index);
  6939. AsmJsSIMDValue value = GetRegRawSimd(srcReg);
  6940. SIMDUtils::SIMDStData(data, value, dataWidth);
  6941. }
  6942. bool InterpreterStackFrame::SIMDAnyNaN(AsmJsSIMDValue& input)
  6943. {
  6944. if (!GetFunctionBody()->IsWasmFunction())
  6945. {
  6946. return false;
  6947. }
  6948. AsmJsSIMDValue compResult = SIMDFloat32x4Operation::OpEqual(input, input);
  6949. return !SIMDBool32x4Operation::OpAllTrue(compResult);
  6950. }
  6951. // handler for SIMD.Int32x4.FromFloat32x4
  6952. template <class T>
  6953. void InterpreterStackFrame::OP_SimdInt32x4FromFloat32x4(const unaligned T* playout)
  6954. {
  6955. bool throws = false;
  6956. AsmJsSIMDValue input = GetRegRawSimd(playout->F4_1);
  6957. AsmJsSIMDValue result{ 0 };
  6958. #ifdef ENABLE_WASM_SIMD
  6959. throws = SIMDAnyNaN(input);
  6960. if (!throws)
  6961. #endif
  6962. {
  6963. result = SIMDInt32x4Operation::OpFromFloat32x4(input, throws);
  6964. }
  6965. // value is out of bound
  6966. if (throws)
  6967. {
  6968. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgumentOutOfRange, _u("SIMD.Int32x4.FromFloat32x4"));
  6969. }
  6970. SetRegRawSimd(playout->I4_0, result);
  6971. }
  6972. // handler for SIMD.Uint32x4.FromFloat32x4
  6973. template <class T>
  6974. void InterpreterStackFrame::OP_SimdUint32x4FromFloat32x4(const unaligned T* playout)
  6975. {
  6976. bool throws = false;
  6977. AsmJsSIMDValue input = GetRegRawSimd(playout->F4_1);
  6978. AsmJsSIMDValue result{ 0 };
  6979. #ifdef ENABLE_WASM_SIMD
  6980. throws = SIMDAnyNaN(input);
  6981. if (!throws)
  6982. #endif
  6983. {
  6984. result = SIMDUint32x4Operation::OpFromFloat32x4(input, throws);
  6985. }
  6986. if (throws)
  6987. {
  6988. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgumentOutOfRange, _u("SIMD.Int32x4.FromFloat32x4"));
  6989. }
  6990. SetRegRawSimd(playout->U4_0, result);
  6991. }
  6992. template <class T>
  6993. void InterpreterStackFrame::OP_WasmSimdConst(const unaligned T* playout)
  6994. {
  6995. AsmJsSIMDValue result{ playout->C1, playout->C2, playout->C3, playout->C4 };
  6996. SetRegRawSimd(playout->F4_0, result);
  6997. }
  6998. template <class T>
  6999. void InterpreterStackFrame::OP_SimdShuffleV8X16(const unaligned T* playout)
  7000. {
  7001. uint32 lanes[Wasm::Simd::MAX_LANES];
  7002. for (uint32 i = 0; i < Wasm::Simd::MAX_LANES; i++)
  7003. {
  7004. Assert(playout->INDICES[i] < Wasm::Simd::MAX_LANES * 2);
  7005. lanes[i] = playout->INDICES[i];
  7006. }
  7007. SetRegRawSimd(playout->R0, SIMDUtils::SIMD128InnerShuffle(GetRegRawSimd(playout->R1), GetRegRawSimd(playout->R2), Wasm::Simd::MAX_LANES, lanes));
  7008. }
  7009. template <class T>
  7010. void InterpreterStackFrame::OP_SimdInt16x8(const unaligned T* playout)
  7011. {
  7012. int16 values[8];
  7013. values[0] = (int16) GetRegRawInt(playout->I1);
  7014. values[1] = (int16) GetRegRawInt(playout->I2);
  7015. values[2] = (int16) GetRegRawInt(playout->I3);
  7016. values[3] = (int16) GetRegRawInt(playout->I4);
  7017. values[4] = (int16) GetRegRawInt(playout->I5);
  7018. values[5] = (int16) GetRegRawInt(playout->I6);
  7019. values[6] = (int16) GetRegRawInt(playout->I7);
  7020. values[7] = (int16) GetRegRawInt(playout->I8);
  7021. AsmJsSIMDValue result = SIMDInt16x8Operation::OpInt16x8(values);
  7022. SetRegRawSimd(playout->I8_0, result);
  7023. }
  7024. template <class T>
  7025. void InterpreterStackFrame::OP_SimdInt8x16(const unaligned T* playout)
  7026. {
  7027. int8 values[16];
  7028. values[0] = (int8)GetRegRawInt(playout->I1);
  7029. values[1] = (int8)GetRegRawInt(playout->I2);
  7030. values[2] = (int8)GetRegRawInt(playout->I3);
  7031. values[3] = (int8)GetRegRawInt(playout->I4);
  7032. values[4] = (int8)GetRegRawInt(playout->I5);
  7033. values[5] = (int8)GetRegRawInt(playout->I6);
  7034. values[6] = (int8)GetRegRawInt(playout->I7);
  7035. values[7] = (int8)GetRegRawInt(playout->I8);
  7036. values[8] = (int8)GetRegRawInt(playout->I9);
  7037. values[9] = (int8)GetRegRawInt(playout->I10);
  7038. values[10] = (int8)GetRegRawInt(playout->I11);
  7039. values[11] = (int8)GetRegRawInt(playout->I12);
  7040. values[12] = (int8)GetRegRawInt(playout->I13);
  7041. values[13] = (int8)GetRegRawInt(playout->I14);
  7042. values[14] = (int8)GetRegRawInt(playout->I15);
  7043. values[15] = (int8)GetRegRawInt(playout->I16);
  7044. AsmJsSIMDValue result = SIMDInt8x16Operation::OpInt8x16(values);
  7045. SetRegRawSimd(playout->I16_0, result);
  7046. }
  7047. template <class T>
  7048. void InterpreterStackFrame::OP_SimdUint16x8(const unaligned T* playout)
  7049. {
  7050. uint16 values[8];
  7051. values[0] = (uint16) GetRegRawInt(playout->I1);
  7052. values[1] = (uint16) GetRegRawInt(playout->I2);
  7053. values[2] = (uint16) GetRegRawInt(playout->I3);
  7054. values[3] = (uint16) GetRegRawInt(playout->I4);
  7055. values[4] = (uint16) GetRegRawInt(playout->I5);
  7056. values[5] = (uint16) GetRegRawInt(playout->I6);
  7057. values[6] = (uint16) GetRegRawInt(playout->I7);
  7058. values[7] = (uint16) GetRegRawInt(playout->I8);
  7059. AsmJsSIMDValue result = SIMDUint16x8Operation::OpUint16x8(values);
  7060. SetRegRawSimd(playout->U8_0, result);
  7061. }
  7062. template <class T>
  7063. void InterpreterStackFrame::OP_SimdUint8x16(const unaligned T* playout)
  7064. {
  7065. uint8 values[16];
  7066. values[0] = (uint8) GetRegRawInt(playout->I1);
  7067. values[1] = (uint8) GetRegRawInt(playout->I2);
  7068. values[2] = (uint8) GetRegRawInt(playout->I3);
  7069. values[3] = (uint8) GetRegRawInt(playout->I4);
  7070. values[4] = (uint8) GetRegRawInt(playout->I5);
  7071. values[5] = (uint8) GetRegRawInt(playout->I6);
  7072. values[6] = (uint8) GetRegRawInt(playout->I7);
  7073. values[7] = (uint8) GetRegRawInt(playout->I8);
  7074. values[8] = (uint8) GetRegRawInt(playout->I9);
  7075. values[9] = (uint8) GetRegRawInt(playout->I10);
  7076. values[10] = (uint8) GetRegRawInt(playout->I11);
  7077. values[11] = (uint8) GetRegRawInt(playout->I12);
  7078. values[12] = (uint8) GetRegRawInt(playout->I13);
  7079. values[13] = (uint8) GetRegRawInt(playout->I14);
  7080. values[14] = (uint8) GetRegRawInt(playout->I15);
  7081. values[15] = (uint8) GetRegRawInt(playout->I16);
  7082. AsmJsSIMDValue result = SIMDUint8x16Operation::OpUint8x16(values);
  7083. SetRegRawSimd(playout->U16_0, result);
  7084. }
  7085. // Bool constructors
  7086. template <class T>
  7087. void InterpreterStackFrame::OP_SimdBool32x4(const unaligned T* playout)
  7088. {
  7089. bool arg1 = GetRegRawInt(playout->I1) ? true : false;
  7090. bool arg2 = GetRegRawInt(playout->I2) ? true : false;
  7091. bool arg3 = GetRegRawInt(playout->I3) ? true : false;
  7092. bool arg4 = GetRegRawInt(playout->I4) ? true : false;
  7093. AsmJsSIMDValue result = SIMDBool32x4Operation::OpBool32x4(arg1, arg2, arg3, arg4);
  7094. SetRegRawSimd(playout->B4_0, result);
  7095. }
  7096. template <class T>
  7097. void InterpreterStackFrame::OP_SimdBool16x8(const unaligned T* playout)
  7098. {
  7099. bool values[8];
  7100. values[0] = GetRegRawInt(playout->I1) ? true : false;
  7101. values[1] = GetRegRawInt(playout->I2) ? true : false;
  7102. values[2] = GetRegRawInt(playout->I3) ? true : false;
  7103. values[3] = GetRegRawInt(playout->I4) ? true : false;
  7104. values[4] = GetRegRawInt(playout->I5) ? true : false;
  7105. values[5] = GetRegRawInt(playout->I6) ? true : false;
  7106. values[6] = GetRegRawInt(playout->I7) ? true : false;
  7107. values[7] = GetRegRawInt(playout->I8) ? true : false;
  7108. AsmJsSIMDValue result = SIMDBool16x8Operation::OpBool16x8(values);
  7109. SetRegRawSimd(playout->B8_0, result);
  7110. }
  7111. template <class T>
  7112. void InterpreterStackFrame::OP_SimdBool8x16(const unaligned T* playout)
  7113. {
  7114. bool values[16];
  7115. values[0] = GetRegRawInt(playout->I1) ? true : false;
  7116. values[1] = GetRegRawInt(playout->I2) ? true : false;
  7117. values[2] = GetRegRawInt(playout->I3) ? true : false;
  7118. values[3] = GetRegRawInt(playout->I4) ? true : false;
  7119. values[4] = GetRegRawInt(playout->I5) ? true : false;
  7120. values[5] = GetRegRawInt(playout->I6) ? true : false;
  7121. values[6] = GetRegRawInt(playout->I7) ? true : false;
  7122. values[7] = GetRegRawInt(playout->I8) ? true : false;
  7123. values[8] = GetRegRawInt(playout->I9) ? true : false;
  7124. values[9] = GetRegRawInt(playout->I10) ? true : false;
  7125. values[10] = GetRegRawInt(playout->I11) ? true : false;
  7126. values[11] = GetRegRawInt(playout->I12) ? true : false;
  7127. values[12] = GetRegRawInt(playout->I13) ? true : false;
  7128. values[13] = GetRegRawInt(playout->I14) ? true : false;
  7129. values[14] = GetRegRawInt(playout->I15) ? true : false;
  7130. values[15] = GetRegRawInt(playout->I16) ? true : false;
  7131. AsmJsSIMDValue result = SIMDBool8x16Operation::OpBool8x16(values);
  7132. SetRegRawSimd(playout->B16_0, result);
  7133. }
  7134. Var InterpreterStackFrame::GetNonVarReg(RegSlot localRegisterID) const
  7135. {
  7136. return m_localSlots[localRegisterID];
  7137. }
  7138. void InterpreterStackFrame::SetNonVarReg(RegSlot localRegisterID, Var aValue)
  7139. {
  7140. m_localSlots[localRegisterID] = aValue;
  7141. }
  7142. Var InterpreterStackFrame::GetRootObject() const
  7143. {
  7144. Assert(!this->GetFunctionBody()->IsJsBuiltInCode());
  7145. Var rootObject = GetReg(Js::FunctionBody::RootObjectRegSlot);
  7146. Assert(rootObject == this->GetFunctionBody()->LoadRootObject());
  7147. return rootObject;
  7148. }
  7149. Var InterpreterStackFrame::OP_ArgIn0()
  7150. {
  7151. return m_inParams[0];
  7152. }
  7153. #if ENABLE_PROFILE_INFO
  7154. template <class T>
  7155. void InterpreterStackFrame::OP_ProfiledArgOut_A(const unaligned T * playout)
  7156. {
  7157. FunctionBody* functionBody = this->m_functionBody;
  7158. DynamicProfileInfo * dynamicProfileInfo = functionBody->GetDynamicProfileInfo();
  7159. Assert(playout->Reg > FunctionBody::FirstRegSlot);
  7160. Var value = GetReg(playout->Reg);
  7161. dynamicProfileInfo->RecordParameterAtCallSite(functionBody, playout->profileId, value, playout->Arg, playout->Reg);
  7162. SetOut(playout->Arg, value);
  7163. }
  7164. #endif
  7165. template <class T>
  7166. void InterpreterStackFrame::OP_ArgOut_A(const unaligned T * playout)
  7167. {
  7168. SetOut(playout->Arg, GetReg(playout->Reg));
  7169. }
  7170. #if DBG
  7171. template <class T>
  7172. void InterpreterStackFrame::OP_ArgOut_ANonVar(const unaligned T * playout)
  7173. {
  7174. SetOut(playout->Arg, GetNonVarReg(playout->Reg));
  7175. }
  7176. #endif
  7177. template <class T>
  7178. void InterpreterStackFrame::OP_ArgOut_Env(const unaligned T * playout)
  7179. {
  7180. Var argEnv;
  7181. if (this->m_functionBody->GetLocalFrameDisplayRegister() != Constants::NoRegister)
  7182. {
  7183. argEnv = this->GetLocalFrameDisplay();
  7184. }
  7185. else
  7186. {
  7187. argEnv = this->LdEnv();
  7188. }
  7189. SetOut(playout->Arg, argEnv);
  7190. }
  7191. BOOL InterpreterStackFrame::OP_BrFalse_A(Var aValue, ScriptContext* scriptContext)
  7192. {
  7193. return !JavascriptConversion::ToBoolean(aValue, scriptContext);
  7194. }
  7195. BOOL InterpreterStackFrame::OP_BrTrue_A(Var aValue, ScriptContext* scriptContext)
  7196. {
  7197. return JavascriptConversion::ToBoolean(aValue, scriptContext);
  7198. }
  7199. BOOL InterpreterStackFrame::OP_BrNotNull_A(Var aValue)
  7200. {
  7201. return aValue != NULL;
  7202. }
  7203. BOOL InterpreterStackFrame::OP_BrUndecl_A(Var aValue)
  7204. {
  7205. return this->scriptContext->GetLibrary()->IsUndeclBlockVar(aValue);
  7206. }
  7207. BOOL InterpreterStackFrame::OP_BrNotUndecl_A(Var aValue)
  7208. {
  7209. return !this->scriptContext->GetLibrary()->IsUndeclBlockVar(aValue);
  7210. }
  7211. BOOL InterpreterStackFrame::OP_BrOnHasProperty(Var argInstance, uint propertyIdIndex, ScriptContext* scriptContext)
  7212. {
  7213. return JavascriptOperators::OP_HasProperty(argInstance,
  7214. this->m_functionBody->GetReferencedPropertyId(propertyIdIndex), scriptContext);
  7215. }
  7216. BOOL InterpreterStackFrame::OP_BrOnNoProperty(Var argInstance, uint propertyIdIndex, ScriptContext* scriptContext)
  7217. {
  7218. return !JavascriptOperators::OP_HasProperty(argInstance,
  7219. this->m_functionBody->GetReferencedPropertyId(propertyIdIndex), scriptContext);
  7220. }
  7221. BOOL InterpreterStackFrame::OP_BrOnNoEnvProperty(Var envInstance, int32 slotIndex, uint propertyIdIndex, ScriptContext* scriptContext)
  7222. {
  7223. Var instance = OP_LdFrameDisplaySlot(envInstance, slotIndex);
  7224. return !JavascriptOperators::OP_HasProperty(instance,
  7225. this->m_functionBody->GetReferencedPropertyId(propertyIdIndex), scriptContext);
  7226. }
  7227. BOOL InterpreterStackFrame::OP_BrOnClassConstructor(Var aValue)
  7228. {
  7229. return JavascriptOperators::IsClassConstructor(aValue);
  7230. }
  7231. BOOL InterpreterStackFrame::OP_BrOnBaseConstructorKind(Var aValue)
  7232. {
  7233. return JavascriptOperators::IsBaseConstructorKind(aValue);
  7234. }
  7235. template<class T>
  7236. void InterpreterStackFrame::OP_LdLen(const unaligned T * const playout)
  7237. {
  7238. Assert(playout);
  7239. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  7240. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  7241. threadContext->ClearImplicitCallFlags();
  7242. Var instance = GetReg(playout->Instance);
  7243. Var length = JavascriptOperators::OP_GetLength(instance, GetScriptContext());
  7244. threadContext->CheckAndResetImplicitCallAccessorFlag();
  7245. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  7246. SetReg(playout->Value, length);
  7247. }
  7248. #if ENABLE_PROFILE_INFO
  7249. template<class T>
  7250. void InterpreterStackFrame::OP_ProfiledLdLen(const unaligned OpLayoutDynamicProfile<T> *const playout)
  7251. {
  7252. Assert(playout);
  7253. FunctionBody * functionBody = m_functionBody;
  7254. DynamicProfileInfo * profileData = functionBody->GetDynamicProfileInfo();
  7255. Var instance = GetReg(playout->Instance);
  7256. LdLenInfo ldLenInfo;
  7257. ldLenInfo.arrayType = ValueType::Uninitialized.Merge(instance);
  7258. if (this->TestFlags(InterpreterStackFrameFlags_ProcessingBailOutOnArraySpecialization))
  7259. {
  7260. ldLenInfo.disableAggressiveSpecialization = true;
  7261. this->ClearFlags(InterpreterStackFrameFlags_ProcessingBailOutOnArraySpecialization);
  7262. }
  7263. profileData->RecordLengthLoad(functionBody, playout->profileId, ldLenInfo);
  7264. ThreadContext* threadContext = this->GetScriptContext()->GetThreadContext();
  7265. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  7266. threadContext->ClearImplicitCallFlags();
  7267. PropertyId propertyId = GetPropertyIdFromCacheId(playout->inlineCacheIndex);
  7268. Var value = ProfilingHelpers::ProfiledLdFld<false, false, false>(
  7269. instance,
  7270. propertyId,
  7271. GetInlineCache(playout->inlineCacheIndex),
  7272. playout->inlineCacheIndex,
  7273. GetFunctionBody(),
  7274. instance);
  7275. SetReg(playout->Value, value);
  7276. threadContext->CheckAndResetImplicitCallAccessorFlag();
  7277. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  7278. }
  7279. #endif
  7280. JavascriptFunction* InterpreterStackFrame::GetFunctionExpression()
  7281. {
  7282. // Make sure we get the boxed function object if is there, (or the function itself)
  7283. return StackScriptFunction::GetCurrentFunctionObject(this->function->GetRealFunctionObject());
  7284. }
  7285. template <class T>
  7286. void InterpreterStackFrame::OP_LdFunctionExpression(const unaligned T * playout)
  7287. {
  7288. SetRegAllowStackVar(playout->R0, this->GetFunctionExpression());
  7289. }
  7290. template <class T>
  7291. void InterpreterStackFrame::OP_StFunctionExpression(const unaligned T * playout)
  7292. {
  7293. OP_StFunctionExpression(GetReg(playout->Instance), GetReg(playout->Value), playout->PropertyIdIndex);
  7294. }
  7295. template <class T>
  7296. void InterpreterStackFrame::OP_StLocalFunctionExpression(const unaligned T * playout)
  7297. {
  7298. OP_StFunctionExpression(this->localClosure, GetReg(playout->Instance), playout->PropertyIdIndex);
  7299. }
  7300. void InterpreterStackFrame::OP_StFunctionExpression(Var instance, Var value, PropertyIdIndexType index)
  7301. {
  7302. JavascriptOperators::OP_StFunctionExpression(instance,
  7303. this->m_functionBody->GetReferencedPropertyId(index), value);
  7304. }
  7305. template <class T>
  7306. void InterpreterStackFrame::OP_LdNewTarget(const unaligned T* playout)
  7307. {
  7308. if (Js::CallInfo::HasNewTarget(this->m_callFlags))
  7309. {
  7310. SetRegAllowStackVar(playout->R0, (Js::RecyclableObject*)Js::CallInfo::GetNewTarget(this->m_callFlags, this->m_inParams, (ArgSlot)this->m_inSlotsCount));
  7311. }
  7312. else if (this->m_callFlags & CallFlags_New)
  7313. {
  7314. SetRegAllowStackVar(playout->R0, this->GetFunctionExpression());
  7315. }
  7316. else
  7317. {
  7318. SetReg(playout->R0, this->GetScriptContext()->GetLibrary()->GetUndefined());
  7319. }
  7320. }
  7321. Var InterpreterStackFrame::OP_Ld_A(Var aValue)
  7322. {
  7323. return aValue;
  7324. }
  7325. Var InterpreterStackFrame::LdEnv() const
  7326. {
  7327. return this->function->GetEnvironment();
  7328. }
  7329. void InterpreterStackFrame::SetEnv(FrameDisplay *frameDisplay)
  7330. {
  7331. this->function->SetEnvironment(frameDisplay);
  7332. }
  7333. Var InterpreterStackFrame::OP_LdLocalObj()
  7334. {
  7335. if (!VirtualTableInfo<ActivationObject>::HasVirtualTable(this->localClosure) &&
  7336. !VirtualTableInfo<ActivationObjectEx>::HasVirtualTable(this->localClosure))
  7337. {
  7338. Js::Throw::FatalInternalError();
  7339. }
  7340. return this->localClosure;
  7341. }
  7342. Var InterpreterStackFrame::OP_LdParamObj()
  7343. {
  7344. if (!VirtualTableInfo<ActivationObject>::HasVirtualTable(this->paramClosure) &&
  7345. !VirtualTableInfo<ActivationObjectEx>::HasVirtualTable(this->paramClosure))
  7346. {
  7347. Js::Throw::FatalInternalError();
  7348. }
  7349. return this->paramClosure;
  7350. }
  7351. #ifdef ASMJS_PLAT
  7352. template <typename ArrayType, typename RegType>
  7353. void InterpreterStackFrame::OP_StArr(uint32 index, RegSlot regSlot)
  7354. {
  7355. JavascriptArrayBuffer* arr = GetAsmJsBuffer();
  7356. if (index < arr->GetByteLength())
  7357. {
  7358. BYTE* buffer = arr->GetBuffer();
  7359. *(ArrayType*)(buffer + index) = (ArrayType)GetRegRaw<RegType>(regSlot);
  7360. }
  7361. }
  7362. #endif
  7363. template<> inline double InterpreterStackFrame::GetArrayViewOverflowVal()
  7364. {
  7365. return *(double*)&NumberConstants::k_Nan;
  7366. }
  7367. template<> inline float InterpreterStackFrame::GetArrayViewOverflowVal()
  7368. {
  7369. return (float)*(double*)&NumberConstants::k_Nan;
  7370. }
  7371. template<typename T> T InterpreterStackFrame::GetArrayViewOverflowVal()
  7372. {
  7373. return 0;
  7374. }
  7375. template <class T>
  7376. void InterpreterStackFrame::OP_LdArrFunc(const unaligned T* playout)
  7377. {
  7378. Var* arr = (Var*)GetRegRawPtr(playout->Instance);
  7379. const uint32 index = (uint32)GetRegRawInt(playout->SlotIndex);
  7380. SetRegRawPtr(playout->Value, arr[index]);
  7381. }
  7382. template <class T>
  7383. void InterpreterStackFrame::OP_LdArrWasmFunc(const unaligned T* playout)
  7384. {
  7385. #ifdef ENABLE_WASM
  7386. WebAssemblyTable * table = WebAssemblyTable::FromVar(GetRegRawPtr(playout->Instance));
  7387. const uint32 index = (uint32)GetRegRawInt(playout->SlotIndex);
  7388. if (index >= table->GetCurrentLength())
  7389. {
  7390. JavascriptError::ThrowWebAssemblyRuntimeError(GetScriptContext(), WASMERR_TableIndexOutOfRange);
  7391. }
  7392. Var func = table->DirectGetValue(index);
  7393. if (!func)
  7394. {
  7395. JavascriptError::ThrowWebAssemblyRuntimeError(GetScriptContext(), WASMERR_NeedWebAssemblyFunc);
  7396. }
  7397. SetRegRawPtr(playout->Value, func);
  7398. #endif
  7399. }
  7400. template <class T>
  7401. void InterpreterStackFrame::OP_CheckSignature(const unaligned T* playout)
  7402. {
  7403. #ifdef ENABLE_WASM
  7404. ScriptFunction * func = ScriptFunction::FromVar(GetRegRawPtr(playout->R0));
  7405. int sigIndex = playout->C1;
  7406. Wasm::WasmSignature * expected = &m_signatures[sigIndex];
  7407. if (func->GetFunctionInfo()->IsDeferredParseFunction())
  7408. {
  7409. // TODO: should be able to assert this once imports are converted to wasm functions
  7410. JavascriptError::ThrowWebAssemblyRuntimeError(GetScriptContext(), WASMERR_NeedWebAssemblyFunc);
  7411. }
  7412. AsmJsFunctionInfo * asmInfo = func->GetFunctionBody()->GetAsmJsFunctionInfo();
  7413. if (!asmInfo)
  7414. {
  7415. // TODO: should be able to assert this once imports are converted to wasm functions
  7416. JavascriptError::ThrowWebAssemblyRuntimeError(GetScriptContext(), WASMERR_NeedWebAssemblyFunc);
  7417. }
  7418. if (!expected->IsEquivalent(asmInfo->GetWasmSignature()))
  7419. {
  7420. JavascriptError::ThrowWebAssemblyRuntimeError(GetScriptContext(), WASMERR_SignatureMismatch);
  7421. }
  7422. #endif
  7423. }
  7424. #ifdef ASMJS_PLAT
  7425. template <typename ArrayType, typename RegType>
  7426. void InterpreterStackFrame::OP_LdArr(uint32 index, RegSlot regSlot)
  7427. {
  7428. JavascriptArrayBuffer* arr = GetAsmJsBuffer();
  7429. BYTE* buffer = arr->GetBuffer();
  7430. ArrayType val = index < (arr->GetByteLength()) ? *(ArrayType*)(buffer + index) : GetArrayViewOverflowVal<ArrayType>();
  7431. SetRegRaw<RegType>(regSlot, (RegType)val);
  7432. }
  7433. #endif
  7434. template <class T, typename T2>
  7435. void InterpreterStackFrame::OP_StSlotPrimitive(const unaligned T* playout)
  7436. {
  7437. T2* buffer = (T2*)GetNonVarReg(playout->Instance);
  7438. buffer[playout->SlotIndex] = GetRegRaw<T2>(playout->Value);
  7439. }
  7440. template <class T>
  7441. void InterpreterStackFrame::OP_LdAsmJsSlot(const unaligned T* playout)
  7442. {
  7443. Var * slotArray = (Var*)GetNonVarReg(playout->Instance);
  7444. SetRegRawPtr(playout->Value, slotArray[playout->SlotIndex]);
  7445. }
  7446. template <class T, typename T2>
  7447. void InterpreterStackFrame::OP_LdSlotPrimitive(const unaligned T* playout)
  7448. {
  7449. T2* buffer = (T2*)GetNonVarReg(playout->Instance);
  7450. SetRegRaw<T2>(playout->Value, buffer[playout->SlotIndex]);
  7451. }
  7452. #ifndef TEMP_DISABLE_ASMJS
  7453. template <class T>
  7454. void InterpreterStackFrame::OP_LdArrGeneric(const unaligned T* playout)
  7455. {
  7456. const uint32 index = (uint32)GetRegRawInt(playout->SlotIndex);
  7457. switch (playout->ViewType)
  7458. {
  7459. #define ARRAYBUFFER_VIEW(name, align, RegType, MemType, ...) \
  7460. case ArrayBufferView::ViewType::TYPE_##name: \
  7461. OP_LdArr<MemType, RegType>(index & ARRAYBUFFER_VIEW_MASK(align), playout->Value); \
  7462. return;
  7463. #include "AsmJsArrayBufferViews.h"
  7464. default:Assert(UNREACHED);
  7465. }
  7466. }
  7467. template<typename MemType>
  7468. void InterpreterStackFrame::WasmArrayBoundsCheck(uint64 index, uint32 byteLength)
  7469. {
  7470. if (index + sizeof(MemType) > byteLength)
  7471. {
  7472. JavascriptError::ThrowWebAssemblyRuntimeError(scriptContext, WASMERR_ArrayIndexOutOfRange);
  7473. }
  7474. }
  7475. template<typename MemType>
  7476. MemType* InterpreterStackFrame::WasmAtomicsArrayBoundsCheck(byte* buffer, uint64 index, uint32 byteLength)
  7477. {
  7478. MemType* readBuffer = (MemType*)(buffer + index);
  7479. // Do alignment check to be coherent with the order the jit does the checks
  7480. if (!::Math::IsAligned<intptr_t>((intptr_t)readBuffer, sizeof(MemType)))
  7481. {
  7482. JavascriptError::ThrowWebAssemblyRuntimeError(scriptContext, WASMERR_UnalignedAtomicAccess);
  7483. }
  7484. WasmArrayBoundsCheck<MemType>(index, byteLength);
  7485. return readBuffer;
  7486. }
  7487. template <class T>
  7488. void InterpreterStackFrame::OP_LdArrWasm(const unaligned T* playout)
  7489. {
  7490. #ifdef ENABLE_WASM
  7491. Assert(playout->ViewType < Js::ArrayBufferView::TYPE_COUNT);
  7492. const uint64 index = playout->Offset + (uint64)(uint32)GetRegRawInt(playout->SlotIndex);
  7493. ArrayBufferBase* arr = GetWebAssemblyMemory()->GetBuffer();
  7494. uint32 byteLength = arr->GetByteLength();
  7495. BYTE* buffer = arr->GetBuffer();
  7496. switch (playout->ViewType)
  7497. {
  7498. #define ARRAYBUFFER_VIEW(name, align, RegType, MemType, ...) \
  7499. case ArrayBufferView::ViewType::TYPE_##name: \
  7500. WasmArrayBoundsCheck<MemType>(index, byteLength); \
  7501. SetRegRaw<RegType>(playout->Value, (RegType)*(MemType*)(buffer + index)); \
  7502. return;
  7503. #include "AsmJsArrayBufferViews.h"
  7504. default:Assert(UNREACHED);
  7505. }
  7506. #else
  7507. Assert(UNREACHED);
  7508. #endif
  7509. }
  7510. template <class T>
  7511. void InterpreterStackFrame::OP_LdArrAtomic(const unaligned T* playout)
  7512. {
  7513. #ifdef ENABLE_WASM
  7514. Assert(Wasm::Threads::IsEnabled());
  7515. Assert(playout->ViewType < Js::ArrayBufferView::TYPE_COUNT);
  7516. const uint64 index = playout->Offset + (uint64)(uint32)GetRegRawInt(playout->SlotIndex);
  7517. ArrayBufferBase* arr = GetWebAssemblyMemory()->GetBuffer();
  7518. uint32 byteLength = arr->GetByteLength();
  7519. BYTE* buffer = arr->GetBuffer();
  7520. switch (playout->ViewType)
  7521. {
  7522. #define ARRAYBUFFER_VIEW_INT(name, align, RegType, MemType, ...) \
  7523. case ArrayBufferView::ViewType::TYPE_##name: {\
  7524. MemType* readBuffer = WasmAtomicsArrayBoundsCheck<MemType>(buffer, index, byteLength); \
  7525. MemType value = AtomicsOperations::Load<MemType>(readBuffer); \
  7526. SetRegRaw<RegType>(playout->Value, (RegType)value); \
  7527. return; \
  7528. }
  7529. #include "AsmJsArrayBufferViews.h"
  7530. default:Assert(UNREACHED);
  7531. }
  7532. #else
  7533. Assert(UNREACHED);
  7534. #endif
  7535. }
  7536. template <class T>
  7537. void InterpreterStackFrame::OP_StArrAtomic(const unaligned T* playout)
  7538. {
  7539. #ifdef ENABLE_WASM
  7540. Assert(Wasm::Threads::IsEnabled());
  7541. Assert(playout->ViewType < Js::ArrayBufferView::TYPE_COUNT);
  7542. const uint64 index = playout->Offset + (uint64)(uint32)GetRegRawInt(playout->SlotIndex);
  7543. ArrayBufferBase* arr = GetWebAssemblyMemory()->GetBuffer();
  7544. uint32 byteLength = arr->GetByteLength();
  7545. BYTE* buffer = arr->GetBuffer();
  7546. switch (playout->ViewType)
  7547. {
  7548. #define ARRAYBUFFER_VIEW_INT(name, align, RegType, MemType, ...) \
  7549. case ArrayBufferView::ViewType::TYPE_##name: {\
  7550. MemType* readBuffer = WasmAtomicsArrayBoundsCheck<MemType>(buffer, index, byteLength); \
  7551. MemType value = (MemType)GetRegRaw<RegType>(playout->Value); \
  7552. MemType storedValue = AtomicsOperations::Store<MemType>(readBuffer, value); \
  7553. Assert(storedValue == value); \
  7554. return; \
  7555. }
  7556. #include "AsmJsArrayBufferViews.h"
  7557. default:Assert(UNREACHED);
  7558. }
  7559. #else
  7560. Assert(UNREACHED);
  7561. #endif
  7562. }
  7563. template <class T>
  7564. void InterpreterStackFrame::OP_LdArrConstIndex(const unaligned T* playout)
  7565. {
  7566. switch (playout->ViewType)
  7567. {
  7568. #define ARRAYBUFFER_VIEW(name, align, RegType, MemType, ...) \
  7569. case ArrayBufferView::ViewType::TYPE_##name: \
  7570. OP_LdArr<MemType, RegType>(playout->SlotIndex, playout->Value); \
  7571. return;
  7572. #include "AsmJsArrayBufferViews.h"
  7573. default:Assert(UNREACHED);
  7574. }
  7575. }
  7576. template <class T>
  7577. void InterpreterStackFrame::OP_StArrGeneric(const unaligned T* playout)
  7578. {
  7579. const uint32 index = (uint32)GetRegRawInt(playout->SlotIndex);
  7580. switch (playout->ViewType)
  7581. {
  7582. #define ARRAYBUFFER_VIEW(name, align, RegType, MemType, ...) \
  7583. case ArrayBufferView::ViewType::TYPE_##name: \
  7584. OP_StArr<MemType, RegType>(index & ARRAYBUFFER_VIEW_MASK(align), playout->Value); \
  7585. return;
  7586. #include "AsmJsArrayBufferViews.h"
  7587. default:Assert(UNREACHED);
  7588. }
  7589. }
  7590. template <class T>
  7591. void InterpreterStackFrame::OP_StArrWasm(const unaligned T* playout)
  7592. {
  7593. #ifdef ENABLE_WASM
  7594. Assert(playout->ViewType < Js::ArrayBufferView::TYPE_COUNT);
  7595. const uint64 index = playout->Offset + (uint64)(uint32)GetRegRawInt(playout->SlotIndex);
  7596. ArrayBufferBase* arr = GetWebAssemblyMemory()->GetBuffer();
  7597. uint32 byteLength = arr->GetByteLength();
  7598. BYTE* buffer = arr->GetBuffer();
  7599. switch (playout->ViewType)
  7600. {
  7601. #define ARRAYBUFFER_VIEW(name, align, RegType, MemType, ...) \
  7602. case ArrayBufferView::ViewType::TYPE_##name: \
  7603. WasmArrayBoundsCheck<MemType>(index, byteLength); \
  7604. *(MemType*)(buffer + index) = (MemType)(GetRegRaw<RegType>(playout->Value)); \
  7605. break;
  7606. #include "AsmJsArrayBufferViews.h"
  7607. default:Assert(UNREACHED);
  7608. }
  7609. CompileAssert(ArrayBufferView::ViewType::TYPE_COUNT == 15);
  7610. #if DBG
  7611. if (PHASE_TRACE(WasmMemWritesPhase, m_functionBody))
  7612. {
  7613. GetWebAssemblyMemory()->TraceMemWrite(GetWebAssemblyMemory(), (uint32)GetRegRawInt(playout->SlotIndex), playout->Offset, playout->ViewType, (uint32)(size_t)this->DEBUG_currentByteOffset, scriptContext);
  7614. }
  7615. #endif
  7616. return;
  7617. #else
  7618. Assert(UNREACHED);
  7619. #endif
  7620. }
  7621. template <class T>
  7622. void InterpreterStackFrame::OP_StArrConstIndex(const unaligned T* playout)
  7623. {
  7624. switch (playout->ViewType)
  7625. {
  7626. #define ARRAYBUFFER_VIEW(name, align, RegType, MemType, ...) \
  7627. case ArrayBufferView::ViewType::TYPE_##name: \
  7628. OP_StArr<MemType, RegType>(playout->SlotIndex, playout->Value); \
  7629. return;
  7630. #include "AsmJsArrayBufferViews.h"
  7631. default:Assert(UNREACHED);
  7632. }
  7633. }
  7634. #endif
  7635. Var InterpreterStackFrame::OP_LdSlot(Var instance, int32 slotIndex)
  7636. {
  7637. if (!PHASE_OFF(ClosureRangeCheckPhase, this->m_functionBody))
  7638. {
  7639. if ((uintptr_t)((Var*)instance)[ScopeSlots::EncodedSlotCountSlotIndex] <= (uintptr_t)(slotIndex - ScopeSlots::FirstSlotIndex))
  7640. {
  7641. Js::Throw::FatalInternalError();
  7642. }
  7643. }
  7644. return ((Var*)(instance))[slotIndex];
  7645. }
  7646. template <class T>
  7647. Var InterpreterStackFrame::OP_LdSlot(Var instance, const unaligned T* playout)
  7648. {
  7649. return OP_LdSlot(instance, playout->SlotIndex);
  7650. }
  7651. #if ENABLE_PROFILE_INFO
  7652. template <class T>
  7653. Var InterpreterStackFrame::OP_ProfiledLdSlot(Var instance, const unaligned T* playout)
  7654. {
  7655. Var value = OP_LdSlot(instance, playout->SlotIndex);
  7656. ProfilingHelpers::ProfileLdSlot(value, GetFunctionBody(), playout->profileId);
  7657. return value;
  7658. }
  7659. #endif
  7660. template <class T>
  7661. Var InterpreterStackFrame::OP_LdInnerSlot(Var slotArray, const unaligned T* playout)
  7662. {
  7663. return OP_LdSlot(slotArray, playout->SlotIndex2);
  7664. }
  7665. #if ENABLE_PROFILE_INFO
  7666. template <class T>
  7667. Var InterpreterStackFrame::OP_ProfiledLdInnerSlot(Var slotArray, const unaligned T* playout)
  7668. {
  7669. Var value = OP_LdInnerSlot(slotArray, playout);
  7670. ProfilingHelpers::ProfileLdSlot(value, GetFunctionBody(), playout->profileId);
  7671. return value;
  7672. }
  7673. #endif
  7674. template <class T>
  7675. Var InterpreterStackFrame::OP_LdInnerObjSlot(Var slotArray, const unaligned T* playout)
  7676. {
  7677. return OP_LdObjSlot(slotArray, playout->SlotIndex2);
  7678. }
  7679. #if ENABLE_PROFILE_INFO
  7680. template <class T>
  7681. Var InterpreterStackFrame::OP_ProfiledLdInnerObjSlot(Var slotArray, const unaligned T* playout)
  7682. {
  7683. Var value = OP_LdInnerObjSlot(slotArray, playout);
  7684. ProfilingHelpers::ProfileLdSlot(value, GetFunctionBody(), playout->profileId);
  7685. return value;
  7686. }
  7687. #endif
  7688. Var InterpreterStackFrame::OP_LdFrameDisplaySlot(Var instance, int32 slotIndex)
  7689. {
  7690. if (!PHASE_OFF(ClosureRangeCheckPhase, this->m_functionBody))
  7691. {
  7692. if (((FrameDisplay*)instance)->GetLength() <= slotIndex - Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Var))
  7693. {
  7694. Js::Throw::FatalInternalError();
  7695. }
  7696. }
  7697. return ((Var*)instance)[slotIndex];
  7698. }
  7699. template <class T>
  7700. Var InterpreterStackFrame::OP_LdEnvObj(Var instance, const unaligned T* playout)
  7701. {
  7702. return OP_LdFrameDisplaySlot(instance, playout->SlotIndex);
  7703. }
  7704. template <class T>
  7705. Var InterpreterStackFrame::OP_LdEnvSlot(Var instance, const unaligned T* playout)
  7706. {
  7707. Var slotArray = OP_LdFrameDisplaySlot(instance, playout->SlotIndex1);
  7708. return OP_LdSlot(slotArray, playout->SlotIndex2);
  7709. }
  7710. #if ENABLE_PROFILE_INFO
  7711. template <class T>
  7712. Var InterpreterStackFrame::OP_ProfiledLdEnvSlot(Var instance, const unaligned T* playout)
  7713. {
  7714. Var value = OP_LdEnvSlot(instance, playout);
  7715. ProfilingHelpers::ProfileLdSlot(value, GetFunctionBody(), playout->profileId);
  7716. return value;
  7717. }
  7718. #endif
  7719. Var InterpreterStackFrame::OP_LdObjSlot(Var instance, int32 slotIndex)
  7720. {
  7721. Var *slotArray = *(Var**)((char*)instance + DynamicObject::GetOffsetOfAuxSlots());
  7722. return slotArray[slotIndex];
  7723. }
  7724. template <class T>
  7725. Var InterpreterStackFrame::OP_LdObjSlot(Var instance, const unaligned T* playout)
  7726. {
  7727. return OP_LdObjSlot(instance, playout->SlotIndex);
  7728. }
  7729. #if ENABLE_PROFILE_INFO
  7730. template <class T>
  7731. Var InterpreterStackFrame::OP_ProfiledLdObjSlot(Var instance, const unaligned T* playout)
  7732. {
  7733. Var value = OP_LdObjSlot(instance, playout->SlotIndex);
  7734. ProfilingHelpers::ProfileLdSlot(value, GetFunctionBody(), playout->profileId);
  7735. return value;
  7736. }
  7737. #endif
  7738. template <class T>
  7739. Var InterpreterStackFrame::OP_LdEnvObjSlot(Var instance, const unaligned T* playout)
  7740. {
  7741. Var slotArray = OP_LdFrameDisplaySlot(instance, playout->SlotIndex1);
  7742. return OP_LdObjSlot(slotArray, playout->SlotIndex2);
  7743. }
  7744. template <class T>
  7745. Var InterpreterStackFrame::OP_LdModuleSlot(Var instance, const unaligned T* playout)
  7746. {
  7747. return JavascriptOperators::OP_LdModuleSlot(playout->SlotIndex1, playout->SlotIndex2, scriptContext);
  7748. }
  7749. inline void InterpreterStackFrame::OP_StModuleSlot(Var instance, uint32 slotIndex1, uint32 slotIndex2, Var value)
  7750. {
  7751. JavascriptOperators::OP_StModuleSlot(slotIndex1, slotIndex2, value, scriptContext);
  7752. }
  7753. #if ENABLE_PROFILE_INFO
  7754. template <class T>
  7755. Var InterpreterStackFrame::OP_ProfiledLdEnvObjSlot(Var instance, const unaligned T* playout)
  7756. {
  7757. Var value = OP_LdEnvObjSlot(instance, playout);
  7758. ProfilingHelpers::ProfileLdSlot(value, GetFunctionBody(), playout->profileId);
  7759. return value;
  7760. }
  7761. #endif
  7762. void InterpreterStackFrame::OP_StSlot(Var instance, int32 slotIndex, Var value)
  7763. {
  7764. // We emit OpCode::StSlot in the bytecode only for scope slot arrays, which are not recyclable objects.
  7765. if (!PHASE_OFF(ClosureRangeCheckPhase, this->m_functionBody))
  7766. {
  7767. if ((uintptr_t)((Var*)instance)[ScopeSlots::EncodedSlotCountSlotIndex] <= (uintptr_t)(slotIndex - ScopeSlots::FirstSlotIndex))
  7768. {
  7769. Js::Throw::FatalInternalError();
  7770. }
  7771. }
  7772. ((Field(Var)*)(instance))[slotIndex] = value;
  7773. }
  7774. void InterpreterStackFrame::OP_StEnvSlot(Var instance, int32 slotIndex1, int32 slotIndex2, Var value)
  7775. {
  7776. Var slotArray = (Var*)OP_LdFrameDisplaySlot(instance, slotIndex1);
  7777. OP_StSlot(slotArray, slotIndex2, value);
  7778. }
  7779. void InterpreterStackFrame::OP_StSlotChkUndecl(Var instance, int32 slotIndex, Var value)
  7780. {
  7781. // We emit OpCode::StSlot in the bytecode only for scope slot arrays, which are not recyclable objects.
  7782. if (!PHASE_OFF(ClosureRangeCheckPhase, this->m_functionBody))
  7783. {
  7784. if ((uintptr_t)((Var*)instance)[ScopeSlots::EncodedSlotCountSlotIndex] <= (uintptr_t)(slotIndex - ScopeSlots::FirstSlotIndex))
  7785. {
  7786. Js::Throw::FatalInternalError();
  7787. }
  7788. }
  7789. OP_ChkUndecl(((Field(Var)*)instance)[slotIndex]);
  7790. ((Field(Var)*)(instance))[slotIndex] = value;
  7791. }
  7792. void InterpreterStackFrame::OP_StEnvSlotChkUndecl(Var instance, int32 slotIndex1, int32 slotIndex2, Var value)
  7793. {
  7794. Var slotArray = OP_LdFrameDisplaySlot(instance, slotIndex1);
  7795. OP_StSlotChkUndecl(slotArray, slotIndex2, value);
  7796. }
  7797. void InterpreterStackFrame::OP_StObjSlot(Var instance, int32 slotIndex, Var value)
  7798. {
  7799. // It would be nice to assert that it's ok to store directly to slot, but we don't have the propertyId.
  7800. Field(Var) *slotArray = *(Field(Var)**)((char*)instance + DynamicObject::GetOffsetOfAuxSlots());
  7801. slotArray[slotIndex] = value;
  7802. }
  7803. void InterpreterStackFrame::OP_StObjSlotChkUndecl(Var instance, int32 slotIndex, Var value)
  7804. {
  7805. // It would be nice to assert that it's ok to store directly to slot, but we don't have the propertyId.
  7806. Field(Var) *slotArray = *(Field(Var)**)((char*)instance + DynamicObject::GetOffsetOfAuxSlots());
  7807. OP_ChkUndecl(slotArray[slotIndex]);
  7808. slotArray[slotIndex] = value;
  7809. }
  7810. void InterpreterStackFrame::OP_StEnvObjSlot(Var instance, int32 slotIndex1, int32 slotIndex2, Var value)
  7811. {
  7812. // It would be nice to assert that it's ok to store directly to slot, but we don't have the propertyId.
  7813. Var envInstance = (Var*)OP_LdFrameDisplaySlot(instance, slotIndex1);
  7814. OP_StObjSlot(envInstance, slotIndex2, value);
  7815. }
  7816. void InterpreterStackFrame::OP_StEnvObjSlotChkUndecl(Var instance, int32 slotIndex1, int32 slotIndex2, Var value)
  7817. {
  7818. // It would be nice to assert that it's ok to store directly to slot, but we don't have the propertyId.
  7819. Var envInstance = (Var*)OP_LdFrameDisplaySlot(instance, slotIndex1);
  7820. OP_StObjSlotChkUndecl(envInstance, slotIndex2, value);
  7821. }
  7822. Var InterpreterStackFrame::OP_LdStackArgPtr(void)
  7823. {
  7824. // Return the address of the first param after "this".
  7825. return m_inParams + 1;
  7826. }
  7827. ForInObjectEnumerator * InterpreterStackFrame::GetForInEnumerator(uint forInLoopLevel)
  7828. {
  7829. Assert(forInLoopLevel < this->m_functionBody->GetForInLoopDepth());
  7830. return &this->forInObjectEnumerators[forInLoopLevel];
  7831. }
  7832. void InterpreterStackFrame::OP_InitForInEnumerator(Var object, uint forInLoopLevel)
  7833. {
  7834. JavascriptOperators::OP_InitForInEnumerator(object, GetForInEnumerator(forInLoopLevel), this->GetScriptContext());
  7835. }
  7836. void InterpreterStackFrame::OP_InitForInEnumeratorWithCache(Var object, uint forInLoopLevel, ProfileId profileId)
  7837. {
  7838. JavascriptOperators::OP_InitForInEnumerator(object, GetForInEnumerator(forInLoopLevel), this->GetScriptContext(),
  7839. m_functionBody->GetForInCache(profileId));
  7840. }
  7841. // Called for the debug purpose, to create the arguments object explicitly even though script has not declared it.
  7842. Var InterpreterStackFrame::CreateHeapArguments(ScriptContext* scriptContext)
  7843. {
  7844. return JavascriptOperators::LoadHeapArguments(this->function->GetRealFunctionObject(), this->m_inSlotsCount - 1, &this->m_inParams[1], scriptContext->GetLibrary()->GetNull(), scriptContext->GetLibrary()->GetNull(), scriptContext, false);
  7845. }
  7846. template <bool letArgs>
  7847. Var InterpreterStackFrame::LdHeapArgumentsImpl(Var argsArray, ScriptContext* scriptContext)
  7848. {
  7849. Var frameObj;
  7850. if (m_functionBody->HasScopeObject() && argsArray != scriptContext->GetLibrary()->GetNull())
  7851. {
  7852. frameObj = this->localClosure;
  7853. Assert(frameObj);
  7854. }
  7855. else
  7856. {
  7857. frameObj = scriptContext->GetLibrary()->GetNull();
  7858. }
  7859. Var args = JavascriptOperators::LoadHeapArguments(this->function->GetRealFunctionObject(), this->m_inSlotsCount - 1, &this->m_inParams[1], frameObj, argsArray, scriptContext, letArgs);
  7860. this->m_arguments = args;
  7861. return args;
  7862. }
  7863. Var InterpreterStackFrame::OP_LdHeapArguments(ScriptContext* scriptContext)
  7864. {
  7865. Var argsArray = m_functionBody->GetFormalsPropIdArrayOrNullObj();
  7866. return LdHeapArgumentsImpl<false>(argsArray, scriptContext);
  7867. }
  7868. Var InterpreterStackFrame::OP_LdLetHeapArguments(ScriptContext* scriptContext)
  7869. {
  7870. Var argsArray = m_functionBody->GetFormalsPropIdArrayOrNullObj();
  7871. return LdHeapArgumentsImpl<true>(argsArray, scriptContext);
  7872. }
  7873. Var InterpreterStackFrame::OP_LdHeapArgsCached(ScriptContext* scriptContext)
  7874. {
  7875. uint32 formalsCount = this->m_functionBody->GetInParamsCount() - 1;
  7876. Var args = JavascriptOperators::LoadHeapArgsCached(this->function->GetRealFunctionObject(), this->m_inSlotsCount - 1, formalsCount, &this->m_inParams[1], this->localClosure, scriptContext, false);
  7877. this->m_arguments = args;
  7878. return args;
  7879. }
  7880. Var InterpreterStackFrame::OP_LdLetHeapArgsCached(ScriptContext* scriptContext)
  7881. {
  7882. uint32 formalsCount = this->m_functionBody->GetInParamsCount() - 1;
  7883. Var args = JavascriptOperators::LoadHeapArgsCached(this->function->GetRealFunctionObject(), this->m_inSlotsCount - 1, formalsCount, &this->m_inParams[1], this->localClosure, scriptContext, true);
  7884. this->m_arguments = args;
  7885. return args;
  7886. }
  7887. HeapArgumentsObject * InterpreterStackFrame::CreateEmptyHeapArgumentsObject(ScriptContext* scriptContext)
  7888. {
  7889. HeapArgumentsObject * args = JavascriptOperators::CreateHeapArguments(this->function->GetRealFunctionObject(), this->m_inSlotsCount - 1, 0, nullptr, scriptContext);
  7890. this->m_arguments = args;
  7891. return args;
  7892. }
  7893. void InterpreterStackFrame::TrySetFrameObjectInHeapArgObj(ScriptContext * scriptContext, bool hasNonSimpleParams, bool isScopeObjRestored)
  7894. {
  7895. Var frameObject = nullptr;
  7896. uint32 formalsCount = this->m_functionBody->GetInParamsCount() - 1;
  7897. Js::PropertyIdArray * propIds = nullptr;
  7898. Js::HeapArgumentsObject* heapArgObj = nullptr;
  7899. //We always set the Frame object to nullptr in BailOutRecord::EnsureArguments for stack args optimization.
  7900. if (m_arguments != nullptr && ((Js::HeapArgumentsObject*)(m_arguments))->GetFrameObject() == nullptr)
  7901. {
  7902. heapArgObj = (Js::HeapArgumentsObject*)m_arguments;
  7903. }
  7904. bool isCachedScope = false;
  7905. //For Non-simple params, we don't have a scope object created.
  7906. if (this->m_functionBody->NeedScopeObjectForArguments(hasNonSimpleParams))
  7907. {
  7908. frameObject = GetLocalClosure();
  7909. isCachedScope = m_functionBody->HasCachedScopePropIds();
  7910. propIds = this->m_functionBody->GetFormalsPropIdArray();
  7911. if(isScopeObjRestored && ActivationObject::Is(frameObject))
  7912. {
  7913. Assert(this->GetFunctionBody()->GetDoScopeObjectCreation());
  7914. isCachedScope = true;
  7915. if (PHASE_VERBOSE_TRACE1(Js::StackArgFormalsOptPhase) && m_functionBody->GetInParamsCount() > 1)
  7916. {
  7917. Output::Print(_u("StackArgFormals : %s (%d) :Using the restored scope object in the bail out path. \n"), m_functionBody->GetDisplayName(), m_functionBody->GetFunctionNumber());
  7918. Output::Flush();
  7919. }
  7920. }
  7921. else
  7922. {
  7923. if (isCachedScope)
  7924. {
  7925. Field(DynamicType*) literalType = nullptr;
  7926. Assert(!propIds->hasNonSimpleParams && !hasNonSimpleParams);
  7927. frameObject = JavascriptOperators::OP_InitCachedScope(this->GetJavascriptFunction(), propIds, &literalType, hasNonSimpleParams, scriptContext);
  7928. }
  7929. else
  7930. {
  7931. frameObject = JavascriptOperators::OP_NewScopeObject(GetScriptContext());
  7932. }
  7933. Assert(propIds != nullptr);
  7934. SetLocalClosure(frameObject);
  7935. if (PHASE_VERBOSE_TRACE1(Js::StackArgFormalsOptPhase) && m_functionBody->GetInParamsCount() > 1)
  7936. {
  7937. Output::Print(_u("StackArgFormals : %s (%d) :Creating scope object in the bail out path. \n"), m_functionBody->GetDisplayName(), m_functionBody->GetFunctionNumber());
  7938. Output::Flush();
  7939. }
  7940. }
  7941. }
  7942. else
  7943. {
  7944. //We reached here because, either we don't have any formals or we don't have a scope object (it could be in strict mode or have non-simple param list)
  7945. Assert(formalsCount == 0 || (m_functionBody->GetIsStrictMode() || hasNonSimpleParams));
  7946. frameObject = nullptr;
  7947. formalsCount = 0;
  7948. if (PHASE_VERBOSE_TRACE1(Js::StackArgOptPhase))
  7949. {
  7950. Output::Print(_u("StackArgOpt : %s (%d) :Creating NULL scope object in the bail out path. \n"), m_functionBody->GetDisplayName(), m_functionBody->GetFunctionNumber());
  7951. Output::Flush();
  7952. }
  7953. }
  7954. if (heapArgObj)
  7955. {
  7956. Assert(frameObject == nullptr || ActivationObject::Is(frameObject));
  7957. heapArgObj->SetFormalCount(formalsCount);
  7958. heapArgObj->SetFrameObject(frameObject != nullptr ?
  7959. static_cast<ActivationObject*>(frameObject) : nullptr);
  7960. if (PHASE_TRACE1(Js::StackArgFormalsOptPhase) && formalsCount > 0)
  7961. {
  7962. Output::Print(_u("StackArgFormals : %s (%d) :Attaching the scope object with the heap arguments object in the bail out path. \n"), m_functionBody->GetDisplayName(), m_functionBody->GetFunctionNumber());
  7963. Output::Flush();
  7964. }
  7965. }
  7966. //Fill the Heap arguments and scope object with values
  7967. // If there is no heap arguments object, then fill only the scope object with actuals.
  7968. JavascriptOperators::FillScopeObject(this->function->GetRealFunctionObject(), this->m_inSlotsCount - 1, formalsCount, frameObject, &this->m_inParams[1], propIds, heapArgObj, scriptContext, hasNonSimpleParams, isCachedScope);
  7969. }
  7970. Var InterpreterStackFrame::OP_LdArgumentsFromFrame()
  7971. {
  7972. return this->m_arguments;
  7973. }
  7974. void* InterpreterStackFrame::OP_LdArgCnt()
  7975. {
  7976. return (void*)m_inSlotsCount;
  7977. }
  7978. Var InterpreterStackFrame::OP_ResumeYield(Var yieldDataVar, RegSlot yieldStarIterator)
  7979. {
  7980. ResumeYieldData* yieldData = static_cast<ResumeYieldData*>(yieldDataVar);
  7981. RecyclableObject* iterator = yieldStarIterator != Constants::NoRegister ? RecyclableObject::FromVar(GetNonVarReg(yieldStarIterator)) : nullptr;
  7982. return JavascriptOperators::OP_ResumeYield(yieldData, iterator);
  7983. }
  7984. void* InterpreterStackFrame::operator new(size_t byteSize, void* previousAllocation) throw()
  7985. {
  7986. //
  7987. // Placement 'new' is used by InterpreterStackFrame to initialize the C++ object on the RcInterpreter's
  7988. // program stack:
  7989. // - Unlike most other allocations, the previously allocated memory will __not__ be
  7990. // zero-initialized, as we do not want the overhead of zero-initializing the frame when
  7991. // calling functions.
  7992. //
  7993. // NOTE: If we wanted to add C# semantics of all locals are automatically zero-initialized,
  7994. // need to determine the most efficient mechanism for this.
  7995. //
  7996. return previousAllocation;
  7997. }
  7998. void __cdecl InterpreterStackFrame::operator delete(void * allocationToFree, void * previousAllocation) throw()
  7999. {
  8000. AssertMsg(allocationToFree == previousAllocation, "Memory locations should match");
  8001. AssertMsg(false, "This function should never actually be called");
  8002. }
  8003. void InterpreterStackFrame::OP_WasmPrintFunc(int regIndex)
  8004. {
  8005. #if defined(ENABLE_DEBUG_CONFIG_OPTIONS) && defined(ENABLE_WASM)
  8006. Assert(m_functionBody->IsWasmFunction());
  8007. uint index = GetRegRawInt(regIndex);
  8008. Wasm::WasmFunctionInfo* info = m_functionBody->GetAsmJsFunctionInfo()->GetWebAssemblyModule()->GetWasmFunctionInfo(index);
  8009. int col = WAsmJs::Tracing::GetPrintCol();
  8010. if (col > 0)
  8011. {
  8012. Output::SkipToColumn(col);
  8013. }
  8014. info->GetBody()->DumpFullFunctionName();
  8015. Output::Print(_u("("));
  8016. #endif
  8017. }
  8018. JavascriptArrayBuffer* InterpreterStackFrame::GetAsmJsBuffer() const
  8019. {
  8020. AssertMsg(!m_functionBody->IsWasmFunction(), "Do not use GetAsmJsBuffer for WebAssembly, Use GetWebAssemblyMemory instead");
  8021. return m_asmJsBuffer;
  8022. }
  8023. #ifdef ENABLE_WASM
  8024. WebAssemblyMemory* InterpreterStackFrame::GetWebAssemblyMemory() const
  8025. {
  8026. AssertMsg(m_functionBody->IsWasmFunction(), "Do not use GetWebAssemblyMemory for Asm.js, Use GetAsmJsBuffer instead");
  8027. return m_wasmMemory;
  8028. }
  8029. #endif
  8030. template void* Js::InterpreterStackFrame::GetReg<unsigned int>(unsigned int) const;
  8031. template void Js::InterpreterStackFrame::SetReg<unsigned int>(unsigned int, void*);
  8032. } // namespace Js
  8033. // Make sure the macro and the layout for the op is consistent
  8034. #define DEF2(x, op, ...) \
  8035. CompileAssert(!Js::OpCodeInfo<Js::OpCode::op>::HasMultiSizeLayout); \
  8036. CompileAssert(!Js::OpCodeInfo<Js::OpCode::op>::IsExtendedOpcode);
  8037. #define DEF3(x, op, ...) DEF2(x, op)
  8038. #define EXDEF2(x, op, ...) \
  8039. CompileAssert(!Js::OpCodeInfo<Js::OpCode::op>::HasMultiSizeLayout); \
  8040. CompileAssert(Js::OpCodeInfo<Js::OpCode::op>::IsExtendedOpcode);
  8041. #define EXDEF3(x, op, ...) EXDEF2(x, op)
  8042. #define DEF2_WMS(x, op, ...) \
  8043. CompileAssert(Js::OpCodeInfo<Js::OpCode::op>::HasMultiSizeLayout); \
  8044. CompileAssert(!Js::OpCodeInfo<Js::OpCode::op>::IsExtendedOpcode);
  8045. #define DEF3_WMS(x, op, ...) DEF2_WMS(x, op)
  8046. #define EXDEF2_WMS(x, op, ...) \
  8047. CompileAssert(Js::OpCodeInfo<Js::OpCode::op>::HasMultiSizeLayout); \
  8048. CompileAssert(Js::OpCodeInfo<Js::OpCode::op>::IsExtendedOpcode);
  8049. #define EXDEF3_WMS(x, op, ...) EXDEF2_WMS(x, op)
  8050. #include "InterpreterHandler.inl"
  8051. // Make sure the macro and the layout for the op is consistent
  8052. #define DEF2(x, op, ...) \
  8053. CompileAssert(!Js::OpCodeInfoAsmJs<Js::OpCodeAsmJs::op>::HasMultiSizeLayout); \
  8054. CompileAssert(!Js::OpCodeInfoAsmJs<Js::OpCodeAsmJs::op>::IsExtendedOpcode);
  8055. #define DEF3(x, op, ...) DEF2(x, op)
  8056. #define DEF4(x, op, ...) DEF2(x, op)
  8057. #define EXDEF2(x, op, ...) \
  8058. CompileAssert(!Js::OpCodeInfoAsmJs<Js::OpCodeAsmJs::op>::HasMultiSizeLayout); \
  8059. CompileAssert(Js::OpCodeInfoAsmJs<Js::OpCodeAsmJs::op>::IsExtendedOpcode);
  8060. #define EXDEF3(x, op, ...) EXDEF2(x, op)
  8061. #define EXDEF4(x, op, ...) EXDEF2(x, op)
  8062. #define DEF2_WMS(x, op, ...) \
  8063. CompileAssert(Js::OpCodeInfoAsmJs<Js::OpCodeAsmJs::op>::HasMultiSizeLayout); \
  8064. CompileAssert(!Js::OpCodeInfoAsmJs<Js::OpCodeAsmJs::op>::IsExtendedOpcode);
  8065. #define DEF3_WMS(x, op, ...) DEF2_WMS(x, op)
  8066. #define DEF4_WMS(x, op, ...) DEF2_WMS(x, op)
  8067. #define EXDEF2_WMS(x, op, ...) \
  8068. CompileAssert(Js::OpCodeInfoAsmJs<Js::OpCodeAsmJs::op>::HasMultiSizeLayout); \
  8069. CompileAssert(Js::OpCodeInfoAsmJs<Js::OpCodeAsmJs::op>::IsExtendedOpcode);
  8070. #define EXDEF3_WMS(x, op, ...) EXDEF2_WMS(x, op)
  8071. #define EXDEF4_WMS(x, op, ...) EXDEF2_WMS(x, op)
  8072. #include "InterpreterHandlerAsmJs.inl"