FunctionBody.cpp 361 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "RuntimeBasePch.h"
  6. #include "ByteCode/ByteCodeApi.h"
  7. #include "ByteCode/ByteCodeDumper.h"
  8. #include "Language/AsmJsTypes.h"
  9. #include "Language/AsmJsModule.h"
  10. #include "ByteCode/ByteCodeSerializer.h"
  11. #include "Language/FunctionCodeGenRuntimeData.h"
  12. #include "ByteCode/ScopeInfo.h"
  13. #include "Base/EtwTrace.h"
  14. #ifdef VTUNE_PROFILING
  15. #include "Base/VTuneChakraProfile.h"
  16. #endif
  17. #ifdef DYNAMIC_PROFILE_MUTATOR
  18. #include "Language/DynamicProfileMutator.h"
  19. #endif
  20. #include "Language/SourceDynamicProfileManager.h"
  21. #ifdef ENABLE_SCRIPT_DEBUGGING
  22. #include "Debug/ProbeContainer.h"
  23. #include "Debug/DebugContext.h"
  24. #endif
  25. #include "Parser.h"
  26. #include "RegexCommon.h"
  27. #include "RegexPattern.h"
  28. #include "Library/RegexHelper.h"
  29. #include "Language/InterpreterStackFrame.h"
  30. #include "Library/ModuleRoot.h"
  31. #include "Types/PathTypeHandler.h"
  32. #include "Common/MathUtil.h"
  33. #if ENABLE_NATIVE_CODEGEN
  34. #include "NativeEntryPointData.h"
  35. #include "JitTransferData.h"
  36. #endif
  37. namespace Js
  38. {
  39. // The VS2013 linker treats this as a redefinition of an already
  40. // defined constant and complains. So skip the declaration if we're compiling
  41. // with VS2013 or below.
  42. #if !defined(_MSC_VER) || _MSC_VER >= 1900
  43. uint const ScopeSlots::MaxEncodedSlotCount;
  44. #endif
  45. #ifdef FIELD_ACCESS_STATS
  46. void FieldAccessStats::Add(FieldAccessStats* other)
  47. {
  48. Assert(other != nullptr);
  49. this->totalInlineCacheCount += other->totalInlineCacheCount;
  50. this->noInfoInlineCacheCount += other->noInfoInlineCacheCount;
  51. this->monoInlineCacheCount += other->monoInlineCacheCount;
  52. this->emptyMonoInlineCacheCount += other->emptyMonoInlineCacheCount;
  53. this->polyInlineCacheCount += other->polyInlineCacheCount;
  54. this->nullPolyInlineCacheCount += other->nullPolyInlineCacheCount;
  55. this->emptyPolyInlineCacheCount += other->emptyPolyInlineCacheCount;
  56. this->ignoredPolyInlineCacheCount += other->ignoredPolyInlineCacheCount;
  57. this->highUtilPolyInlineCacheCount += other->highUtilPolyInlineCacheCount;
  58. this->lowUtilPolyInlineCacheCount += other->lowUtilPolyInlineCacheCount;
  59. this->equivPolyInlineCacheCount += other->equivPolyInlineCacheCount;
  60. this->nonEquivPolyInlineCacheCount += other->nonEquivPolyInlineCacheCount;
  61. this->disabledPolyInlineCacheCount += other->disabledPolyInlineCacheCount;
  62. this->clonedMonoInlineCacheCount += other->clonedMonoInlineCacheCount;
  63. this->clonedPolyInlineCacheCount += other->clonedPolyInlineCacheCount;
  64. }
  65. #endif
  66. // FunctionProxy methods
  67. FunctionProxy::FunctionProxy(ScriptContext* scriptContext, Utf8SourceInfo* utf8SourceInfo, uint functionNumber):
  68. m_isTopLevel(false),
  69. m_isPublicLibraryCode(false),
  70. m_scriptContext(scriptContext),
  71. deferredPrototypeType(nullptr),
  72. undeferredFunctionType(nullptr),
  73. m_utf8SourceInfo(utf8SourceInfo),
  74. m_functionNumber(functionNumber),
  75. m_defaultEntryPointInfo(nullptr),
  76. m_displayNameIsRecyclerAllocated(false),
  77. m_tag11(true),
  78. m_isJsBuiltInCode(false)
  79. {
  80. PERF_COUNTER_INC(Code, TotalFunction);
  81. }
  82. bool FunctionProxy::IsWasmFunction() const
  83. {
  84. return GetFunctionInfo()->HasParseableInfo() &&
  85. GetFunctionInfo()->GetFunctionBody()->IsWasmFunction();
  86. }
  87. Recycler* FunctionProxy::GetRecycler() const
  88. {
  89. return m_scriptContext->GetRecycler();
  90. }
  91. void* FunctionProxy::GetAuxPtr(AuxPointerType e) const
  92. {
  93. if (this->auxPtrs == nullptr)
  94. {
  95. return nullptr;
  96. }
  97. // On process detach this can be called from another thread but the ThreadContext should be locked
  98. Assert(ThreadContext::GetContextForCurrentThread() || ThreadContext::GetCriticalSection()->IsLocked());
  99. return AuxPtrsT::GetAuxPtr(this, e);
  100. }
  101. void* FunctionProxy::GetAuxPtrWithLock(AuxPointerType e) const
  102. {
  103. if (this->auxPtrs == nullptr)
  104. {
  105. return nullptr;
  106. }
  107. #if DBG && ENABLE_NATIVE_CODEGEN && defined(_WIN32)
  108. // the lock for work item queue should not be locked while accessing AuxPtrs in background thread
  109. auto jobProcessor = this->GetScriptContext()->GetThreadContext()->GetJobProcessor();
  110. auto jobProcessorCS = jobProcessor->GetCriticalSection();
  111. // ->IsLocked is not supported on xplat
  112. Assert(!jobProcessorCS || !jobProcessor->ProcessesInBackground() || !jobProcessorCS->IsLocked());
  113. #endif
  114. AutoCriticalSection autoCS(this->GetScriptContext()->GetThreadContext()->GetFunctionBodyLock());
  115. return AuxPtrsT::GetAuxPtr(this, e);
  116. }
  117. void FunctionProxy::SetAuxPtr(AuxPointerType e, void* ptr)
  118. {
  119. // On process detach this can be called from another thread but the ThreadContext should be locked
  120. Assert(ThreadContext::GetContextForCurrentThread() || ThreadContext::GetCriticalSection()->IsLocked());
  121. if (ptr == nullptr && GetAuxPtr(e) == nullptr)
  122. {
  123. return;
  124. }
  125. // when setting ptr to null we never need to promote
  126. AutoCriticalSection autoCS(this->GetScriptContext()->GetThreadContext()->GetFunctionBodyLock());
  127. AuxPtrsT::SetAuxPtr(this, e, ptr);
  128. }
  129. uint FunctionProxy::GetSourceContextId() const
  130. {
  131. return this->GetUtf8SourceInfo()->GetSrcInfo()->sourceContextInfo->sourceContextId;
  132. }
  133. char16* FunctionProxy::GetDebugNumberSet(wchar(&bufferToWriteTo)[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE]) const
  134. {
  135. // (#%u.%u), #%u --> (source file Id . function Id) , function Number
  136. int len = swprintf_s(bufferToWriteTo, MAX_FUNCTION_BODY_DEBUG_STRING_SIZE, _u(" (#%d.%u), #%u"),
  137. (int)this->GetSourceContextId(), this->GetLocalFunctionId(), this->GetFunctionNumber());
  138. Assert(len > 8);
  139. return bufferToWriteTo;
  140. }
  141. bool
  142. FunctionProxy::IsFunctionBody() const
  143. {
  144. return !IsDeferredDeserializeFunction() && GetParseableFunctionInfo()->IsFunctionParsed();
  145. }
  146. uint
  147. ParseableFunctionInfo::GetSourceIndex() const
  148. {
  149. return this->m_sourceIndex;
  150. }
  151. LPCUTF8
  152. ParseableFunctionInfo::GetSource(const char16* reason) const
  153. {
  154. return this->GetUtf8SourceInfo()->GetSource(reason == nullptr ? _u("ParseableFunctionInfo::GetSource") : reason) + this->StartOffset();
  155. }
  156. LPCUTF8
  157. ParseableFunctionInfo::GetStartOfDocument(const char16* reason) const
  158. {
  159. return this->GetUtf8SourceInfo()->GetSource(reason == nullptr ? _u("ParseableFunctionInfo::GetStartOfDocument") : reason);
  160. }
  161. bool
  162. ParseableFunctionInfo::IsDynamicFunction() const
  163. {
  164. return this->m_isDynamicFunction;
  165. }
  166. bool
  167. ParseableFunctionInfo::IsDynamicScript() const
  168. {
  169. return this->GetSourceContextInfo()->IsDynamic();
  170. }
  171. charcount_t
  172. ParseableFunctionInfo::StartInDocument() const
  173. {
  174. return this->m_cchStartOffset;
  175. }
  176. uint
  177. ParseableFunctionInfo::StartOffset() const
  178. {
  179. return this->m_cbStartOffset;
  180. }
  181. void ParseableFunctionInfo::RegisterFuncToDiag(ScriptContext * scriptContext, char16 const * pszTitle)
  182. {
  183. #ifdef ENABLE_SCRIPT_DEBUGGING
  184. // Register the function to the PDM as eval code (the debugger app will show file as 'eval code')
  185. scriptContext->GetDebugContext()->RegisterFunction(this, pszTitle);
  186. #endif
  187. }
  188. bool ParseableFunctionInfo::IsES6ModuleCode() const
  189. {
  190. return (GetGrfscr() & fscrIsModuleCode) == fscrIsModuleCode;
  191. }
  192. // Given an offset into the source buffer, determine if the end of this SourceInfo
  193. // lies after the given offset.
  194. bool
  195. ParseableFunctionInfo::EndsAfter(size_t offset) const
  196. {
  197. return offset < this->StartOffset() + this->LengthInBytes();
  198. }
  199. uint32 FunctionBody::GetCountField(FunctionBody::CounterFields fieldEnum) const
  200. {
  201. #if DBG
  202. Assert(ThreadContext::GetContextForCurrentThread() || counters.isLockedDown
  203. || (ThreadContext::GetCriticalSection()->IsLocked() && this->m_scriptContext->GetThreadContext()->GetFunctionBodyLock()->IsLocked())); // etw rundown
  204. #endif
  205. return counters.Get(fieldEnum);
  206. }
  207. uint32 FunctionBody::SetCountField(FunctionBody::CounterFields fieldEnum, uint32 val)
  208. {
  209. Assert(!counters.isLockedDown);
  210. return counters.Set(fieldEnum, val, this);
  211. }
  212. uint32 FunctionBody::IncreaseCountField(FunctionBody::CounterFields fieldEnum)
  213. {
  214. Assert(!counters.isLockedDown);
  215. return counters.Increase(fieldEnum, this);
  216. }
  217. void
  218. FunctionBody::RecordStatementMap(StatementMap* pStatementMap)
  219. {
  220. Assert(!this->m_sourceInfo.pSpanSequence);
  221. Recycler* recycler = this->m_scriptContext->GetRecycler();
  222. StatementMapList * statementMaps = this->GetStatementMaps();
  223. if (!statementMaps)
  224. {
  225. statementMaps = RecyclerNew(recycler, StatementMapList, recycler);
  226. this->SetStatementMaps(statementMaps);
  227. }
  228. statementMaps->Add(pStatementMap);
  229. }
  230. void
  231. FunctionBody::RecordStatementMap(SmallSpanSequenceIter &iter, StatementData * data)
  232. {
  233. Assert(!this->GetStatementMaps());
  234. if (!this->m_sourceInfo.pSpanSequence)
  235. {
  236. this->m_sourceInfo.pSpanSequence = HeapNew(SmallSpanSequence);
  237. }
  238. this->m_sourceInfo.pSpanSequence->RecordARange(iter, data);
  239. }
  240. void
  241. FunctionBody::RecordStatementAdjustment(uint offset, StatementAdjustmentType adjType)
  242. {
  243. this->EnsureAuxStatementData();
  244. Recycler* recycler = this->m_scriptContext->GetRecycler();
  245. if (this->GetStatementAdjustmentRecords() == nullptr)
  246. {
  247. m_sourceInfo.m_auxStatementData->m_statementAdjustmentRecords = RecyclerNew(recycler, StatementAdjustmentRecordList, recycler);
  248. }
  249. StatementAdjustmentRecord record(adjType, offset);
  250. this->GetStatementAdjustmentRecords()->Add(record); // Will copy stack value and put the copy into the container.
  251. }
  252. BOOL
  253. FunctionBody::GetBranchOffsetWithin(uint start, uint end, StatementAdjustmentRecord* record)
  254. {
  255. Assert(start < end);
  256. if (!this->GetStatementAdjustmentRecords())
  257. {
  258. // No Offset
  259. return FALSE;
  260. }
  261. int count = this->GetStatementAdjustmentRecords()->Count();
  262. for (int i = 0; i < count; i++)
  263. {
  264. StatementAdjustmentRecord item = this->GetStatementAdjustmentRecords()->Item(i);
  265. if (item.GetByteCodeOffset() > start && item.GetByteCodeOffset() < end)
  266. {
  267. *record = item;
  268. return TRUE;
  269. }
  270. }
  271. // No offset found in the range.
  272. return FALSE;
  273. }
  274. ScriptContext* EntryPointInfo::GetScriptContext()
  275. {
  276. Assert(!IsCleanedUp());
  277. return this->library->GetScriptContext();
  278. }
  279. #if ENABLE_NATIVE_CODEGEN
  280. #if DBG_DUMP | defined(VTUNE_PROFILING)
  281. void
  282. EntryPointInfo::RecordNativeMap(uint32 nativeOffset, uint32 statementIndex)
  283. {
  284. auto& nativeOffsetMaps = this->GetNativeEntryPointData()->GetNativeOffsetMaps();
  285. int count = nativeOffsetMaps.Count();
  286. if (count)
  287. {
  288. NativeEntryPointData::NativeOffsetMap* previous = &nativeOffsetMaps.Item(count-1);
  289. // Check if the range is still not finished.
  290. if (previous->nativeOffsetSpan.begin == previous->nativeOffsetSpan.end)
  291. {
  292. if (previous->statementIndex == statementIndex)
  293. {
  294. // If the statement index is the same, we can continue with the previous range
  295. return;
  296. }
  297. // If the range is empty, replace the previous range.
  298. if ((uint32)previous->nativeOffsetSpan.begin == nativeOffset)
  299. {
  300. if (statementIndex == Js::Constants::NoStatementIndex)
  301. {
  302. nativeOffsetMaps.RemoveAtEnd();
  303. }
  304. else
  305. {
  306. previous->statementIndex = statementIndex;
  307. }
  308. return;
  309. }
  310. // Close the previous range
  311. previous->nativeOffsetSpan.end = nativeOffset;
  312. }
  313. }
  314. if (statementIndex == Js::Constants::NoStatementIndex)
  315. {
  316. // We do not explicitly record the offsets that do not map to user code.
  317. return;
  318. }
  319. NativeEntryPointData::NativeOffsetMap map;
  320. map.statementIndex = statementIndex;
  321. map.nativeOffsetSpan.begin = nativeOffset;
  322. map.nativeOffsetSpan.end = nativeOffset;
  323. nativeOffsetMaps.Add(map);
  324. }
  325. #endif
  326. #endif
  327. void
  328. FunctionBody::CopySourceInfo(ParseableFunctionInfo* originalFunctionInfo)
  329. {
  330. this->FinishSourceInfo();
  331. }
  332. // When sourceInfo is complete, register this functionBody to utf8SourceInfo. This ensures we never
  333. // put incomplete functionBody into utf8SourceInfo map. (Previously we do it in FunctionBody constructor.
  334. // If an error occurs thereafter before SetSourceInfo, e.g. OOM, we'll have an incomplete functionBody
  335. // in utf8SourceInfo map whose source range is unknown and can't be reparsed.)
  336. void FunctionBody::FinishSourceInfo()
  337. {
  338. this->GetUtf8SourceInfo()->SetFunctionBody(this);
  339. }
  340. RegSlot FunctionBody::GetFrameDisplayRegister() const
  341. {
  342. return this->m_sourceInfo.frameDisplayRegister;
  343. }
  344. void FunctionBody::SetFrameDisplayRegister(RegSlot frameDisplayRegister)
  345. {
  346. this->m_sourceInfo.frameDisplayRegister = frameDisplayRegister;
  347. }
  348. RegSlot FunctionBody::GetObjectRegister() const
  349. {
  350. return this->m_sourceInfo.objectRegister;
  351. }
  352. void FunctionBody::SetObjectRegister(RegSlot objectRegister)
  353. {
  354. this->m_sourceInfo.objectRegister = objectRegister;
  355. }
  356. ScopeObjectChain *FunctionBody::GetScopeObjectChain() const
  357. {
  358. return this->m_sourceInfo.pScopeObjectChain;
  359. }
  360. void FunctionBody::SetScopeObjectChain(ScopeObjectChain *pScopeObjectChain)
  361. {
  362. this->m_sourceInfo.pScopeObjectChain = pScopeObjectChain;
  363. }
  364. ByteBlock *FunctionBody::GetProbeBackingBlock()
  365. {
  366. return this->m_sourceInfo.m_probeBackingBlock;
  367. }
  368. void FunctionBody::SetProbeBackingBlock(ByteBlock* probeBackingBlock)
  369. {
  370. this->m_sourceInfo.m_probeBackingBlock = probeBackingBlock;
  371. }
  372. FunctionBody * FunctionBody::NewFromRecycler(ScriptContext * scriptContext, const char16 * displayName, uint displayNameLength, uint displayShortNameOffset, uint nestedCount,
  373. Utf8SourceInfo* sourceInfo, uint uScriptId, Js::LocalFunctionId functionId, FunctionInfo::Attributes attributes, FunctionBodyFlags flags
  374. #ifdef PERF_COUNTERS
  375. , bool isDeserializedFunction
  376. #endif
  377. )
  378. {
  379. return FunctionBody::NewFromRecycler(scriptContext, displayName, displayNameLength, displayShortNameOffset, nestedCount, sourceInfo,
  380. scriptContext->GetThreadContext()->NewFunctionNumber(), uScriptId, functionId, attributes, flags
  381. #ifdef PERF_COUNTERS
  382. , isDeserializedFunction
  383. #endif
  384. );
  385. }
  386. FunctionBody * FunctionBody::NewFromRecycler(ScriptContext * scriptContext, const char16 * displayName, uint displayNameLength, uint displayShortNameOffset, uint nestedCount,
  387. Utf8SourceInfo* sourceInfo, uint uFunctionNumber, uint uScriptId, Js::LocalFunctionId functionId, FunctionInfo::Attributes attributes, FunctionBodyFlags flags
  388. #ifdef PERF_COUNTERS
  389. , bool isDeserializedFunction
  390. #endif
  391. )
  392. {
  393. #ifdef PERF_COUNTERS
  394. return RecyclerNewWithBarrierFinalized(scriptContext->GetRecycler(), FunctionBody, scriptContext, displayName, displayNameLength, displayShortNameOffset, nestedCount, sourceInfo, uFunctionNumber, uScriptId, functionId, attributes, flags, isDeserializedFunction);
  395. #else
  396. return RecyclerNewWithBarrierFinalized(scriptContext->GetRecycler(), FunctionBody, scriptContext, displayName, displayNameLength, displayShortNameOffset, nestedCount, sourceInfo, uFunctionNumber, uScriptId, functionId, attributes, flags);
  397. #endif
  398. }
  399. FunctionBody *
  400. FunctionBody::NewFromParseableFunctionInfo(ParseableFunctionInfo * parseableFunctionInfo)
  401. {
  402. ScriptContext * scriptContext = parseableFunctionInfo->GetScriptContext();
  403. uint nestedCount = parseableFunctionInfo->GetNestedCount();
  404. FunctionBody * functionBody = RecyclerNewWithBarrierFinalized(scriptContext->GetRecycler(),
  405. FunctionBody,
  406. parseableFunctionInfo);
  407. // Initialize nested function array, update back pointers
  408. for (uint i = 0; i < nestedCount; i++)
  409. {
  410. FunctionInfo * nestedInfo = parseableFunctionInfo->GetNestedFunc(i);
  411. functionBody->SetNestedFunc(nestedInfo, i, 0);
  412. }
  413. return functionBody;
  414. }
  415. FunctionBody::FunctionBody(ScriptContext* scriptContext, const char16* displayName, uint displayNameLength, uint displayShortNameOffset, uint nestedCount,
  416. Utf8SourceInfo* utf8SourceInfo, uint uFunctionNumber, uint uScriptId,
  417. Js::LocalFunctionId functionId, FunctionInfo::Attributes attributes, FunctionBodyFlags flags
  418. #ifdef PERF_COUNTERS
  419. , bool isDeserializedFunction
  420. #endif
  421. ) :
  422. ParseableFunctionInfo(scriptContext->CurrentThunk, nestedCount, functionId, utf8SourceInfo, scriptContext, uFunctionNumber, displayName, displayNameLength, displayShortNameOffset, attributes, flags),
  423. counters(this),
  424. m_uScriptId(uScriptId),
  425. cleanedUp(false),
  426. sourceInfoCleanedUp(false),
  427. profiledLdLenCount(0),
  428. profiledLdElemCount(0),
  429. profiledStElemCount(0),
  430. profiledCallSiteCount(0),
  431. profiledArrayCallSiteCount(0),
  432. profiledDivOrRemCount(0),
  433. profiledSwitchCount(0),
  434. profiledReturnTypeCount(0),
  435. profiledSlotCount(0),
  436. m_isFuncRegistered(false),
  437. m_isFuncRegisteredToDiag(false),
  438. m_hasBailoutInstrInJittedCode(false),
  439. m_depth(0),
  440. inlineDepth(0),
  441. m_pendingLoopHeaderRelease(false),
  442. hasCachedScopePropIds(false),
  443. m_argUsedForBranch(0),
  444. m_envDepth((uint16)-1),
  445. loopInterpreterLimit(CONFIG_FLAG(LoopInterpretCount)),
  446. savedPolymorphicCacheState(0),
  447. debuggerScopeIndex(0),
  448. m_hasFinally(false),
  449. #if ENABLE_PROFILE_INFO
  450. dynamicProfileInfo(nullptr),
  451. #endif
  452. savedInlinerVersion(0),
  453. #if ENABLE_NATIVE_CODEGEN
  454. savedImplicitCallsFlags(ImplicitCall_HasNoInfo),
  455. #endif
  456. hasExecutionDynamicProfileInfo(false),
  457. m_hasAllNonLocalReferenced(false),
  458. m_hasSetIsObject(false),
  459. m_hasFunExprNameReference(false),
  460. m_CallsEval(false),
  461. m_ChildCallsEval(false),
  462. m_hasReferenceableBuiltInArguments(false),
  463. m_isParamAndBodyScopeMerged(true),
  464. m_firstFunctionObject(true),
  465. m_inlineCachesOnFunctionObject(false),
  466. m_hasDoneAllNonLocalReferenced(false),
  467. m_hasFunctionCompiledSent(false),
  468. byteCodeCache(nullptr),
  469. m_hasLocalClosureRegister(false),
  470. m_hasParamClosureRegister(false),
  471. m_hasLocalFrameDisplayRegister(false),
  472. m_hasEnvRegister(false),
  473. m_hasThisRegisterForEventHandler(false),
  474. m_hasFirstInnerScopeRegister(false),
  475. m_hasFuncExprScopeRegister(false),
  476. m_hasFirstTmpRegister(false),
  477. m_hasActiveReference(false),
  478. m_tag31(true),
  479. m_tag32(true),
  480. m_tag33(true),
  481. m_nativeEntryPointUsed(false),
  482. hasDoneLoopBodyCodeGen(false),
  483. bailOnMisingProfileCount(0),
  484. bailOnMisingProfileRejitCount(0),
  485. byteCodeBlock(nullptr),
  486. entryPoints(nullptr),
  487. m_constTable(nullptr),
  488. inlineCaches(nullptr),
  489. cacheIdToPropertyIdMap(nullptr),
  490. wasCalledFromLoop(false),
  491. hasScopeObject(false),
  492. hasNestedLoop(false),
  493. recentlyBailedOutOfJittedLoopBody(false),
  494. m_isAsmJsScheduledForFullJIT(false),
  495. m_asmJsTotalLoopCount(0)
  496. //
  497. // Even if the function does not require any locals, we must always have "R0" to propagate
  498. // a return value. By enabling this here, we avoid unnecessary conditionals during execution.
  499. //
  500. #ifdef IR_VIEWER
  501. ,m_isIRDumpEnabled(false)
  502. ,m_irDumpBaseObject(nullptr)
  503. #endif /* IR_VIEWER */
  504. , m_isFromNativeCodeModule(false)
  505. , hasHotLoop(false)
  506. , m_isPartialDeserializedFunction(false)
  507. #if DBG
  508. , m_isSerialized(false)
  509. #endif
  510. #ifdef PERF_COUNTERS
  511. , m_isDeserializedFunction(isDeserializedFunction)
  512. #endif
  513. #if DBG
  514. , m_DEBUG_executionCount(0)
  515. , m_nativeEntryPointIsInterpreterThunk(false)
  516. , m_canDoStackNestedFunc(false)
  517. , m_inlineCacheTypes(nullptr)
  518. , m_iProfileSession(-1)
  519. #endif
  520. #if ENABLE_DEBUG_CONFIG_OPTIONS
  521. , regAllocLoadCount(0)
  522. , regAllocStoreCount(0)
  523. , callCountStats(0)
  524. #endif
  525. {
  526. SetCountField(CounterFields::ConstantCount, 1);
  527. this->SetDefaultFunctionEntryPointInfo((FunctionEntryPointInfo*) this->GetDefaultEntryPointInfo(), DefaultEntryThunk);
  528. this->m_hasBeenParsed = true;
  529. #ifdef PERF_COUNTERS
  530. if (isDeserializedFunction)
  531. {
  532. PERF_COUNTER_INC(Code, DeserializedFunctionBody);
  533. }
  534. #endif
  535. Assert(!utf8SourceInfo || m_uScriptId == utf8SourceInfo->GetSrcInfo()->sourceContextInfo->sourceContextId);
  536. // Sync entryPoints changes to etw rundown lock
  537. CriticalSection* syncObj = scriptContext->GetThreadContext()->GetFunctionBodyLock();
  538. this->entryPoints = RecyclerNew(this->m_scriptContext->GetRecycler(), FunctionEntryPointList, this->m_scriptContext->GetRecycler(), syncObj);
  539. this->AddEntryPointToEntryPointList(this->GetDefaultFunctionEntryPointInfo());
  540. Assert(this->GetDefaultEntryPointInfo()->jsMethod != nullptr);
  541. InitDisableInlineApply();
  542. InitDisableInlineSpread();
  543. }
  544. FunctionBody::FunctionBody(ParseableFunctionInfo * proxy) :
  545. ParseableFunctionInfo(proxy),
  546. counters(this),
  547. m_uScriptId(proxy->GetUtf8SourceInfo()->GetSrcInfo()->sourceContextInfo->sourceContextId),
  548. cleanedUp(false),
  549. sourceInfoCleanedUp(false),
  550. profiledLdLenCount(0),
  551. profiledLdElemCount(0),
  552. profiledStElemCount(0),
  553. profiledCallSiteCount(0),
  554. profiledArrayCallSiteCount(0),
  555. profiledDivOrRemCount(0),
  556. profiledSwitchCount(0),
  557. profiledReturnTypeCount(0),
  558. profiledSlotCount(0),
  559. m_isFuncRegistered(false),
  560. m_isFuncRegisteredToDiag(false),
  561. m_hasBailoutInstrInJittedCode(false),
  562. m_depth(0),
  563. inlineDepth(0),
  564. m_pendingLoopHeaderRelease(false),
  565. hasCachedScopePropIds(false),
  566. m_argUsedForBranch(0),
  567. m_envDepth((uint16)-1),
  568. loopInterpreterLimit(CONFIG_FLAG(LoopInterpretCount)),
  569. savedPolymorphicCacheState(0),
  570. debuggerScopeIndex(0),
  571. m_hasFinally(false),
  572. #if ENABLE_PROFILE_INFO
  573. dynamicProfileInfo(nullptr),
  574. #endif
  575. savedInlinerVersion(0),
  576. #if ENABLE_NATIVE_CODEGEN
  577. savedImplicitCallsFlags(ImplicitCall_HasNoInfo),
  578. #endif
  579. hasExecutionDynamicProfileInfo(false),
  580. m_hasAllNonLocalReferenced(false),
  581. m_hasSetIsObject(false),
  582. m_hasFunExprNameReference(false),
  583. m_CallsEval(false),
  584. m_ChildCallsEval(false),
  585. m_hasReferenceableBuiltInArguments(false),
  586. m_isParamAndBodyScopeMerged(true),
  587. m_firstFunctionObject(true),
  588. m_inlineCachesOnFunctionObject(false),
  589. m_hasDoneAllNonLocalReferenced(false),
  590. m_hasFunctionCompiledSent(false),
  591. byteCodeCache(nullptr),
  592. m_hasLocalClosureRegister(false),
  593. m_hasParamClosureRegister(false),
  594. m_hasLocalFrameDisplayRegister(false),
  595. m_hasEnvRegister(false),
  596. m_hasThisRegisterForEventHandler(false),
  597. m_hasFirstInnerScopeRegister(false),
  598. m_hasFuncExprScopeRegister(false),
  599. m_hasFirstTmpRegister(false),
  600. m_hasActiveReference(false),
  601. m_tag31(true),
  602. m_tag32(true),
  603. m_tag33(true),
  604. m_nativeEntryPointUsed(false),
  605. hasDoneLoopBodyCodeGen(false),
  606. bailOnMisingProfileCount(0),
  607. bailOnMisingProfileRejitCount(0),
  608. byteCodeBlock(nullptr),
  609. entryPoints(nullptr),
  610. m_constTable(nullptr),
  611. inlineCaches(nullptr),
  612. cacheIdToPropertyIdMap(nullptr),
  613. wasCalledFromLoop(false),
  614. hasScopeObject(false),
  615. hasNestedLoop(false),
  616. recentlyBailedOutOfJittedLoopBody(false),
  617. m_isAsmJsScheduledForFullJIT(false),
  618. m_asmJsTotalLoopCount(0)
  619. //
  620. // Even if the function does not require any locals, we must always have "R0" to propagate
  621. // a return value. By enabling this here, we avoid unnecessary conditionals during execution.
  622. //
  623. #ifdef IR_VIEWER
  624. ,m_isIRDumpEnabled(false)
  625. ,m_irDumpBaseObject(nullptr)
  626. #endif /* IR_VIEWER */
  627. , m_isFromNativeCodeModule(false)
  628. , hasHotLoop(false)
  629. , m_isPartialDeserializedFunction(false)
  630. #if DBG
  631. , m_isSerialized(false)
  632. #endif
  633. #ifdef PERF_COUNTERS
  634. , m_isDeserializedFunction(false)
  635. #endif
  636. #if DBG
  637. , m_DEBUG_executionCount(0)
  638. , m_nativeEntryPointIsInterpreterThunk(false)
  639. , m_canDoStackNestedFunc(false)
  640. , m_inlineCacheTypes(nullptr)
  641. , m_iProfileSession(-1)
  642. #endif
  643. #if ENABLE_DEBUG_CONFIG_OPTIONS
  644. , regAllocLoadCount(0)
  645. , regAllocStoreCount(0)
  646. , callCountStats(0)
  647. #endif
  648. {
  649. ScriptContext * scriptContext = proxy->GetScriptContext();
  650. SetCountField(CounterFields::ConstantCount, 1);
  651. proxy->UpdateFunctionBodyImpl(this);
  652. this->m_defaultEntryPointInfo = RecyclerNewFinalized(scriptContext->GetRecycler(),
  653. FunctionEntryPointInfo, this, scriptContext->CurrentThunk, scriptContext->GetThreadContext());
  654. this->SetDefaultFunctionEntryPointInfo((FunctionEntryPointInfo*) this->GetDefaultEntryPointInfo(), DefaultEntryThunk);
  655. this->m_hasBeenParsed = true;
  656. Assert(!proxy->GetUtf8SourceInfo() || m_uScriptId == proxy->GetUtf8SourceInfo()->GetSrcInfo()->sourceContextInfo->sourceContextId);
  657. // Sync entryPoints changes to etw rundown lock
  658. CriticalSection* syncObj = scriptContext->GetThreadContext()->GetFunctionBodyLock();
  659. this->entryPoints = RecyclerNew(scriptContext->GetRecycler(), FunctionEntryPointList, scriptContext->GetRecycler(), syncObj);
  660. this->AddEntryPointToEntryPointList(this->GetDefaultFunctionEntryPointInfo());
  661. Assert(this->GetDefaultEntryPointInfo()->jsMethod != nullptr);
  662. InitDisableInlineApply();
  663. InitDisableInlineSpread();
  664. }
  665. bool FunctionBody::InterpretedSinceCallCountCollection() const
  666. {
  667. return executionState.InterpretedSinceCallCountCollection();
  668. }
  669. void FunctionBody::CollectInterpretedCounts()
  670. {
  671. executionState.CollectInterpretedCounts();
  672. }
  673. void FunctionBody::IncrInactiveCount(uint increment)
  674. {
  675. this->inactiveCount = UInt32Math::Add(this->inactiveCount, increment);
  676. }
  677. bool FunctionBody::IsActiveFunction(ActiveFunctionSet * pActiveFuncs) const
  678. {
  679. return !!pActiveFuncs->Test(this->GetFunctionNumber());
  680. }
  681. bool FunctionBody::TestAndUpdateActiveFunctions(ActiveFunctionSet * pActiveFuncs) const
  682. {
  683. return !!pActiveFuncs->TestAndSet(this->GetFunctionNumber());
  684. }
  685. void FunctionBody::UpdateActiveFunctionsForOneDataSet(ActiveFunctionSet *pActiveFuncs, FunctionCodeGenRuntimeData *parentData, Field(FunctionCodeGenRuntimeData*)* dataSet, uint count) const
  686. {
  687. FunctionCodeGenRuntimeData *inlineeData;
  688. for (uint i = 0; i < count; i++)
  689. {
  690. for (inlineeData = dataSet[i]; inlineeData; inlineeData = inlineeData->GetNext())
  691. {
  692. // inlineeData == parentData indicates a cycle in the structure. We've already processed parentData, so don't descend.
  693. if (inlineeData != parentData)
  694. {
  695. inlineeData->GetFunctionBody()->UpdateActiveFunctionSet(pActiveFuncs, inlineeData);
  696. }
  697. }
  698. }
  699. }
  700. void FunctionBody::UpdateActiveFunctionSet(ActiveFunctionSet *pActiveFuncs, FunctionCodeGenRuntimeData *callSiteData) const
  701. {
  702. // Always walk the inlinee and ldFldInlinee data (if we have them), as they are different at each call site.
  703. if (callSiteData)
  704. {
  705. if (callSiteData->GetInlinees())
  706. {
  707. this->UpdateActiveFunctionsForOneDataSet(pActiveFuncs, callSiteData, callSiteData->GetInlinees(), this->GetProfiledCallSiteCount());
  708. }
  709. if (callSiteData->GetLdFldInlinees())
  710. {
  711. this->UpdateActiveFunctionsForOneDataSet(pActiveFuncs, callSiteData, callSiteData->GetLdFldInlinees(), this->GetInlineCacheCount());
  712. }
  713. if (callSiteData->GetCallbackInlinees())
  714. {
  715. this->UpdateActiveFunctionsForOneDataSet(pActiveFuncs, callSiteData, callSiteData->GetCallbackInlinees(), this->GetProfiledCallSiteCount());
  716. }
  717. }
  718. // Now walk the top-level data, but only do it once, since it's always the same.
  719. if (this->TestAndUpdateActiveFunctions(pActiveFuncs))
  720. {
  721. return;
  722. }
  723. {
  724. Field(FunctionCodeGenRuntimeData*)* data = this->GetCodeGenRuntimeData();
  725. if (data != nullptr)
  726. {
  727. this->UpdateActiveFunctionsForOneDataSet(pActiveFuncs, nullptr, data, this->GetProfiledCallSiteCount());
  728. }
  729. }
  730. {
  731. Field(FunctionCodeGenRuntimeData*)* data = this->GetCodeGenGetSetRuntimeData();
  732. if (data != nullptr)
  733. {
  734. this->UpdateActiveFunctionsForOneDataSet(pActiveFuncs, nullptr, data, this->GetInlineCacheCount());
  735. }
  736. }
  737. {
  738. Field(FunctionCodeGenRuntimeData*)* data = this->GetCodeGenCallbackRuntimeData();
  739. if (data != nullptr)
  740. {
  741. this->UpdateActiveFunctionsForOneDataSet(pActiveFuncs, nullptr, data, this->GetProfiledCallSiteCount());
  742. }
  743. }
  744. }
  745. bool FunctionBody::DoRedeferFunction(uint inactiveThreshold) const
  746. {
  747. if (!(this->GetFunctionInfo()->GetFunctionProxy() == this &&
  748. this->CanBeDeferred() &&
  749. this->GetByteCode() &&
  750. this->GetCanDefer()))
  751. {
  752. return false;
  753. }
  754. if (!PHASE_FORCE(Js::RedeferralPhase, this) && !PHASE_STRESS(Js::RedeferralPhase, this))
  755. {
  756. uint compileCount = this->GetCompileCount();
  757. if (compileCount >= (uint)CONFIG_FLAG(RedeferralCap))
  758. {
  759. return false;
  760. }
  761. // Redeferral threshold is k^x, where x is the number of previous compiles.
  762. bool overflow = false;
  763. uint currentThreshold = inactiveThreshold;
  764. if (compileCount > 1)
  765. {
  766. currentThreshold = JavascriptNumber::DirectPowIntInt(&overflow, inactiveThreshold, compileCount);
  767. }
  768. if (overflow)
  769. {
  770. currentThreshold = 0xFFFFFFFF;
  771. }
  772. if (this->GetInactiveCount() < currentThreshold)
  773. {
  774. return false;
  775. }
  776. }
  777. // Make sure the function won't be jitted
  778. bool isJitCandidate = false;
  779. #if ENABLE_NATIVE_CODEGEN
  780. bool isJitModeFunction = !this->IsInterpreterExecutionMode();
  781. isJitCandidate = MapEntryPointsUntil([=](int index, FunctionEntryPointInfo *entryPointInfo)
  782. {
  783. if ((entryPointInfo->IsCodeGenPending() && isJitModeFunction) || entryPointInfo->IsCodeGenQueued() || entryPointInfo->IsCodeGenRecorded() || (entryPointInfo->IsCodeGenDone() && !entryPointInfo->IsNativeEntryPointProcessed()))
  784. {
  785. return true;
  786. }
  787. return false;
  788. });
  789. if (!isJitCandidate)
  790. {
  791. // Now check loop body entry points
  792. isJitCandidate = MapLoopHeadersUntil([=](uint loopNumber, LoopHeader* header)
  793. {
  794. return header->MapEntryPointsUntil([&](int index, LoopEntryPointInfo* entryPointInfo)
  795. {
  796. if (entryPointInfo->IsCodeGenPending() || entryPointInfo->IsCodeGenQueued() || entryPointInfo->IsCodeGenRecorded() || (entryPointInfo->IsCodeGenDone() && !entryPointInfo->IsNativeEntryPointProcessed()))
  797. {
  798. return true;
  799. }
  800. return false;
  801. });
  802. });
  803. }
  804. #endif
  805. return !isJitCandidate;
  806. }
  807. void FunctionBody::RedeferFunction()
  808. {
  809. Assert(this->CanBeDeferred());
  810. #if DBG
  811. if (PHASE_STATS(RedeferralPhase, this))
  812. {
  813. ThreadContext * threadContext = this->GetScriptContext()->GetThreadContext();
  814. threadContext->redeferredFunctions++;
  815. threadContext->recoveredBytes += sizeof(*this) + this->GetInlineCacheCount() * sizeof(InlineCache);
  816. if (this->byteCodeBlock)
  817. {
  818. threadContext->recoveredBytes += this->byteCodeBlock->GetLength();
  819. if (this->GetAuxiliaryData())
  820. {
  821. threadContext->recoveredBytes += this->GetAuxiliaryData()->GetLength();
  822. }
  823. }
  824. this->MapEntryPoints([&](int index, FunctionEntryPointInfo * info) {
  825. threadContext->recoveredBytes += sizeof(info);
  826. });
  827. // TODO: Get size of polymorphic caches, jitted code, etc.
  828. }
  829. // We can't get here if the function is being jitted. Jitting was either completed or not begun.
  830. this->UnlockCounters();
  831. #endif
  832. PHASE_PRINT_TRACE(Js::RedeferralPhase, this, _u("Redeferring function %d.%d: %s\n"),
  833. GetSourceContextId(), GetLocalFunctionId(),
  834. GetDisplayName() ? GetDisplayName() : _u("Anonymous function)"));
  835. ParseableFunctionInfo * parseableFunctionInfo =
  836. Js::ParseableFunctionInfo::NewDeferredFunctionFromFunctionBody(this);
  837. FunctionInfo * functionInfo = this->GetFunctionInfo();
  838. this->RedeferFunctionObjectTypes();
  839. this->Cleanup(false);
  840. if (GetIsFuncRegistered())
  841. {
  842. this->GetUtf8SourceInfo()->RemoveFunctionBody(this);
  843. }
  844. // New allocation is done at this point, so update existing structures
  845. // Adjust functionInfo attributes, point to new proxy
  846. functionInfo->SetAttributes((FunctionInfo::Attributes)(functionInfo->GetAttributes() | FunctionInfo::Attributes::DeferredParse));
  847. functionInfo->SetFunctionProxy(parseableFunctionInfo);
  848. functionInfo->SetOriginalEntryPoint(DefaultEntryThunk);
  849. }
  850. void FunctionBody::RedeferFunctionObjectTypes()
  851. {
  852. this->MapFunctionObjectTypes([&](ScriptFunctionType* functionType)
  853. {
  854. Assert(functionType->GetTypeId() == TypeIds_Function);
  855. if (!CrossSite::IsThunk(functionType->GetEntryPoint()))
  856. {
  857. functionType->SetEntryPoint(GetScriptContext()->DeferredParsingThunk);
  858. }
  859. if (!CrossSite::IsThunk(functionType->GetEntryPointInfo()->jsMethod))
  860. {
  861. functionType->GetEntryPointInfo()->jsMethod = GetScriptContext()->DeferredParsingThunk;
  862. }
  863. });
  864. }
  865. void FunctionBody::SetDefaultFunctionEntryPointInfo(FunctionEntryPointInfo* entryPointInfo, const JavascriptMethod originalEntryPoint)
  866. {
  867. Assert(entryPointInfo);
  868. // Need to set twice since ProxyEntryPointInfo cast points to an interior pointer
  869. this->m_defaultEntryPointInfo = (ProxyEntryPointInfo*) entryPointInfo;
  870. this->defaultFunctionEntryPointInfo = entryPointInfo;
  871. SetOriginalEntryPoint(originalEntryPoint);
  872. }
  873. Var
  874. FunctionBody::GetFormalsPropIdArrayOrNullObj()
  875. {
  876. Var formalsPropIdArray = this->GetAuxPtrWithLock<AuxPointerType::FormalsPropIdArray>();
  877. if (formalsPropIdArray == nullptr)
  878. {
  879. return GetScriptContext()->GetLibrary()->GetNull();
  880. }
  881. return formalsPropIdArray;
  882. }
  883. PropertyIdArray*
  884. FunctionBody::GetFormalsPropIdArray(bool checkForNull)
  885. {
  886. if (checkForNull)
  887. {
  888. Assert(this->GetAuxPtrWithLock<AuxPointerType::FormalsPropIdArray>());
  889. }
  890. return this->GetAuxPtrWithLock<AuxPointerType::FormalsPropIdArray>();
  891. }
  892. void
  893. FunctionBody::SetFormalsPropIdArray(PropertyIdArray * propIdArray)
  894. {
  895. AssertMsg(propIdArray == nullptr || this->GetAuxPtrWithLock<AuxPointerType::FormalsPropIdArray>() == nullptr, "Already set?");
  896. this->SetAuxPtr<AuxPointerType::FormalsPropIdArray>(propIdArray);
  897. }
  898. ByteBlock*
  899. FunctionBody::GetByteCode() const
  900. {
  901. return this->byteCodeBlock;
  902. }
  903. // Returns original bytecode without probes (such as BPs).
  904. ByteBlock*
  905. FunctionBody::GetOriginalByteCode()
  906. {
  907. if (m_sourceInfo.m_probeBackingBlock)
  908. {
  909. return m_sourceInfo.m_probeBackingBlock;
  910. }
  911. else
  912. {
  913. return this->GetByteCode();
  914. }
  915. }
  916. // Returns a raw pointer to the display name which may not have a well-known lifetime. It's safer to use
  917. // GetExternalDisplayNameObject if the end goal is to create an object anyway.
  918. const char16* ParseableFunctionInfo::GetExternalDisplayName() const
  919. {
  920. return GetExternalDisplayName(this);
  921. }
  922. // Allocates a new JavascriptString object containing the display name associated with the FunctionBody.
  923. JavascriptString* ParseableFunctionInfo::GetExternalDisplayNameObject(ScriptContext* scriptContext) const
  924. {
  925. const char16* name = GetExternalDisplayName();
  926. if (!GetDisplayNameIsRecyclerAllocated() && !IsConstantFunctionName(name))
  927. {
  928. // The string is allocated in memory that we don't directly control the lifetime of. Copy the string to
  929. // ensure that the buffer remains valid for the lifetime of the object.
  930. return Js::JavascriptString::NewCopySz(name, scriptContext);
  931. }
  932. else
  933. {
  934. // Use the incoming buffer directly to create the object. This only works when the lifetime of the data is
  935. // static or GC allocated.
  936. return Js::JavascriptString::NewWithSz(name, scriptContext);
  937. }
  938. }
  939. RegSlot
  940. FunctionBody::GetLocalsCount()
  941. {
  942. return GetConstantCount() + GetVarCount();
  943. }
  944. RegSlot
  945. FunctionBody::GetVarCount()
  946. {
  947. return this->GetCountField(CounterFields::VarCount);
  948. }
  949. // Returns the number of non-temp local vars.
  950. uint32
  951. FunctionBody::GetNonTempLocalVarCount()
  952. {
  953. Assert(this->GetEndNonTempLocalIndex() >= this->GetFirstNonTempLocalIndex());
  954. return this->GetEndNonTempLocalIndex() - this->GetFirstNonTempLocalIndex();
  955. }
  956. uint32
  957. FunctionBody::GetFirstNonTempLocalIndex()
  958. {
  959. // First local var starts when the const vars end.
  960. return GetConstantCount();
  961. }
  962. uint32
  963. FunctionBody::GetEndNonTempLocalIndex()
  964. {
  965. // It will give the index on which current non temp locals ends, which is a first temp reg.
  966. RegSlot firstTmpReg = GetFirstTmpRegister();
  967. return firstTmpReg != Constants::NoRegister ? firstTmpReg : GetLocalsCount();
  968. }
  969. bool
  970. FunctionBody::IsNonTempLocalVar(uint32 varIndex)
  971. {
  972. return GetFirstNonTempLocalIndex() <= varIndex && varIndex < GetEndNonTempLocalIndex();
  973. }
  974. bool
  975. FunctionBody::GetSlotOffset(RegSlot slotId, int32 * slotOffset, bool allowTemp)
  976. {
  977. if (IsNonTempLocalVar(slotId) || allowTemp)
  978. {
  979. *slotOffset = (slotId - GetFirstNonTempLocalIndex()) * DIAGLOCALSLOTSIZE;
  980. return true;
  981. }
  982. return false;
  983. }
  984. void
  985. FunctionBody::CheckAndSetConstantCount(RegSlot cNewConstants) // New register count
  986. {
  987. CheckNotExecuting();
  988. AssertMsg(GetConstantCount() <= cNewConstants, "Cannot shrink register usage");
  989. this->SetConstantCount(cNewConstants);
  990. }
  991. void
  992. FunctionBody::SetConstantCount(RegSlot cNewConstants) // New register count
  993. {
  994. this->SetCountField(CounterFields::ConstantCount, cNewConstants);
  995. }
  996. void
  997. FunctionBody::CheckAndSetVarCount(RegSlot cNewVars)
  998. {
  999. CheckNotExecuting();
  1000. AssertMsg(this->GetVarCount() <= cNewVars, "Cannot shrink register usage");
  1001. this->SetVarCount(cNewVars);
  1002. }
  1003. void
  1004. FunctionBody::SetVarCount(RegSlot cNewVars) // New register count
  1005. {
  1006. this->SetCountField(FunctionBody::CounterFields::VarCount, cNewVars);
  1007. }
  1008. RegSlot
  1009. FunctionBody::GetYieldRegister()
  1010. {
  1011. return GetEndNonTempLocalIndex() - 1;
  1012. }
  1013. RegSlot
  1014. FunctionBody::GetFirstTmpReg()
  1015. {
  1016. AssertMsg(GetFirstTmpRegister() != Constants::NoRegister, "First temp hasn't been set yet");
  1017. return GetFirstTmpRegister();
  1018. }
  1019. void
  1020. FunctionBody::SetFirstTmpReg(
  1021. RegSlot firstTmpReg)
  1022. {
  1023. CheckNotExecuting();
  1024. AssertMsg(GetFirstTmpRegister() == Constants::NoRegister, "Should not be resetting the first temp");
  1025. SetFirstTmpRegister(firstTmpReg);
  1026. }
  1027. RegSlot
  1028. FunctionBody::GetTempCount()
  1029. {
  1030. return GetLocalsCount() - GetFirstTmpRegister();
  1031. }
  1032. void
  1033. FunctionBody::SetOutParamMaxDepth(RegSlot cOutParamsDepth)
  1034. {
  1035. #if _M_X64
  1036. constexpr RegSlot minAsmJsOutParams = MinAsmJsOutParams();
  1037. if (GetIsAsmJsFunction() && cOutParamsDepth < minAsmJsOutParams)
  1038. {
  1039. cOutParamsDepth = minAsmJsOutParams;
  1040. }
  1041. #endif
  1042. SetCountField(CounterFields::OutParamMaxDepth, cOutParamsDepth);
  1043. }
  1044. void
  1045. FunctionBody::CheckAndSetOutParamMaxDepth(RegSlot cOutParamsDepth)
  1046. {
  1047. CheckNotExecuting();
  1048. SetOutParamMaxDepth(cOutParamsDepth);
  1049. }
  1050. RegSlot
  1051. FunctionBody::GetOutParamMaxDepth()
  1052. {
  1053. return GetCountField(CounterFields::OutParamMaxDepth);
  1054. }
  1055. ModuleID
  1056. FunctionBody::GetModuleID() const
  1057. {
  1058. return this->GetHostSrcInfo()->moduleID;
  1059. }
  1060. ///----------------------------------------------------------------------------
  1061. ///
  1062. /// FunctionBody::BeginExecution
  1063. ///
  1064. /// BeginExecution() is called by InterpreterStackFrame when a function begins execution.
  1065. /// - Once started execution, the function may not be modified, as it would
  1066. /// change the stack-frame layout:
  1067. /// - This is a debug-only check because of the runtime cost. At release time,
  1068. /// a stack-walk will be performed by GC to determine which functions are
  1069. /// executing.
  1070. ///
  1071. ///----------------------------------------------------------------------------
  1072. void
  1073. FunctionBody::BeginExecution()
  1074. {
  1075. #if DBG
  1076. m_DEBUG_executionCount++;
  1077. this->LockDownCounters();
  1078. #endif
  1079. // Don't allow loop headers to be released while the function is executing
  1080. ::InterlockedIncrement(&this->m_depth);
  1081. }
  1082. ///----------------------------------------------------------------------------
  1083. ///
  1084. /// FunctionBody::CheckEmpty
  1085. ///
  1086. /// CheckEmpty() validates that the given instance has not been given an
  1087. /// implementation yet.
  1088. ///
  1089. ///----------------------------------------------------------------------------
  1090. void
  1091. FunctionBody::CheckEmpty()
  1092. {
  1093. AssertMsg((this->byteCodeBlock == nullptr) && (this->GetAuxiliaryData() == nullptr) && (this->GetAuxiliaryContextData() == nullptr), "Function body may only be set once");
  1094. }
  1095. ///----------------------------------------------------------------------------
  1096. ///
  1097. /// FunctionBody::CheckNotExecuting
  1098. ///
  1099. /// CheckNotExecuting() checks that function is not currently executing when it
  1100. /// is being modified. See BeginExecution() for details.
  1101. ///
  1102. ///----------------------------------------------------------------------------
  1103. void
  1104. FunctionBody::CheckNotExecuting()
  1105. {
  1106. AssertMsg(m_DEBUG_executionCount == 0, "Function cannot be executing when modified");
  1107. }
  1108. ///----------------------------------------------------------------------------
  1109. ///
  1110. /// FunctionBody::EndExecution
  1111. ///
  1112. /// EndExecution() is called by InterpreterStackFrame when a function ends execution.
  1113. /// See BeginExecution() for details.
  1114. ///
  1115. ///----------------------------------------------------------------------------
  1116. void
  1117. FunctionBody::EndExecution()
  1118. {
  1119. #if DBG
  1120. AssertMsg(m_DEBUG_executionCount > 0, "Must have a previous execution to end");
  1121. m_DEBUG_executionCount--;
  1122. #endif
  1123. uint depth = ::InterlockedDecrement(&this->m_depth);
  1124. // If loop headers were determined to be no longer needed
  1125. // during the execution of the function, we release them now
  1126. if (depth == 0 && this->m_pendingLoopHeaderRelease)
  1127. {
  1128. this->m_pendingLoopHeaderRelease = false;
  1129. ReleaseLoopHeaders();
  1130. }
  1131. }
  1132. void FunctionBody::AddEntryPointToEntryPointList(FunctionEntryPointInfo* entryPointInfo)
  1133. {
  1134. ThreadContext::AutoDisableExpiration disableExpiration(this->m_scriptContext->GetThreadContext());
  1135. Recycler* recycler = this->m_scriptContext->GetRecycler();
  1136. entryPointInfo->entryPointIndex = this->entryPoints->Add(recycler->CreateWeakReferenceHandle(entryPointInfo));
  1137. }
  1138. #if DBG
  1139. BOOL FunctionBody::IsInterpreterThunk() const
  1140. {
  1141. bool isInterpreterThunk = this->GetOriginalEntryPoint_Unchecked() == DefaultEntryThunk;
  1142. #if DYNAMIC_INTERPRETER_THUNK
  1143. bool isStaticInterpreterThunk = this->GetOriginalEntryPoint_Unchecked() == InterpreterStackFrame::StaticInterpreterThunk;
  1144. isInterpreterThunk = isInterpreterThunk || isStaticInterpreterThunk || IsDynamicInterpreterThunk();
  1145. #endif
  1146. return isInterpreterThunk;
  1147. }
  1148. BOOL FunctionBody::IsDynamicInterpreterThunk() const
  1149. {
  1150. #if DYNAMIC_INTERPRETER_THUNK
  1151. return this->GetScriptContext()->IsDynamicInterpreterThunk(this->GetOriginalEntryPoint_Unchecked());
  1152. #else
  1153. return FALSE;
  1154. #endif
  1155. }
  1156. #endif
  1157. FunctionEntryPointInfo * FunctionBody::TryGetEntryPointInfo(int index) const
  1158. {
  1159. // If we've already freed the recyclable data, we're shutting down the script context so skip clean up
  1160. if (this->entryPoints == nullptr) return 0;
  1161. Assert(index < this->entryPoints->Count());
  1162. FunctionEntryPointInfo* entryPoint = this->entryPoints->Item(index)->Get();
  1163. return entryPoint;
  1164. }
  1165. FunctionEntryPointInfo * FunctionBody::GetEntryPointInfo(int index) const
  1166. {
  1167. FunctionEntryPointInfo* entryPoint = TryGetEntryPointInfo(index);
  1168. Assert(entryPoint);
  1169. return entryPoint;
  1170. }
  1171. #if ENABLE_NATIVE_CODEGEN
  1172. uint32 FunctionBody::GetFrameHeight(EntryPointInfo* entryPointInfo) const
  1173. {
  1174. return entryPointInfo->GetNativeEntryPointData()->GetFrameHeight();
  1175. }
  1176. void
  1177. FunctionBody::SetNativeThrowSpanSequence(SmallSpanSequence *seq, uint loopNum, LoopEntryPointInfo* entryPoint)
  1178. {
  1179. Assert(loopNum != LoopHeader::NoLoop);
  1180. LoopHeader *loopHeader = this->GetLoopHeaderWithLock(loopNum);
  1181. Assert(loopHeader);
  1182. Assert(entryPoint->loopHeader == loopHeader);
  1183. entryPoint->SetNativeThrowSpanSequence(seq);
  1184. }
  1185. void
  1186. FunctionBody::RecordNativeThrowMap(SmallSpanSequenceIter& iter, uint32 nativeOffset, uint32 statementIndex, EntryPointInfo* entryPoint, uint loopNum)
  1187. {
  1188. SmallSpanSequence *pSpanSequence;
  1189. pSpanSequence = entryPoint->GetNativeThrowSpanSequence();
  1190. if (!pSpanSequence)
  1191. {
  1192. if (statementIndex == -1)
  1193. {
  1194. return; // No need to initialize native throw map for non-user code
  1195. }
  1196. pSpanSequence = HeapNew(SmallSpanSequence);
  1197. if (loopNum == LoopHeader::NoLoop)
  1198. {
  1199. ((FunctionEntryPointInfo*) entryPoint)->SetNativeThrowSpanSequence(pSpanSequence);
  1200. }
  1201. else
  1202. {
  1203. this->SetNativeThrowSpanSequence(pSpanSequence, loopNum, (LoopEntryPointInfo*) entryPoint);
  1204. }
  1205. }
  1206. else if (iter.accumulatedSourceBegin == static_cast<int>(statementIndex))
  1207. {
  1208. return; // Compress adjacent spans which share the same statementIndex
  1209. }
  1210. StatementData data;
  1211. data.sourceBegin = static_cast<int>(statementIndex); // sourceBegin represents statementIndex here
  1212. data.bytecodeBegin = static_cast<int>(nativeOffset); // bytecodeBegin represents nativeOffset here
  1213. pSpanSequence->RecordARange(iter, &data);
  1214. }
  1215. #endif
  1216. PropertyId
  1217. ParseableFunctionInfo::GetOrAddPropertyIdTracked(JsUtil::CharacterBuffer<WCHAR> const& propName)
  1218. {
  1219. const Js::PropertyRecord* propRecord = nullptr;
  1220. ScriptContext * scriptContext = this->m_scriptContext;
  1221. scriptContext->GetOrAddPropertyRecord(propName, &propRecord);
  1222. PropertyId propertyId = propRecord->GetPropertyId();
  1223. if (!scriptContext->IsTrackedPropertyId(propertyId))
  1224. {
  1225. this->m_utf8SourceInfo->GetBoundedPropertyRecordHashSet()->Item(propRecord);
  1226. }
  1227. return propertyId;
  1228. }
  1229. SmallSpanSequence::SmallSpanSequence()
  1230. : pStatementBuffer(nullptr),
  1231. pActualOffsetList(nullptr),
  1232. baseValue(0)
  1233. {
  1234. }
  1235. BOOL SmallSpanSequence::RecordARange(SmallSpanSequenceIter &iter, StatementData * data)
  1236. {
  1237. Assert(data);
  1238. if (!this->pStatementBuffer)
  1239. {
  1240. this->pStatementBuffer = JsUtil::GrowingUint32HeapArray::Create(4);
  1241. baseValue = data->sourceBegin;
  1242. Reset(iter);
  1243. }
  1244. SmallSpan span(0);
  1245. span.sourceBegin = GetDiff(data->sourceBegin, iter.accumulatedSourceBegin);
  1246. span.bytecodeBegin = GetDiff(data->bytecodeBegin, iter.accumulatedBytecodeBegin);
  1247. this->pStatementBuffer->Add((uint32)span);
  1248. // Update iterator for the next set
  1249. iter.accumulatedSourceBegin = data->sourceBegin;
  1250. iter.accumulatedBytecodeBegin = data->bytecodeBegin;
  1251. return TRUE;
  1252. }
  1253. // FunctionProxy methods
  1254. ScriptContext*
  1255. FunctionProxy::GetScriptContext() const
  1256. {
  1257. return m_scriptContext;
  1258. }
  1259. void FunctionProxy::Copy(FunctionProxy* other)
  1260. {
  1261. Assert(other);
  1262. other->SetIsTopLevel(this->m_isTopLevel);
  1263. if (this->IsPublicLibraryCode())
  1264. {
  1265. other->SetIsPublicLibraryCode();
  1266. }
  1267. if (this->IsJsBuiltInCode())
  1268. {
  1269. other->SetIsJsBuiltInCode();
  1270. }
  1271. #define CopyDeferParseField(field) other->field = this->field;
  1272. CopyDeferParseField(deferredPrototypeType);
  1273. CopyDeferParseField(undeferredFunctionType);
  1274. #undef CopyDeferParseField
  1275. }
  1276. void ParseableFunctionInfo::Copy(ParseableFunctionInfo * other)
  1277. {
  1278. __super::Copy(other);
  1279. #define CopyDeferParseField(field) other->field = this->field;
  1280. CopyDeferParseField(flags);
  1281. CopyDeferParseField(m_isDeclaration);
  1282. CopyDeferParseField(m_isAccessor);
  1283. CopyDeferParseField(m_isStrictMode);
  1284. CopyDeferParseField(m_isGlobalFunc);
  1285. CopyDeferParseField(m_doBackendArgumentsOptimization);
  1286. CopyDeferParseField(m_doScopeObjectCreation);
  1287. CopyDeferParseField(m_usesArgumentsObject);
  1288. CopyDeferParseField(m_isEval);
  1289. CopyDeferParseField(m_isDynamicFunction);
  1290. CopyDeferParseField(m_hasImplicitArgIns);
  1291. CopyDeferParseField(m_dontInline);
  1292. CopyDeferParseField(m_inParamCount);
  1293. CopyDeferParseField(m_grfscr);
  1294. other->SetScopeInfo(this->GetScopeInfo());
  1295. other->SetDeferredStubs(this->GetDeferredStubs());
  1296. CopyDeferParseField(m_utf8SourceHasBeenSet);
  1297. #if DBG
  1298. CopyDeferParseField(deferredParseNextFunctionId);
  1299. CopyDeferParseField(scopeObjectSize);
  1300. #endif
  1301. CopyDeferParseField(scopeSlotArraySize);
  1302. CopyDeferParseField(paramScopeSlotArraySize);
  1303. other->SetCachedSourceStringWeakRef(this->GetCachedSourceStringWeakRef());
  1304. CopyDeferParseField(m_isAsmjsMode);
  1305. CopyDeferParseField(m_isAsmJsFunction);
  1306. other->SetFunctionObjectTypeList(this->GetFunctionObjectTypeList());
  1307. PropertyId * propertyIds = this->GetPropertyIdsForScopeSlotArray();
  1308. if (propertyIds != nullptr)
  1309. {
  1310. other->SetPropertyIdsForScopeSlotArray(propertyIds, this->scopeSlotArraySize, this->paramScopeSlotArraySize);
  1311. }
  1312. CopyDeferParseField(m_sourceIndex);
  1313. CopyDeferParseField(m_cchStartOffset);
  1314. CopyDeferParseField(m_cchLength);
  1315. CopyDeferParseField(m_lineNumber);
  1316. CopyDeferParseField(m_columnNumber);
  1317. CopyDeferParseField(m_cbStartOffset);
  1318. CopyDeferParseField(m_cbLength);
  1319. this->CopyNestedArray(other);
  1320. #undef CopyDeferParseField
  1321. }
  1322. void ParseableFunctionInfo::Copy(FunctionBody* other)
  1323. {
  1324. this->Copy(static_cast<ParseableFunctionInfo*>(other));
  1325. other->CopySourceInfo(this);
  1326. }
  1327. void ParseableFunctionInfo::CopyNestedArray(ParseableFunctionInfo * other)
  1328. {
  1329. NestedArray * thisNestedArray = this->GetNestedArray();
  1330. NestedArray * otherNestedArray = other->GetNestedArray();
  1331. if (thisNestedArray == nullptr)
  1332. {
  1333. Assert(otherNestedArray == nullptr);
  1334. return;
  1335. }
  1336. Assert(otherNestedArray->nestedCount == thisNestedArray->nestedCount);
  1337. for (uint i = 0; i < thisNestedArray->nestedCount; i++)
  1338. {
  1339. otherNestedArray->functionInfoArray[i] = thisNestedArray->functionInfoArray[i];
  1340. }
  1341. }
  1342. // DeferDeserializeFunctionInfo methods
  1343. DeferDeserializeFunctionInfo::DeferDeserializeFunctionInfo(int nestedCount, LocalFunctionId functionId, ByteCodeCache* byteCodeCache, const byte* serializedFunction, Utf8SourceInfo* sourceInfo, ScriptContext* scriptContext, uint functionNumber, const char16* displayName, uint displayNameLength, uint displayShortNameOffset, NativeModule *nativeModule, FunctionInfo::Attributes attributes) :
  1344. FunctionProxy(scriptContext, sourceInfo, functionNumber),
  1345. m_cache(byteCodeCache),
  1346. m_functionBytes(serializedFunction),
  1347. m_displayName(nullptr),
  1348. m_displayNameLength(0),
  1349. m_nativeModule(nativeModule)
  1350. {
  1351. this->functionInfo = RecyclerNew(scriptContext->GetRecycler(), FunctionInfo, DefaultDeferredDeserializeThunk, (FunctionInfo::Attributes)(attributes | FunctionInfo::Attributes::DeferredDeserialize), functionId, this);
  1352. this->m_defaultEntryPointInfo = RecyclerNew(scriptContext->GetRecycler(), ProxyEntryPointInfo, DefaultDeferredDeserializeThunk);
  1353. PERF_COUNTER_INC(Code, DeferDeserializeFunctionProxy);
  1354. SetDisplayName(displayName, displayNameLength, displayShortNameOffset, FunctionProxy::SetDisplayNameFlagsDontCopy);
  1355. }
  1356. DeferDeserializeFunctionInfo* DeferDeserializeFunctionInfo::New(ScriptContext* scriptContext, int nestedCount, LocalFunctionId functionId, ByteCodeCache* byteCodeCache, const byte* serializedFunction, Utf8SourceInfo* sourceInfo, const char16* displayName, uint displayNameLength, uint displayShortNameOffset, NativeModule *nativeModule, FunctionInfo::Attributes attributes)
  1357. {
  1358. return RecyclerNewFinalized(scriptContext->GetRecycler(),
  1359. DeferDeserializeFunctionInfo,
  1360. nestedCount,
  1361. functionId,
  1362. byteCodeCache,
  1363. serializedFunction,
  1364. sourceInfo,
  1365. scriptContext,
  1366. scriptContext->GetThreadContext()->NewFunctionNumber(),
  1367. displayName,
  1368. displayNameLength,
  1369. displayShortNameOffset,
  1370. nativeModule,
  1371. attributes);
  1372. }
  1373. const char16*
  1374. DeferDeserializeFunctionInfo::GetDisplayName() const
  1375. {
  1376. return this->m_displayName;
  1377. }
  1378. // ParseableFunctionInfo methods
  1379. ParseableFunctionInfo::ParseableFunctionInfo(JavascriptMethod entryPoint, int nestedCount,
  1380. LocalFunctionId functionId, Utf8SourceInfo* sourceInfo, ScriptContext* scriptContext, uint functionNumber,
  1381. const char16* displayName, uint displayNameLength, uint displayShortNameOffset, FunctionInfo::Attributes attributes, FunctionBodyFlags flags) :
  1382. FunctionProxy(scriptContext, sourceInfo, functionNumber),
  1383. #if DYNAMIC_INTERPRETER_THUNK
  1384. m_dynamicInterpreterThunk(nullptr),
  1385. #endif
  1386. flags(flags),
  1387. m_hasBeenParsed(false),
  1388. m_isGlobalFunc(false),
  1389. m_isDeclaration(false),
  1390. m_isNamedFunctionExpression(false),
  1391. m_isNameIdentifierRef (true),
  1392. m_isStaticNameFunction(false),
  1393. m_doBackendArgumentsOptimization(true),
  1394. m_doScopeObjectCreation(true),
  1395. m_usesArgumentsObject(false),
  1396. m_isStrictMode(false),
  1397. m_isAsmjsMode(false),
  1398. m_dontInline(false),
  1399. m_hasImplicitArgIns(true),
  1400. m_grfscr(0),
  1401. m_inParamCount(0),
  1402. m_reportedInParamCount(0),
  1403. m_sourceIndex(Js::Constants::InvalidSourceIndex),
  1404. m_utf8SourceHasBeenSet(false),
  1405. m_cchLength(0),
  1406. m_cbLength(0),
  1407. m_cchStartOffset(0),
  1408. m_cbStartOffset(0),
  1409. m_lineNumber(0),
  1410. m_columnNumber(0),
  1411. m_isEval(false),
  1412. m_isDynamicFunction(false),
  1413. m_displayName(nullptr),
  1414. m_displayNameLength(0),
  1415. m_displayShortNameOffset(0),
  1416. scopeSlotArraySize(0),
  1417. paramScopeSlotArraySize(0),
  1418. m_reparsed(false),
  1419. m_isAsmJsFunction(false),
  1420. m_tag21(true),
  1421. m_isMethod(false)
  1422. #if DBG
  1423. ,m_wasEverAsmjsMode(false)
  1424. ,scopeObjectSize(0)
  1425. #endif
  1426. {
  1427. this->functionInfo = RecyclerNew(scriptContext->GetRecycler(), FunctionInfo, entryPoint, attributes, functionId, this);
  1428. if (nestedCount > 0)
  1429. {
  1430. nestedArray = RecyclerNewPlusZ(m_scriptContext->GetRecycler(),
  1431. nestedCount*sizeof(FunctionProxy*), NestedArray, nestedCount);
  1432. }
  1433. else
  1434. {
  1435. nestedArray = nullptr;
  1436. }
  1437. if ((attributes & Js::FunctionInfo::DeferredParse) == 0)
  1438. {
  1439. this->m_defaultEntryPointInfo = RecyclerNewFinalized(scriptContext->GetRecycler(),
  1440. FunctionEntryPointInfo, this, entryPoint, scriptContext->GetThreadContext());
  1441. }
  1442. else
  1443. {
  1444. this->m_defaultEntryPointInfo = RecyclerNew(scriptContext->GetRecycler(), ProxyEntryPointInfo, entryPoint);
  1445. }
  1446. SetDisplayName(displayName, displayNameLength, displayShortNameOffset);
  1447. this->SetOriginalEntryPoint(DefaultEntryThunk);
  1448. }
  1449. ParseableFunctionInfo::ParseableFunctionInfo(ParseableFunctionInfo * proxy) :
  1450. FunctionProxy(proxy->GetScriptContext(), proxy->GetUtf8SourceInfo(), proxy->GetFunctionNumber()),
  1451. #if DYNAMIC_INTERPRETER_THUNK
  1452. m_dynamicInterpreterThunk(nullptr),
  1453. #endif
  1454. m_hasBeenParsed(false),
  1455. m_isNamedFunctionExpression(proxy->GetIsNamedFunctionExpression()),
  1456. m_isNameIdentifierRef (proxy->GetIsNameIdentifierRef()),
  1457. m_isStaticNameFunction(proxy->GetIsStaticNameFunction()),
  1458. m_reportedInParamCount(proxy->GetReportedInParamsCount()),
  1459. m_reparsed(proxy->IsReparsed()),
  1460. m_isMethod(proxy->IsMethod()),
  1461. m_tag21(true)
  1462. #if DBG
  1463. , m_wasEverAsmjsMode(proxy->m_wasEverAsmjsMode)
  1464. #endif
  1465. {
  1466. FunctionInfo * functionInfo = proxy->GetFunctionInfo();
  1467. this->functionInfo = functionInfo;
  1468. uint nestedCount = proxy->GetNestedCount();
  1469. if (nestedCount > 0)
  1470. {
  1471. nestedArray = RecyclerNewPlusZ(m_scriptContext->GetRecycler(),
  1472. nestedCount*sizeof(FunctionProxy*), NestedArray, nestedCount);
  1473. }
  1474. else
  1475. {
  1476. nestedArray = nullptr;
  1477. }
  1478. proxy->Copy(this);
  1479. SetDisplayName(proxy->GetDisplayName(), proxy->GetDisplayNameLength(), proxy->GetShortDisplayNameOffset());
  1480. }
  1481. ParseableFunctionInfo* ParseableFunctionInfo::New(ScriptContext* scriptContext, int nestedCount,
  1482. LocalFunctionId functionId, Utf8SourceInfo* sourceInfo, const char16* displayName, uint displayNameLength, uint displayShortNameOffset, FunctionInfo::Attributes attributes, FunctionBodyFlags flags)
  1483. {
  1484. #if defined(ENABLE_SCRIPT_PROFILING) || defined(ENABLE_SCRIPT_DEBUGGING)
  1485. Assert(
  1486. scriptContext->DeferredParsingThunk == ProfileDeferredParsingThunk ||
  1487. scriptContext->DeferredParsingThunk == DefaultDeferredParsingThunk);
  1488. #else
  1489. Assert(scriptContext->DeferredParsingThunk == DefaultDeferredParsingThunk);
  1490. #endif
  1491. #ifdef PERF_COUNTERS
  1492. PERF_COUNTER_INC(Code, DeferredFunction);
  1493. #endif
  1494. uint newFunctionNumber = scriptContext->GetThreadContext()->NewFunctionNumber();
  1495. if (!sourceInfo->GetSourceContextInfo()->IsDynamic())
  1496. {
  1497. PHASE_PRINT_TESTTRACE1(Js::DeferParsePhase, _u("Function was deferred from parsing - ID: %d; Display Name: %s; Utf8SourceInfo ID: %d; Source Length: %d; Source Url:%s\n"), newFunctionNumber, displayName, sourceInfo->GetSourceInfoId(), sourceInfo->GetCchLength(), sourceInfo->GetSourceContextInfo()->url);
  1498. }
  1499. else
  1500. {
  1501. PHASE_PRINT_TESTTRACE1(Js::DeferParsePhase, _u("Function was deferred from parsing - ID: %d; Display Name: %s; Utf8SourceInfo ID: %d; Source Length: %d;\n"), newFunctionNumber, displayName, sourceInfo->GetSourceInfoId(), sourceInfo->GetCchLength());
  1502. }
  1503. // When generating a new defer parse function, we always use a new function number
  1504. return RecyclerNewWithBarrierFinalized(scriptContext->GetRecycler(),
  1505. ParseableFunctionInfo,
  1506. scriptContext->DeferredParsingThunk,
  1507. nestedCount,
  1508. functionId,
  1509. sourceInfo,
  1510. scriptContext,
  1511. newFunctionNumber,
  1512. displayName,
  1513. displayNameLength,
  1514. displayShortNameOffset,
  1515. (FunctionInfo::Attributes)(attributes | FunctionInfo::Attributes::DeferredParse),
  1516. flags);
  1517. }
  1518. ParseableFunctionInfo *
  1519. ParseableFunctionInfo::NewDeferredFunctionFromFunctionBody(FunctionBody * functionBody)
  1520. {
  1521. ScriptContext * scriptContext = functionBody->GetScriptContext();
  1522. uint nestedCount = functionBody->GetNestedCount();
  1523. ParseableFunctionInfo * info = RecyclerNewWithBarrierFinalized(scriptContext->GetRecycler(),
  1524. ParseableFunctionInfo,
  1525. functionBody);
  1526. // Create new entry point info
  1527. info->m_defaultEntryPointInfo = RecyclerNew(scriptContext->GetRecycler(), ProxyEntryPointInfo, scriptContext->DeferredParsingThunk);
  1528. // Initialize nested function array, update back pointers
  1529. for (uint i = 0; i < nestedCount; i++)
  1530. {
  1531. FunctionInfo * nestedInfo = functionBody->GetNestedFunc(i);
  1532. info->SetNestedFunc(nestedInfo, i, 0);
  1533. }
  1534. // Update function objects
  1535. return info;
  1536. }
  1537. DWORD_PTR FunctionProxy::GetSecondaryHostSourceContext() const
  1538. {
  1539. return this->GetUtf8SourceInfo()->GetSecondaryHostSourceContext();
  1540. }
  1541. DWORD_PTR FunctionProxy::GetHostSourceContext() const
  1542. {
  1543. return this->GetSourceContextInfo()->dwHostSourceContext;
  1544. }
  1545. SourceContextInfo * FunctionProxy::GetSourceContextInfo() const
  1546. {
  1547. return this->GetHostSrcInfo()->sourceContextInfo;
  1548. }
  1549. SRCINFO const * FunctionProxy::GetHostSrcInfo() const
  1550. {
  1551. return this->GetUtf8SourceInfo()->GetSrcInfo();
  1552. }
  1553. //
  1554. // Returns the start line for the script buffer (code buffer for the entire script tag) of this current function.
  1555. // We subtract the lnMinHost because it is the number of lines we have added to augment scriptlets passed through
  1556. // ParseProcedureText to have a function name.
  1557. //
  1558. ULONG FunctionProxy::GetHostStartLine() const
  1559. {
  1560. return this->GetHostSrcInfo()->dlnHost - this->GetHostSrcInfo()->lnMinHost;
  1561. }
  1562. //
  1563. // Returns the start column of the first line for the script buffer of this current function.
  1564. //
  1565. ULONG FunctionProxy::GetHostStartColumn() const
  1566. {
  1567. return this->GetHostSrcInfo()->ulColumnHost;
  1568. }
  1569. //
  1570. // Returns line number in unmodified host buffer (i.e. without extra scriptlet code added by ParseProcedureText --
  1571. // when e.g. we add extra code for event handlers, such as "function onclick(event)\n{\n").
  1572. //
  1573. ULONG FunctionProxy::GetLineNumberInHostBuffer(ULONG relativeLineNumber) const
  1574. {
  1575. ULONG lineNumber = relativeLineNumber;
  1576. if (lineNumber >= this->GetHostSrcInfo()->lnMinHost)
  1577. {
  1578. lineNumber -= this->GetHostSrcInfo()->lnMinHost;
  1579. }
  1580. // Note that '<' is still a valid case -- that would be the case for onclick scriptlet function itself (lineNumber == 0).
  1581. return lineNumber;
  1582. }
  1583. ULONG FunctionProxy::ComputeAbsoluteLineNumber(ULONG relativeLineNumber) const
  1584. {
  1585. // We add 1 because the line numbers start from 0.
  1586. return this->GetHostSrcInfo()->dlnHost + GetLineNumberInHostBuffer(relativeLineNumber) + 1;
  1587. }
  1588. ULONG FunctionProxy::ComputeAbsoluteColumnNumber(ULONG relativeLineNumber, ULONG relativeColumnNumber) const
  1589. {
  1590. if (this->GetLineNumberInHostBuffer(relativeLineNumber) == 0)
  1591. {
  1592. // The host column matters only for the first line.
  1593. return this->GetHostStartColumn() + relativeColumnNumber + 1;
  1594. }
  1595. // We add 1 because the column numbers start from 0.
  1596. return relativeColumnNumber + 1;
  1597. }
  1598. //
  1599. // Returns the line number of the function declaration in the source file.
  1600. //
  1601. ULONG
  1602. ParseableFunctionInfo::GetLineNumber() const
  1603. {
  1604. return this->ComputeAbsoluteLineNumber(this->m_lineNumber);
  1605. }
  1606. //
  1607. // Returns the column number of the function declaration in the source file.
  1608. //
  1609. ULONG
  1610. ParseableFunctionInfo::GetColumnNumber() const
  1611. {
  1612. return ComputeAbsoluteColumnNumber(this->m_lineNumber, m_columnNumber);
  1613. }
  1614. LPCWSTR
  1615. ParseableFunctionInfo::GetSourceName() const
  1616. {
  1617. return GetSourceName(this->GetSourceContextInfo());
  1618. }
  1619. void
  1620. ParseableFunctionInfo::SetGrfscr(uint32 grfscr)
  1621. {
  1622. this->m_grfscr = grfscr;
  1623. }
  1624. uint32
  1625. ParseableFunctionInfo::GetGrfscr() const
  1626. {
  1627. return this->m_grfscr;
  1628. }
  1629. ProxyEntryPointInfo*
  1630. FunctionProxy::GetDefaultEntryPointInfo() const
  1631. {
  1632. return this->m_defaultEntryPointInfo;
  1633. }
  1634. FunctionEntryPointInfo*
  1635. FunctionBody::GetDefaultFunctionEntryPointInfo() const
  1636. {
  1637. Assert(((ProxyEntryPointInfo*) this->defaultFunctionEntryPointInfo) == this->m_defaultEntryPointInfo);
  1638. return this->defaultFunctionEntryPointInfo;
  1639. }
  1640. void
  1641. ParseableFunctionInfo::SetInParamsCount(ArgSlot newInParamCount)
  1642. {
  1643. AssertMsg(m_inParamCount <= newInParamCount, "Cannot shrink register usage");
  1644. m_inParamCount = newInParamCount;
  1645. if (newInParamCount <= 1)
  1646. {
  1647. SetHasImplicitArgIns(false);
  1648. }
  1649. }
  1650. ArgSlot
  1651. ParseableFunctionInfo::GetReportedInParamsCount() const
  1652. {
  1653. return m_reportedInParamCount;
  1654. }
  1655. void
  1656. ParseableFunctionInfo::SetReportedInParamsCount(ArgSlot newInParamCount)
  1657. {
  1658. AssertMsg(m_reportedInParamCount <= newInParamCount, "Cannot shrink register usage");
  1659. m_reportedInParamCount = newInParamCount;
  1660. }
  1661. void
  1662. ParseableFunctionInfo::ResetInParams()
  1663. {
  1664. m_inParamCount = 0;
  1665. m_reportedInParamCount = 0;
  1666. }
  1667. const char16*
  1668. ParseableFunctionInfo::GetDisplayName() const
  1669. {
  1670. return this->m_displayName;
  1671. }
  1672. void ParseableFunctionInfo::BuildDeferredStubs(ParseNodeFnc *pnodeFnc)
  1673. {
  1674. DeferredFunctionStub* deferredStubs = Parser::BuildDeferredStubTree(pnodeFnc, m_scriptContext->GetRecycler());
  1675. this->SetDeferredStubs(deferredStubs);
  1676. }
  1677. JavascriptString * ParseableFunctionInfo::GetCachedSourceString()
  1678. {
  1679. RecyclerWeakReference<JavascriptString> * weakRef = GetCachedSourceStringWeakRef();
  1680. if (weakRef)
  1681. {
  1682. JavascriptString * string = weakRef->Get();
  1683. if (string)
  1684. {
  1685. return string;
  1686. }
  1687. this->SetAuxPtr<AuxPointerType::CachedSourceString>(nullptr);
  1688. }
  1689. return nullptr;
  1690. }
  1691. void ParseableFunctionInfo::SetCachedSourceString(JavascriptString * sourceString)
  1692. {
  1693. Assert(this->GetCachedSourceString() == nullptr);
  1694. if (sourceString)
  1695. {
  1696. this->SetCachedSourceStringWeakRef(this->GetRecycler()->CreateWeakReferenceHandle(sourceString));
  1697. }
  1698. }
  1699. RecyclerWeakReference<JavascriptString> * ParseableFunctionInfo::GetCachedSourceStringWeakRef()
  1700. {
  1701. return this->GetAuxPtr<AuxPointerType::CachedSourceString>();
  1702. }
  1703. void ParseableFunctionInfo::SetCachedSourceStringWeakRef(RecyclerWeakReference<JavascriptString> * weakRef)
  1704. {
  1705. Assert(this->GetCachedSourceString() == nullptr);
  1706. this->SetAuxPtr<AuxPointerType::CachedSourceString>(weakRef);
  1707. }
  1708. FunctionInfoArray ParseableFunctionInfo::GetNestedFuncArray()
  1709. {
  1710. Assert(GetNestedArray() != nullptr);
  1711. return GetNestedArray()->functionInfoArray;
  1712. }
  1713. void ParseableFunctionInfo::SetNestedFunc(FunctionInfo* nestedFunc, uint index, uint32 flags)
  1714. {
  1715. AssertMsg(index < this->GetNestedCount(), "Trying to write past the nested func array");
  1716. FunctionInfoArray nested = this->GetNestedFuncArray();
  1717. nested[index] = nestedFunc;
  1718. }
  1719. FunctionInfo* ParseableFunctionInfo::GetNestedFunc(uint index)
  1720. {
  1721. return *(GetNestedFuncReference(index));
  1722. }
  1723. FunctionProxy* ParseableFunctionInfo::GetNestedFunctionProxy(uint index)
  1724. {
  1725. FunctionInfo *info = GetNestedFunc(index);
  1726. return info ? info->GetFunctionProxy() : nullptr;
  1727. }
  1728. FunctionInfoPtrPtr ParseableFunctionInfo::GetNestedFuncReference(uint index)
  1729. {
  1730. AssertMsg(index < this->GetNestedCount(), "Trying to write past the nested func array");
  1731. FunctionInfoArray nested = this->GetNestedFuncArray();
  1732. return &nested[index];
  1733. }
  1734. ParseableFunctionInfo* ParseableFunctionInfo::GetNestedFunctionForExecution(uint index)
  1735. {
  1736. FunctionInfo* currentNestedFunction = this->GetNestedFunc(index);
  1737. Assert(currentNestedFunction);
  1738. if (currentNestedFunction->IsDeferredDeserializeFunction())
  1739. {
  1740. currentNestedFunction->GetFunctionProxy()->EnsureDeserialized();
  1741. }
  1742. return currentNestedFunction->GetParseableFunctionInfo();
  1743. }
  1744. void
  1745. FunctionProxy::UpdateFunctionBodyImpl(FunctionBody * body)
  1746. {
  1747. FunctionInfo *functionInfo = this->GetFunctionInfo();
  1748. Assert(functionInfo->GetFunctionProxy() == this);
  1749. Assert(!this->IsFunctionBody() || body == this);
  1750. functionInfo->SetFunctionProxy(body);
  1751. body->SetFunctionInfo(functionInfo);
  1752. body->SetAttributes((FunctionInfo::Attributes)(functionInfo->GetAttributes() & ~(FunctionInfo::Attributes::DeferredParse | FunctionInfo::Attributes::DeferredDeserialize)));
  1753. }
  1754. //
  1755. // This method gets a function body for the purposes of execution
  1756. // It has an if within it to avoid making it a virtual- it's called from the interpreter
  1757. // It will cause the function info to get deserialized if it hasn't been deserialized
  1758. // already
  1759. //
  1760. ParseableFunctionInfo * FunctionProxy::EnsureDeserialized()
  1761. {
  1762. Assert(this == this->GetFunctionInfo()->GetFunctionProxy());
  1763. FunctionProxy * executionFunctionBody = this;
  1764. if (IsDeferredDeserializeFunction())
  1765. {
  1766. // No need to deserialize function body if scriptContext closed because we can't execute it.
  1767. // Bigger problem is the script engine might have released bytecode file mapping and we can't deserialize.
  1768. Assert(!m_scriptContext->IsClosed());
  1769. executionFunctionBody = ((DeferDeserializeFunctionInfo*) this)->Deserialize();
  1770. this->GetFunctionInfo()->SetFunctionProxy(executionFunctionBody);
  1771. Assert(executionFunctionBody->GetFunctionInfo()->HasBody());
  1772. Assert(executionFunctionBody != this);
  1773. }
  1774. return (ParseableFunctionInfo *)executionFunctionBody;
  1775. }
  1776. ScriptFunctionType * FunctionProxy::GetDeferredPrototypeType() const
  1777. {
  1778. return deferredPrototypeType;
  1779. }
  1780. ScriptFunctionType * FunctionProxy::EnsureDeferredPrototypeType()
  1781. {
  1782. Assert(this->GetFunctionInfo()->GetFunctionProxy() == this);
  1783. return deferredPrototypeType != nullptr ?
  1784. static_cast<ScriptFunctionType*>(deferredPrototypeType) : AllocDeferredPrototypeType();
  1785. }
  1786. ScriptFunctionType * FunctionProxy::AllocDeferredPrototypeType()
  1787. {
  1788. Assert(deferredPrototypeType == nullptr);
  1789. ScriptFunctionType * type = ScriptFunctionType::New(this, true);
  1790. deferredPrototypeType = type;
  1791. return type;
  1792. }
  1793. ScriptFunctionType * FunctionProxy::GetUndeferredFunctionType() const
  1794. {
  1795. return undeferredFunctionType;
  1796. }
  1797. void FunctionProxy::SetUndeferredFunctionType(ScriptFunctionType * type)
  1798. {
  1799. undeferredFunctionType = type;
  1800. }
  1801. JavascriptMethod FunctionProxy::GetDirectEntryPoint(ProxyEntryPointInfo* entryPoint) const
  1802. {
  1803. Assert(entryPoint->jsMethod != nullptr);
  1804. return entryPoint->jsMethod;
  1805. }
  1806. // Function object type list methods
  1807. FunctionProxy::FunctionTypeWeakRefList* FunctionProxy::GetFunctionObjectTypeList() const
  1808. {
  1809. return this->GetAuxPtr<AuxPointerType::FunctionObjectTypeList>();
  1810. }
  1811. void FunctionProxy::SetFunctionObjectTypeList(FunctionProxy::FunctionTypeWeakRefList* list)
  1812. {
  1813. this->SetAuxPtr<AuxPointerType::FunctionObjectTypeList>(list);
  1814. }
  1815. template <typename Fn>
  1816. void FunctionProxy::MapFunctionObjectTypes(Fn func)
  1817. {
  1818. FunctionTypeWeakRefList* functionObjectTypeList = this->GetFunctionObjectTypeList();
  1819. if (functionObjectTypeList != nullptr)
  1820. {
  1821. functionObjectTypeList->Map([&](int, FunctionTypeWeakRef* typeWeakRef)
  1822. {
  1823. if (typeWeakRef)
  1824. {
  1825. ScriptFunctionType* type = typeWeakRef->Get();
  1826. if (type)
  1827. {
  1828. func(type);
  1829. }
  1830. }
  1831. });
  1832. }
  1833. if (this->deferredPrototypeType)
  1834. {
  1835. func(this->deferredPrototypeType);
  1836. }
  1837. // NOTE: We deliberately do not map the undeferredFunctionType here, since it's in the list
  1838. // of registered function object types we processed above.
  1839. }
  1840. FunctionProxy::FunctionTypeWeakRefList* FunctionProxy::EnsureFunctionObjectTypeList()
  1841. {
  1842. FunctionTypeWeakRefList* functionObjectTypeList = this->GetFunctionObjectTypeList();
  1843. if (functionObjectTypeList == nullptr)
  1844. {
  1845. Recycler* recycler = this->GetScriptContext()->GetRecycler();
  1846. functionObjectTypeList = RecyclerNew(recycler, FunctionTypeWeakRefList, recycler);
  1847. this->SetFunctionObjectTypeList(functionObjectTypeList);
  1848. }
  1849. return functionObjectTypeList;
  1850. }
  1851. void FunctionProxy::RegisterFunctionObjectType(ScriptFunctionType* functionType)
  1852. {
  1853. FunctionTypeWeakRefList* typeList = EnsureFunctionObjectTypeList();
  1854. Assert(functionType != deferredPrototypeType);
  1855. Recycler * recycler = this->GetScriptContext()->GetRecycler();
  1856. FunctionTypeWeakRef* weakRef = recycler->CreateWeakReferenceHandle(functionType);
  1857. typeList->SetAtFirstFreeSpot(weakRef);
  1858. OUTPUT_TRACE(Js::ExpirableCollectPhase, _u("Registered type 0x%p on function body %p, count = %d\n"), functionType, this, typeList->Count());
  1859. }
  1860. void DeferDeserializeFunctionInfo::SetDisplayName(const char16* displayName)
  1861. {
  1862. size_t len = wcslen(displayName);
  1863. if (len > UINT_MAX)
  1864. {
  1865. // Can't support display name that big
  1866. Js::Throw::OutOfMemory();
  1867. }
  1868. SetDisplayName(displayName, (uint)len, 0);
  1869. }
  1870. void DeferDeserializeFunctionInfo::SetDisplayName(const char16* pszDisplayName, uint displayNameLength, uint displayShortNameOffset, SetDisplayNameFlags flags /* default to None */)
  1871. {
  1872. this->m_displayNameLength = displayNameLength;
  1873. this->m_displayShortNameOffset = displayShortNameOffset;
  1874. this->m_displayNameIsRecyclerAllocated = FunctionProxy::SetDisplayName(pszDisplayName, &this->m_displayName, displayNameLength, m_scriptContext, flags);
  1875. }
  1876. LPCWSTR DeferDeserializeFunctionInfo::GetSourceInfo(int& lineNumber, int& columnNumber) const
  1877. {
  1878. // Read all the necessary information from the serialized byte code
  1879. int lineNumberField, columnNumberField;
  1880. bool m_isEval, m_isDynamicFunction;
  1881. ByteCodeSerializer::ReadSourceInfo(this, lineNumberField, columnNumberField, m_isEval, m_isDynamicFunction);
  1882. // Decode them
  1883. lineNumber = ComputeAbsoluteLineNumber(lineNumberField);
  1884. columnNumber = ComputeAbsoluteColumnNumber(lineNumberField, columnNumberField);
  1885. return Js::ParseableFunctionInfo::GetSourceName<SourceContextInfo*>(this->GetSourceContextInfo(), m_isEval, m_isDynamicFunction);
  1886. }
  1887. void DeferDeserializeFunctionInfo::Finalize(bool isShutdown)
  1888. {
  1889. __super::Finalize(isShutdown);
  1890. PERF_COUNTER_DEC(Code, DeferDeserializeFunctionProxy);
  1891. }
  1892. FunctionBody* DeferDeserializeFunctionInfo::Deserialize()
  1893. {
  1894. Assert(this->GetFunctionInfo()->GetFunctionProxy() == this);
  1895. FunctionBody * body = ByteCodeSerializer::DeserializeFunction(this->m_scriptContext, this);
  1896. this->SetLocalFunctionId(body->GetLocalFunctionId());
  1897. this->SetOriginalEntryPoint(body->GetOriginalEntryPoint());
  1898. this->Copy(body);
  1899. this->UpdateFunctionBodyImpl(body);
  1900. Assert(body->GetFunctionBody() == body);
  1901. return body;
  1902. }
  1903. //
  1904. // hrParse can be one of the following from deferred re-parse (check CompileScriptException::ProcessError):
  1905. // E_OUTOFMEMORY
  1906. // E_UNEXPECTED
  1907. // SCRIPT_E_RECORDED,
  1908. // with ei.scode: ERRnoMemory, VBSERR_OutOfStack, E_OUTOFMEMORY, E_FAIL, E_ABORT
  1909. // Any other ei.scode shouldn't appear in deferred re-parse.
  1910. //
  1911. // Map errors like OOM/SOE, return it and clean hrParse. Any other error remaining in hrParse is an internal error.
  1912. //
  1913. HRESULT ParseableFunctionInfo::MapDeferredReparseError(HRESULT& hrParse, const CompileScriptException& se)
  1914. {
  1915. HRESULT hrMapped = NO_ERROR;
  1916. switch (hrParse)
  1917. {
  1918. case E_OUTOFMEMORY:
  1919. hrMapped = E_OUTOFMEMORY;
  1920. break;
  1921. case SCRIPT_E_RECORDED:
  1922. switch (se.ei.scode)
  1923. {
  1924. case ERRnoMemory:
  1925. case E_OUTOFMEMORY:
  1926. case VBSERR_OutOfMemory:
  1927. hrMapped = E_OUTOFMEMORY;
  1928. break;
  1929. case VBSERR_OutOfStack:
  1930. hrMapped = VBSERR_OutOfStack;
  1931. break;
  1932. case JSERR_AsmJsCompileError:
  1933. hrMapped = JSERR_AsmJsCompileError;
  1934. break;
  1935. case E_ABORT:
  1936. hrMapped = E_ABORT;
  1937. break;
  1938. }
  1939. }
  1940. if (FAILED(hrMapped))
  1941. {
  1942. // If we have mapped error, clear hrParse. We'll throw error from hrMapped.
  1943. hrParse = NO_ERROR;
  1944. }
  1945. return hrMapped;
  1946. }
  1947. FunctionBody* ParseableFunctionInfo::Parse(ScriptFunction ** functionRef, bool isByteCodeDeserialization)
  1948. {
  1949. Assert(this == this->GetFunctionInfo()->GetFunctionProxy());
  1950. if (!IsDeferredParseFunction())
  1951. {
  1952. // If not deferredparsed, the functionBodyImpl and this will be the same, just return the current functionBody.
  1953. Assert(GetFunctionBody()->IsFunctionParsed());
  1954. return GetFunctionBody();
  1955. }
  1956. bool asmjsParseFailed = false;
  1957. BOOL fParsed = FALSE;
  1958. FunctionBody* returnFunctionBody = nullptr;
  1959. bool isDebugOrAsmJsReparse = false;
  1960. FunctionBody* funcBody = nullptr;
  1961. {
  1962. AutoRestoreFunctionInfo autoRestoreFunctionInfo(this, DefaultEntryThunk);
  1963. // If m_hasBeenParsed = true, one of the following things happened things happened:
  1964. // - We had multiple function objects which were all defer-parsed, but with the same function body and one of them
  1965. // got the body to be parsed before another was called
  1966. // - We are in debug mode and had our thunks switched to DeferParseThunk
  1967. // - This is an already parsed asm.js module, which has been invalidated at link time and must be reparsed as a non-asm.js function
  1968. if (!this->m_hasBeenParsed)
  1969. {
  1970. this->GetUtf8SourceInfo()->StopTrackingDeferredFunction(this->GetLocalFunctionId());
  1971. funcBody = FunctionBody::NewFromParseableFunctionInfo(this);
  1972. autoRestoreFunctionInfo.funcBody = funcBody;
  1973. PERF_COUNTER_DEC(Code, DeferredFunction);
  1974. if (!this->GetSourceContextInfo()->IsDynamic())
  1975. {
  1976. PHASE_PRINT_TESTTRACE1(Js::DeferParsePhase, _u("TestTrace: Deferred function parsed - ID: %d; Display Name: %s; Length: %d; Nested Function Count: %d; Utf8SourceInfo: %d; Source Length: %d; Is Top Level: %s; Source Url: %s\n"), m_functionNumber, this->GetDisplayName(), this->m_cchLength, this->GetNestedCount(), this->m_utf8SourceInfo->GetSourceInfoId(), this->m_utf8SourceInfo->GetCchLength(), this->GetIsTopLevel() ? _u("True") : _u("False"), this->GetSourceContextInfo()->url);
  1977. }
  1978. else
  1979. {
  1980. PHASE_PRINT_TESTTRACE1(Js::DeferParsePhase, _u("TestTrace: Deferred function parsed - ID: %d; Display Name: %s; Length: %d; Nested Function Count: %d; Utf8SourceInfo: %d; Source Length: %d\n; Is Top Level: %s;"), m_functionNumber, this->GetDisplayName(), this->m_cchLength, this->GetNestedCount(), this->m_utf8SourceInfo->GetSourceInfoId(), this->m_utf8SourceInfo->GetCchLength(), this->GetIsTopLevel() ? _u("True") : _u("False"));
  1981. }
  1982. if (!this->GetIsTopLevel() &&
  1983. !this->GetSourceContextInfo()->IsDynamic() &&
  1984. this->m_scriptContext->DoUndeferGlobalFunctions())
  1985. {
  1986. this->GetUtf8SourceInfo()->UndeferGlobalFunctions([this](const Utf8SourceInfo::DeferredFunctionsDictionary::EntryType& func)
  1987. {
  1988. Js::ParseableFunctionInfo *nextFunc = func.Value();
  1989. JavascriptExceptionObject* pExceptionObject = nullptr;
  1990. if (nextFunc != nullptr && this != nextFunc)
  1991. {
  1992. try
  1993. {
  1994. nextFunc->Parse();
  1995. }
  1996. catch (OutOfMemoryException) {}
  1997. catch (StackOverflowException) {}
  1998. catch (const Js::JavascriptException& err)
  1999. {
  2000. pExceptionObject = err.GetAndClear();
  2001. }
  2002. // Do not do anything with an OOM or SOE, returning true is fine, it will then be undeferred (or attempted to again when called)
  2003. if (pExceptionObject)
  2004. {
  2005. if (pExceptionObject != ThreadContext::GetContextForCurrentThread()->GetPendingOOMErrorObject() &&
  2006. pExceptionObject != ThreadContext::GetContextForCurrentThread()->GetPendingSOErrorObject())
  2007. {
  2008. JavascriptExceptionOperators::DoThrow(pExceptionObject, /*scriptContext*/nullptr);
  2009. }
  2010. }
  2011. }
  2012. return true;
  2013. });
  2014. }
  2015. }
  2016. else
  2017. {
  2018. bool isDebugReparse = m_scriptContext->IsScriptContextInSourceRundownOrDebugMode() && !this->GetUtf8SourceInfo()->GetIsLibraryCode();
  2019. bool isAsmJsReparse = m_isAsmjsMode && !isDebugReparse;
  2020. isDebugOrAsmJsReparse = isAsmJsReparse || isDebugReparse;
  2021. funcBody = this->GetFunctionBody();
  2022. // As we have a valid function body already clear the restore data
  2023. autoRestoreFunctionInfo.Clear();
  2024. if (isDebugOrAsmJsReparse)
  2025. {
  2026. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2027. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2028. #endif
  2029. #if DBG
  2030. Assert(
  2031. funcBody->IsReparsed()
  2032. || m_scriptContext->IsScriptContextInSourceRundownOrDebugMode()
  2033. || m_isAsmjsMode);
  2034. #endif
  2035. OUTPUT_TRACE(Js::DebuggerPhase, _u("Full nested reparse of function: %s (%s)\n"), funcBody->GetDisplayName(), funcBody->GetDebugNumberSet(debugStringBuffer));
  2036. if (funcBody->GetByteCode())
  2037. {
  2038. // The current function needs to be cleaned up before getting generated in the debug mode.
  2039. funcBody->CleanupToReparse();
  2040. }
  2041. }
  2042. }
  2043. // Note that we may be trying to re-gen an already-completed function. (This can happen, for instance,
  2044. // in the case of named function expressions inside "with" statements in compat mode.)
  2045. // In such a case, there's no work to do.
  2046. if (funcBody->GetByteCode() == nullptr)
  2047. {
  2048. #if ENABLE_PROFILE_INFO
  2049. Assert(!funcBody->HasExecutionDynamicProfileInfo());
  2050. #endif
  2051. // In debug or asm.js mode, the scriptlet will be asked to recompile again.
  2052. HRESULT hr = NO_ERROR;
  2053. HRESULT hrParser = NO_ERROR;
  2054. HRESULT hrParseCodeGen = NO_ERROR;
  2055. BEGIN_LEAVE_SCRIPT_INTERNAL(m_scriptContext)
  2056. {
  2057. bool isCesu8 = m_scriptContext->GetSource(funcBody->GetSourceIndex())->IsCesu8();
  2058. size_t offset = this->StartOffset();
  2059. charcount_t charOffset = this->StartInDocument();
  2060. size_t length = this->LengthInBytes();
  2061. LPCUTF8 pszStart = this->GetStartOfDocument();
  2062. uint32 grfscr = funcBody->GetGrfscr() | fscrDeferredFnc;
  2063. // For the global function we want to re-use the glo functionbody which is already created in the non-debug mode
  2064. if (!funcBody->GetIsGlobalFunc())
  2065. {
  2066. grfscr &= ~fscrGlobalCode;
  2067. }
  2068. if (!funcBody->GetIsDeclaration() && !funcBody->GetIsGlobalFunc()) // No refresh may reparse global function (e.g. eval code)
  2069. {
  2070. // Notify the parser that the top-level function was defined in an expression,
  2071. // (not a function declaration statement).
  2072. grfscr |= fscrDeferredFncExpression;
  2073. }
  2074. if (funcBody->IsMethod())
  2075. {
  2076. grfscr |= fscrDeferredFncIsMethod;
  2077. }
  2078. else
  2079. {
  2080. grfscr &= ~fscrDeferredFncIsMethod;
  2081. }
  2082. if (isDebugOrAsmJsReparse)
  2083. {
  2084. grfscr &= ~fscrWillDeferFncParse; // Disable deferred parsing if not DeferNested, or doing a debug/asm.js re-parse
  2085. }
  2086. if (isDebugOrAsmJsReparse)
  2087. {
  2088. grfscr |= fscrNoAsmJs; // Disable asm.js when debugging or if linking failed
  2089. }
  2090. if (isDebugOrAsmJsReparse)
  2091. {
  2092. grfscr &= ~fscrCreateParserState; // Disable parser state cache if we're debugging or reparsing asm.js
  2093. }
  2094. BEGIN_TRANSLATE_EXCEPTION_TO_HRESULT
  2095. {
  2096. CompileScriptException se;
  2097. Parser ps(m_scriptContext, funcBody->GetIsStrictMode() ? TRUE : FALSE);
  2098. ParseNodeProg * parseTree = nullptr;
  2099. uint nextFunctionId = funcBody->GetLocalFunctionId();
  2100. hrParser = ps.ParseSourceWithOffset(&parseTree, pszStart, offset, length, charOffset, isCesu8, grfscr, &se,
  2101. &nextFunctionId, funcBody->GetRelativeLineNumber(), funcBody->GetSourceContextInfo(),
  2102. funcBody);
  2103. // Assert(FAILED(hrParser) || nextFunctionId == funcBody->deferredParseNextFunctionId || isDebugOrAsmJsReparse || isByteCodeDeserialization);
  2104. if (FAILED(hrParser))
  2105. {
  2106. hrParseCodeGen = MapDeferredReparseError(hrParser, se); // Map certain errors like OOM/SOE
  2107. AssertMsg(hrParseCodeGen == JSERR_AsmJsCompileError // AsmJsCompileError is not a syntax error
  2108. || (FAILED(hrParseCodeGen) && SUCCEEDED(hrParser)), "Syntax errors should never be detected on deferred re-parse");
  2109. }
  2110. else
  2111. {
  2112. TRACE_BYTECODE(_u("\nDeferred parse %s\n"), funcBody->GetDisplayName());
  2113. Js::AutoDynamicCodeReference dynamicFunctionReference(m_scriptContext);
  2114. bool forceNoNative = isDebugOrAsmJsReparse ? this->GetScriptContext()->IsInterpreted() : false;
  2115. ParseableFunctionInfo* rootFunc = funcBody->GetParseableFunctionInfo();
  2116. hrParseCodeGen = GenerateByteCode(parseTree, grfscr, m_scriptContext,
  2117. &rootFunc, funcBody->GetSourceIndex(),
  2118. forceNoNative, &ps, &se, funcBody->GetScopeInfo(), functionRef);
  2119. funcBody->SetParseableFunctionInfo(rootFunc);
  2120. if (SUCCEEDED(hrParseCodeGen))
  2121. {
  2122. fParsed = TRUE;
  2123. }
  2124. else
  2125. {
  2126. Assert(hrParseCodeGen == SCRIPT_E_RECORDED);
  2127. hrParseCodeGen = se.ei.scode;
  2128. }
  2129. }
  2130. }
  2131. END_TRANSLATE_EXCEPTION_TO_HRESULT(hr);
  2132. }
  2133. END_LEAVE_SCRIPT_INTERNAL(m_scriptContext);
  2134. THROW_KNOWN_HRESULT_EXCEPTIONS(hr, m_scriptContext);
  2135. Assert(hr == NO_ERROR);
  2136. if (!SUCCEEDED(hrParser))
  2137. {
  2138. JavascriptError::ThrowError(m_scriptContext, VBSERR_InternalError);
  2139. }
  2140. else if (!SUCCEEDED(hrParseCodeGen))
  2141. {
  2142. /*
  2143. * VBSERR_OutOfStack is of type kjstError but we throw a (more specific) StackOverflowError when a hard stack
  2144. * overflow occurs. To keep the behavior consistent I'm special casing it here.
  2145. */
  2146. if (hrParseCodeGen == VBSERR_OutOfStack)
  2147. {
  2148. JavascriptError::ThrowStackOverflowError(m_scriptContext);
  2149. }
  2150. else if (hrParseCodeGen == JSERR_AsmJsCompileError)
  2151. {
  2152. asmjsParseFailed = true;
  2153. }
  2154. else
  2155. {
  2156. JavascriptError::MapAndThrowError(m_scriptContext, hrParseCodeGen);
  2157. }
  2158. }
  2159. }
  2160. else
  2161. {
  2162. fParsed = FALSE;
  2163. }
  2164. if (!asmjsParseFailed)
  2165. {
  2166. autoRestoreFunctionInfo.Clear();
  2167. }
  2168. }
  2169. if (fParsed == TRUE)
  2170. {
  2171. // Restore if the function has nameIdentifier reference, as that name on the left side will not be parsed again while deferparse.
  2172. funcBody->SetIsNameIdentifierRef(this->GetIsNameIdentifierRef());
  2173. this->m_hasBeenParsed = true;
  2174. returnFunctionBody = funcBody;
  2175. }
  2176. else if(!asmjsParseFailed)
  2177. {
  2178. returnFunctionBody = this->GetFunctionBody();
  2179. }
  2180. if (asmjsParseFailed)
  2181. {
  2182. // disable asm.js and reparse on failure
  2183. m_grfscr |= fscrNoAsmJs;
  2184. return Parse(functionRef, isByteCodeDeserialization);
  2185. }
  2186. return returnFunctionBody;
  2187. }
  2188. #ifdef ASMJS_PLAT
  2189. FunctionBody* ParseableFunctionInfo::ParseAsmJs(Parser * ps, __out CompileScriptException * se, __out ParseNodeProg ** parseTree)
  2190. {
  2191. Assert(IsDeferredParseFunction());
  2192. Assert(m_isAsmjsMode);
  2193. FunctionBody* returnFunctionBody = nullptr;
  2194. FunctionBody* funcBody = nullptr;
  2195. funcBody = FunctionBody::NewFromRecycler(
  2196. this->m_scriptContext,
  2197. this->m_displayName,
  2198. this->m_displayNameLength,
  2199. this->m_displayShortNameOffset,
  2200. this->GetNestedCount(),
  2201. this->GetUtf8SourceInfo(),
  2202. this->m_functionNumber,
  2203. this->GetUtf8SourceInfo()->GetSrcInfo()->sourceContextInfo->sourceContextId,
  2204. this->GetLocalFunctionId(),
  2205. (FunctionInfo::Attributes)(this->GetAttributes() & ~(FunctionInfo::Attributes::DeferredDeserialize | FunctionInfo::Attributes::DeferredParse)),
  2206. Js::FunctionBody::FunctionBodyFlags::Flags_HasNoExplicitReturnValue
  2207. #ifdef PERF_COUNTERS
  2208. , false /* is function from deferred deserialized proxy */
  2209. #endif
  2210. );
  2211. this->Copy(funcBody);
  2212. PERF_COUNTER_DEC(Code, DeferredFunction);
  2213. if (!this->GetSourceContextInfo()->IsDynamic())
  2214. {
  2215. PHASE_PRINT_TESTTRACE1(Js::DeferParsePhase, _u("TestTrace: Deferred function parsed - ID: %d; Display Name: %s; Length: %d; Nested Function Count: %d; Utf8SourceInfo: %d; Source Length: %d; Is Top Level: %s; Source Url: %s\n"), m_functionNumber, this->GetDisplayName(), this->m_cchLength, this->GetNestedCount(), this->m_utf8SourceInfo->GetSourceInfoId(), this->m_utf8SourceInfo->GetCchLength(), this->GetIsTopLevel() ? _u("True") : _u("False"), this->GetSourceContextInfo()->url);
  2216. }
  2217. else
  2218. {
  2219. PHASE_PRINT_TESTTRACE1(Js::DeferParsePhase, _u("TestTrace: Deferred function parsed - ID: %d; Display Name: %s; Length: %d; Nested Function Count: %d; Utf8SourceInfo: %d; Source Length: %d\n; Is Top Level: %s;"), m_functionNumber, this->GetDisplayName(), this->m_cchLength, this->GetNestedCount(), this->m_utf8SourceInfo->GetSourceInfoId(), this->m_utf8SourceInfo->GetCchLength(), this->GetIsTopLevel() ? _u("True") : _u("False"));
  2220. }
  2221. #if ENABLE_PROFILE_INFO
  2222. Assert(!funcBody->HasExecutionDynamicProfileInfo());
  2223. #endif
  2224. HRESULT hrParser = NO_ERROR;
  2225. HRESULT hrParseCodeGen = NO_ERROR;
  2226. bool isCesu8 = m_scriptContext->GetSource(funcBody->GetSourceIndex())->IsCesu8();
  2227. size_t offset = this->StartOffset();
  2228. charcount_t charOffset = this->StartInDocument();
  2229. size_t length = this->LengthInBytes();
  2230. LPCUTF8 pszStart = this->GetStartOfDocument();
  2231. uint32 grfscr = funcBody->GetGrfscr() | fscrDeferredFnc | fscrDeferredFncExpression;
  2232. uint nextFunctionId = funcBody->GetLocalFunctionId();
  2233. // if parser throws, it will be caught by function trying to bytecode gen the asm.js module, so don't need to catch/rethrow here
  2234. hrParser = ps->ParseSourceWithOffset(parseTree, pszStart, offset, length, charOffset, isCesu8, grfscr, se,
  2235. &nextFunctionId, funcBody->GetRelativeLineNumber(), funcBody->GetSourceContextInfo(),
  2236. funcBody);
  2237. Assert(FAILED(hrParser) || funcBody->deferredParseNextFunctionId == nextFunctionId);
  2238. if (FAILED(hrParser))
  2239. {
  2240. hrParseCodeGen = MapDeferredReparseError(hrParser, *se); // Map certain errors like OOM/SOE
  2241. AssertMsg(FAILED(hrParseCodeGen) && SUCCEEDED(hrParser), "Syntax errors should never be detected on deferred re-parse");
  2242. }
  2243. if (!SUCCEEDED(hrParser))
  2244. {
  2245. Throw::InternalError();
  2246. }
  2247. else if (!SUCCEEDED(hrParseCodeGen))
  2248. {
  2249. if (hrParseCodeGen == VBSERR_OutOfStack)
  2250. {
  2251. Throw::StackOverflow(m_scriptContext, nullptr);
  2252. }
  2253. else
  2254. {
  2255. Assert(hrParseCodeGen == E_OUTOFMEMORY);
  2256. Throw::OutOfMemory();
  2257. }
  2258. }
  2259. UpdateFunctionBodyImpl(funcBody);
  2260. m_hasBeenParsed = true;
  2261. Assert(funcBody->GetFunctionBody() == funcBody);
  2262. returnFunctionBody = funcBody;
  2263. return returnFunctionBody;
  2264. }
  2265. #endif
  2266. void ParseableFunctionInfo::Finalize(bool isShutdown)
  2267. {
  2268. __super::Finalize(isShutdown);
  2269. if (this->GetFunctionInfo())
  2270. {
  2271. // (If function info was never set, then initialization didn't finish, so there's nothing to remove from the dictionary.)
  2272. this->GetUtf8SourceInfo()->StopTrackingDeferredFunction(this->GetLocalFunctionId());
  2273. }
  2274. if (!this->m_hasBeenParsed)
  2275. {
  2276. PERF_COUNTER_DEC(Code, DeferredFunction);
  2277. }
  2278. }
  2279. bool ParseableFunctionInfo::IsFakeGlobalFunc(uint32 flags) const
  2280. {
  2281. return GetIsGlobalFunc() && !(flags & fscrGlobalCode);
  2282. }
  2283. #ifdef NTBUILD
  2284. bool ParseableFunctionInfo::GetExternalDisplaySourceName(BSTR* sourceName)
  2285. {
  2286. Assert(sourceName);
  2287. if (IsDynamicScript() && GetUtf8SourceInfo()->GetDebugDocumentName(sourceName))
  2288. {
  2289. return true;
  2290. }
  2291. *sourceName = ::SysAllocString(GetSourceName());
  2292. return *sourceName != nullptr;
  2293. }
  2294. #endif
  2295. const char16* FunctionProxy::WrapWithBrackets(const char16* name, charcount_t sz, ScriptContext* scriptContext)
  2296. {
  2297. char16 * wrappedName = RecyclerNewArrayLeaf(scriptContext->GetRecycler(), char16, sz + 3); //[]\0
  2298. wrappedName[0] = _u('[');
  2299. char16 *next = wrappedName;
  2300. js_wmemcpy_s(++next, sz, name, sz);
  2301. wrappedName[sz + 1] = _u(']');
  2302. wrappedName[sz + 2] = _u('\0');
  2303. return wrappedName;
  2304. }
  2305. const char16* FunctionProxy::GetShortDisplayName(charcount_t * shortNameLength)
  2306. {
  2307. const char16* name = this->GetDisplayName();
  2308. uint nameLength = this->GetDisplayNameLength();
  2309. if (name == nullptr)
  2310. {
  2311. *shortNameLength = 0;
  2312. return Constants::Empty;
  2313. }
  2314. if (IsConstantFunctionName(name))
  2315. {
  2316. *shortNameLength = nameLength;
  2317. return name;
  2318. }
  2319. uint shortNameOffset = this->GetShortDisplayNameOffset();
  2320. const char16 * shortName = name + shortNameOffset;
  2321. bool isBracketCase = shortNameOffset != 0 && name[shortNameOffset-1] == '[';
  2322. Assert(nameLength >= shortNameOffset);
  2323. *shortNameLength = nameLength - shortNameOffset;
  2324. if (!isBracketCase)
  2325. {
  2326. return shortName;
  2327. }
  2328. Assert(name[nameLength - 1] == ']');
  2329. char16 * finalshorterName = RecyclerNewArrayLeaf(this->GetScriptContext()->GetRecycler(), char16, *shortNameLength);
  2330. js_wmemcpy_s(finalshorterName, *shortNameLength, shortName, *shortNameLength - 1); // we don't want the last character in shorterName
  2331. finalshorterName[*shortNameLength - 1] = _u('\0');
  2332. *shortNameLength = *shortNameLength - 1;
  2333. return finalshorterName;
  2334. }
  2335. /*static*/
  2336. bool FunctionProxy::IsConstantFunctionName(const char16* srcName)
  2337. {
  2338. if (srcName == Js::Constants::GlobalFunction ||
  2339. srcName == Js::Constants::AnonymousFunction ||
  2340. srcName == Js::Constants::GlobalCode ||
  2341. srcName == Js::Constants::Anonymous ||
  2342. srcName == Js::Constants::UnknownScriptCode ||
  2343. srcName == Js::Constants::FunctionCode)
  2344. {
  2345. return true;
  2346. }
  2347. return false;
  2348. }
  2349. /*static */
  2350. /*Return value: Whether the target value is a recycler pointer or not*/
  2351. bool FunctionProxy::SetDisplayName(const char16* srcName, const char16** destName, uint displayNameLength, ScriptContext * scriptContext, SetDisplayNameFlags flags /* default to None */)
  2352. {
  2353. Assert(destName);
  2354. Assert(scriptContext);
  2355. if (srcName == nullptr)
  2356. {
  2357. *destName = (_u(""));
  2358. return false;
  2359. }
  2360. else if (IsConstantFunctionName(srcName) || (flags & SetDisplayNameFlagsDontCopy) != 0)
  2361. {
  2362. *destName = srcName;
  2363. return (flags & SetDisplayNameFlagsRecyclerAllocated) != 0; // Return true if array is recycler allocated
  2364. }
  2365. else
  2366. {
  2367. uint numCharacters = displayNameLength + 1;
  2368. Assert((flags & SetDisplayNameFlagsDontCopy) == 0);
  2369. *destName = RecyclerNewArrayLeaf(scriptContext->GetRecycler(), char16, numCharacters);
  2370. js_wmemcpy_s((char16 *)*destName, numCharacters, srcName, numCharacters);
  2371. ((char16 *)(*destName))[numCharacters - 1] = _u('\0');
  2372. return true;
  2373. }
  2374. }
  2375. bool FunctionProxy::SetDisplayName(const char16* srcName, WriteBarrierPtr<const char16>* destName, uint displayNameLength, ScriptContext * scriptContext, SetDisplayNameFlags flags /* default to None */)
  2376. {
  2377. const char16* dest = nullptr;
  2378. bool targetIsRecyclerMemory = SetDisplayName(srcName, &dest, displayNameLength, scriptContext, flags);
  2379. if (targetIsRecyclerMemory)
  2380. {
  2381. *destName = dest;
  2382. }
  2383. else
  2384. {
  2385. destName->NoWriteBarrierSet(dest);
  2386. }
  2387. return targetIsRecyclerMemory;
  2388. }
  2389. void ParseableFunctionInfo::SetDisplayName(const char16* pszDisplayName)
  2390. {
  2391. size_t len = wcslen(pszDisplayName);
  2392. if (len > UINT_MAX)
  2393. {
  2394. // Can't support display name that big
  2395. Js::Throw::OutOfMemory();
  2396. }
  2397. SetDisplayName(pszDisplayName, (uint)len, 0);
  2398. }
  2399. void ParseableFunctionInfo::SetDisplayName(const char16* pszDisplayName, uint displayNameLength, uint displayShortNameOffset, SetDisplayNameFlags flags /* default to None */)
  2400. {
  2401. this->m_displayNameLength = displayNameLength;
  2402. this->m_displayShortNameOffset = displayShortNameOffset;
  2403. this->m_displayNameIsRecyclerAllocated = FunctionProxy::SetDisplayName(pszDisplayName, &this->m_displayName, displayNameLength, m_scriptContext, flags);
  2404. }
  2405. // SourceInfo methods
  2406. /* static */
  2407. template <typename TStatementMapList>
  2408. FunctionBody::StatementMap * FunctionBody::GetNextNonSubexpressionStatementMap(TStatementMapList *statementMapList, int & startingAtIndex)
  2409. {
  2410. AssertMsg(statementMapList != nullptr, "Must have valid statementMapList to execute");
  2411. FunctionBody::StatementMap *map = statementMapList->Item(startingAtIndex);
  2412. while (map->isSubexpression && startingAtIndex < statementMapList->Count() - 1)
  2413. {
  2414. map = statementMapList->Item(++startingAtIndex);
  2415. }
  2416. if (map->isSubexpression) // Didn't find any non inner maps
  2417. {
  2418. return nullptr;
  2419. }
  2420. return map;
  2421. }
  2422. // explicitly instantiate template
  2423. template FunctionBody::StatementMap *
  2424. FunctionBody::GetNextNonSubexpressionStatementMap<FunctionBody::ArenaStatementMapList>(FunctionBody::ArenaStatementMapList *statementMapList, int & startingAtIndex);
  2425. template FunctionBody::StatementMap *
  2426. FunctionBody::GetNextNonSubexpressionStatementMap<FunctionBody::StatementMapList>(FunctionBody::StatementMapList *statementMapList, int & startingAtIndex);
  2427. /* static */ FunctionBody::StatementMap * FunctionBody::GetPrevNonSubexpressionStatementMap(StatementMapList *statementMapList, int & startingAtIndex)
  2428. {
  2429. AssertMsg(statementMapList != nullptr, "Must have valid statementMapList to execute");
  2430. StatementMap *map = statementMapList->Item(startingAtIndex);
  2431. while (startingAtIndex && map->isSubexpression)
  2432. {
  2433. map = statementMapList->Item(--startingAtIndex);
  2434. }
  2435. if (map->isSubexpression) // Didn't find any non inner maps
  2436. {
  2437. return nullptr;
  2438. }
  2439. return map;
  2440. }
  2441. void ParseableFunctionInfo::SetSourceInfo(uint sourceIndex, ParseNodeFnc * node, bool isEval, bool isDynamicFunction)
  2442. {
  2443. if (!m_utf8SourceHasBeenSet)
  2444. {
  2445. this->m_sourceIndex = sourceIndex;
  2446. this->m_cchStartOffset = node->ichMin;
  2447. this->m_cchLength = node->LengthInCodepoints();
  2448. this->m_lineNumber = node->lineNumber;
  2449. this->m_columnNumber = node->columnNumber;
  2450. this->m_isEval = isEval;
  2451. this->m_isDynamicFunction = isDynamicFunction;
  2452. // It would have been better if we detect and reject large source buffer earlier before parsing
  2453. size_t cbMin = node->cbMin;
  2454. size_t lengthInBytes = node->LengthInBytes();
  2455. if (cbMin > UINT_MAX || lengthInBytes > UINT_MAX)
  2456. {
  2457. Js::Throw::OutOfMemory();
  2458. }
  2459. this->m_cbStartOffset = (uint)cbMin;
  2460. this->m_cbLength = (uint)lengthInBytes;
  2461. Assert(this->m_utf8SourceInfo != nullptr);
  2462. this->m_utf8SourceHasBeenSet = true;
  2463. if (this->IsFunctionBody())
  2464. {
  2465. this->GetFunctionBody()->FinishSourceInfo();
  2466. }
  2467. }
  2468. #if DBG
  2469. else
  2470. {
  2471. AssertMsg(this->m_sourceIndex == sourceIndex, "Mismatched source index");
  2472. if (!this->GetIsGlobalFunc())
  2473. {
  2474. // In the global function case with a @cc_on, we modify some of these values so it might
  2475. // not match on reparse (see ParseableFunctionInfo::Parse()).
  2476. AssertMsg(this->StartOffset() == node->cbMin, "Mismatched source start offset");
  2477. AssertMsg(this->m_cchStartOffset == node->ichMin, "Mismatched source character start offset");
  2478. AssertMsg(this->m_cchLength == node->LengthInCodepoints(), "Mismatched source length");
  2479. AssertMsg(this->LengthInBytes() == node->LengthInBytes(), "Mismatched source encoded byte length");
  2480. }
  2481. AssertMsg(this->m_isEval == isEval, "Mismatched source type");
  2482. AssertMsg(this->m_isDynamicFunction == isDynamicFunction, "Mismatch source type");
  2483. }
  2484. #endif
  2485. #if DBG_DUMP
  2486. if (PHASE_TRACE1(Js::FunctionSourceInfoParsePhase))
  2487. {
  2488. Assert(this->GetFunctionInfo()->HasBody());
  2489. if (this->IsFunctionBody())
  2490. {
  2491. FunctionBody* functionBody = this->GetFunctionBody();
  2492. Assert( functionBody != nullptr );
  2493. functionBody->PrintStatementSourceLineFromStartOffset(functionBody->StartInDocument());
  2494. Output::Flush();
  2495. }
  2496. }
  2497. #endif
  2498. }
  2499. void ParseableFunctionInfo::SetSourceInfo(uint sourceIndex)
  2500. {
  2501. // TODO (michhol): how do we want to handle wasm source?
  2502. if (!m_utf8SourceHasBeenSet)
  2503. {
  2504. this->m_sourceIndex = sourceIndex;
  2505. this->m_cchStartOffset = 0;
  2506. this->m_cchLength = 0;
  2507. this->m_lineNumber = 0;
  2508. this->m_columnNumber = 0;
  2509. this->m_cbStartOffset = 0;
  2510. this->m_cbLength = 0;
  2511. this->m_utf8SourceHasBeenSet = true;
  2512. if (this->IsFunctionBody())
  2513. {
  2514. this->GetFunctionBody()->FinishSourceInfo();
  2515. }
  2516. }
  2517. #if DBG
  2518. else
  2519. {
  2520. AssertMsg(this->m_sourceIndex == sourceIndex, "Mismatched source index");
  2521. }
  2522. #endif
  2523. }
  2524. bool FunctionBody::Is(void* ptr)
  2525. {
  2526. if(!ptr)
  2527. {
  2528. return false;
  2529. }
  2530. return VirtualTableInfo<FunctionBody>::HasVirtualTable(ptr);
  2531. }
  2532. bool FunctionBody::HasLineBreak() const
  2533. {
  2534. return this->HasLineBreak(this->StartOffset(), this->m_cchStartOffset + this->m_cchLength);
  2535. }
  2536. bool FunctionBody::HasLineBreak(charcount_t start, charcount_t end) const
  2537. {
  2538. if (start > end) return false;
  2539. charcount_t cchLength = end - start;
  2540. if (start < this->m_cchStartOffset || cchLength > this->m_cchLength) return false;
  2541. LPCUTF8 src = this->GetSource(_u("FunctionBody::HasLineBreak"));
  2542. LPCUTF8 last = src + this->LengthInBytes();
  2543. size_t offset = this->LengthInBytes() == this->m_cchLength ?
  2544. start - this->m_cchStartOffset :
  2545. utf8::CharacterIndexToByteIndex(src, this->LengthInBytes(), start - this->m_cchStartOffset, utf8::doAllowThreeByteSurrogates);
  2546. src = src + offset;
  2547. utf8::DecodeOptions options = utf8::doAllowThreeByteSurrogates;
  2548. for (charcount_t cch = cchLength; cch > 0; --cch)
  2549. {
  2550. switch (utf8::Decode(src, last, options))
  2551. {
  2552. case '\r':
  2553. case '\n':
  2554. case 0x2028:
  2555. case 0x2029:
  2556. return true;
  2557. }
  2558. }
  2559. return false;
  2560. }
  2561. FunctionBody::StatementMap* FunctionBody::GetMatchingStatementMapFromByteCode(int byteCodeOffset, bool ignoreSubexpressions /* = false */)
  2562. {
  2563. StatementMapList * pStatementMaps = this->GetStatementMaps();
  2564. if (pStatementMaps)
  2565. {
  2566. Assert(m_sourceInfo.pSpanSequence == nullptr);
  2567. for (int index = 0; index < pStatementMaps->Count(); index++)
  2568. {
  2569. FunctionBody::StatementMap* pStatementMap = pStatementMaps->Item(index);
  2570. if (!(ignoreSubexpressions && pStatementMap->isSubexpression) && pStatementMap->byteCodeSpan.Includes(byteCodeOffset))
  2571. {
  2572. return pStatementMap;
  2573. }
  2574. }
  2575. }
  2576. return nullptr;
  2577. }
  2578. // Returns the StatementMap for the offset.
  2579. // 1. Current statementMap if bytecodeoffset falls within bytecode's span
  2580. // 2. Previous if the bytecodeoffset is in between previous's end to current's begin
  2581. FunctionBody::StatementMap* FunctionBody::GetEnclosingStatementMapFromByteCode(int byteCodeOffset, bool ignoreSubexpressions /* = false */)
  2582. {
  2583. int index = GetEnclosingStatementIndexFromByteCode(byteCodeOffset, ignoreSubexpressions);
  2584. if (index != -1)
  2585. {
  2586. return this->GetStatementMaps()->Item(index);
  2587. }
  2588. return nullptr;
  2589. }
  2590. // Returns the index of StatementMap for
  2591. // 1. Current statementMap if bytecodeoffset falls within bytecode's span
  2592. // 2. Previous if the bytecodeoffset is in between previous's end to current's begin
  2593. // 3. -1 of the failures.
  2594. int FunctionBody::GetEnclosingStatementIndexFromByteCode(int byteCodeOffset, bool ignoreSubexpressions /* = false */)
  2595. {
  2596. StatementMapList * pStatementMaps = this->GetStatementMaps();
  2597. if (pStatementMaps == nullptr)
  2598. {
  2599. // e.g. internal library.
  2600. return -1;
  2601. }
  2602. Assert(m_sourceInfo.pSpanSequence == nullptr);
  2603. for (int index = 0; index < pStatementMaps->Count(); index++)
  2604. {
  2605. FunctionBody::StatementMap* pStatementMap = pStatementMaps->Item(index);
  2606. if (!(ignoreSubexpressions && pStatementMap->isSubexpression) && pStatementMap->byteCodeSpan.Includes(byteCodeOffset))
  2607. {
  2608. return index;
  2609. }
  2610. else if (!pStatementMap->isSubexpression && byteCodeOffset < pStatementMap->byteCodeSpan.begin) // We always ignore sub expressions when checking if we went too far
  2611. {
  2612. return index > 0 ? index - 1 : 0;
  2613. }
  2614. }
  2615. return pStatementMaps->Count() - 1;
  2616. }
  2617. // In some cases in legacy mode, due to the state scriptContext->windowIdList, the parser might not detect an eval call in the first parse but do so in the reparse
  2618. // This fixes up the state at the start of reparse
  2619. void FunctionBody::SaveState(ParseNodeFnc * pnodeFnc)
  2620. {
  2621. Assert(!this->IsReparsed());
  2622. this->SetChildCallsEval(!!pnodeFnc->ChildCallsEval());
  2623. this->SetCallsEval(!!pnodeFnc->CallsEval());
  2624. this->SetHasReferenceableBuiltInArguments(!!pnodeFnc->HasReferenceableBuiltInArguments());
  2625. }
  2626. void FunctionBody::RestoreState(ParseNodeFnc * pnodeFnc)
  2627. {
  2628. Assert(this->IsReparsed());
  2629. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2630. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2631. #endif
  2632. if(!!pnodeFnc->ChildCallsEval() != this->GetChildCallsEval())
  2633. {
  2634. OUTPUT_VERBOSE_TRACE(Js::DebuggerPhase, _u("Child calls eval is different on debug reparse: %s(%s)\n"), this->GetExternalDisplayName(), this->GetDebugNumberSet(debugStringBuffer));
  2635. }
  2636. if(!!pnodeFnc->CallsEval() != this->GetCallsEval())
  2637. {
  2638. OUTPUT_VERBOSE_TRACE(Js::DebuggerPhase, _u("Calls eval is different on debug reparse: %s(%s)\n"), this->GetExternalDisplayName(), this->GetDebugNumberSet(debugStringBuffer));
  2639. }
  2640. if(!!pnodeFnc->HasReferenceableBuiltInArguments() != this->HasReferenceableBuiltInArguments())
  2641. {
  2642. OUTPUT_VERBOSE_TRACE(Js::DebuggerPhase, _u("Referenceable Built in args is different on debug reparse: %s(%s)\n"), this->GetExternalDisplayName(), this->GetDebugNumberSet(debugStringBuffer));
  2643. }
  2644. pnodeFnc->SetChildCallsEval(this->GetChildCallsEval());
  2645. pnodeFnc->SetCallsEval(this->GetCallsEval());
  2646. pnodeFnc->SetHasReferenceableBuiltInArguments(this->HasReferenceableBuiltInArguments());
  2647. }
  2648. // Retrieves statement map for given byte code offset.
  2649. // Parameters:
  2650. // - sourceOffset: byte code offset to get map for.
  2651. // - mapIndex: if not NULL, receives the index of found map.
  2652. FunctionBody::StatementMap* FunctionBody::GetMatchingStatementMapFromSource(int sourceOffset, int* pMapIndex /* = nullptr */)
  2653. {
  2654. StatementMapList * pStatementMaps = this->GetStatementMaps();
  2655. if (pStatementMaps && pStatementMaps->Count() > 0)
  2656. {
  2657. Assert(m_sourceInfo.pSpanSequence == nullptr);
  2658. for (int index = pStatementMaps->Count() - 1; index >= 0; index--)
  2659. {
  2660. FunctionBody::StatementMap* pStatementMap = pStatementMaps->Item(index);
  2661. if (!pStatementMap->isSubexpression && pStatementMap->sourceSpan.Includes(sourceOffset))
  2662. {
  2663. if (pMapIndex)
  2664. {
  2665. *pMapIndex = index;
  2666. }
  2667. return pStatementMap;
  2668. }
  2669. }
  2670. }
  2671. if (pMapIndex)
  2672. {
  2673. *pMapIndex = 0;
  2674. }
  2675. return nullptr;
  2676. }
  2677. //
  2678. // The function determine the line and column for a bytecode offset within the current script buffer.
  2679. //
  2680. bool FunctionBody::GetLineCharOffset(int byteCodeOffset, ULONG* _line, LONG* _charOffset, bool canAllocateLineCache /*= true*/)
  2681. {
  2682. Assert(!this->GetUtf8SourceInfo()->GetIsLibraryCode());
  2683. int startCharOfStatement = this->m_cchStartOffset; // Default to the start of this function
  2684. if (m_sourceInfo.pSpanSequence)
  2685. {
  2686. SmallSpanSequenceIter iter;
  2687. m_sourceInfo.pSpanSequence->Reset(iter);
  2688. StatementData data;
  2689. if (m_sourceInfo.pSpanSequence->GetMatchingStatementFromBytecode(byteCodeOffset, iter, data)
  2690. && EndsAfter(data.sourceBegin))
  2691. {
  2692. startCharOfStatement = data.sourceBegin;
  2693. }
  2694. }
  2695. else
  2696. {
  2697. Js::FunctionBody::StatementMap* map = this->GetEnclosingStatementMapFromByteCode(byteCodeOffset, false);
  2698. if (map && EndsAfter(map->sourceSpan.begin))
  2699. {
  2700. startCharOfStatement = map->sourceSpan.begin;
  2701. }
  2702. }
  2703. return this->GetLineCharOffsetFromStartChar(startCharOfStatement, _line, _charOffset, canAllocateLineCache);
  2704. }
  2705. bool FunctionBody::GetLineCharOffsetFromStartChar(int startCharOfStatement, ULONG* _line, LONG* _charOffset, bool canAllocateLineCache /*= true*/)
  2706. {
  2707. Assert(!this->GetUtf8SourceInfo()->GetIsLibraryCode() || this->IsJsBuiltInCode());
  2708. // The following adjusts for where the script is within the document
  2709. ULONG line = this->GetHostStartLine();
  2710. charcount_t column = 0;
  2711. ULONG lineCharOffset = 0;
  2712. charcount_t lineByteOffset = 0;
  2713. if (startCharOfStatement > 0)
  2714. {
  2715. bool doSlowLookup = !canAllocateLineCache;
  2716. if (canAllocateLineCache)
  2717. {
  2718. HRESULT hr = this->GetUtf8SourceInfo()->EnsureLineOffsetCacheNoThrow();
  2719. if (FAILED(hr))
  2720. {
  2721. if (hr != E_OUTOFMEMORY)
  2722. {
  2723. Assert(hr == E_ABORT); // The only other possible error we know about is ScriptAbort from QueryContinue.
  2724. return false;
  2725. }
  2726. // Clear the cache so it is not used.
  2727. this->GetUtf8SourceInfo()->DeleteLineOffsetCache();
  2728. // We can try and do the slow lookup below
  2729. doSlowLookup = true;
  2730. }
  2731. }
  2732. charcount_t cacheLine = 0;
  2733. this->GetUtf8SourceInfo()->GetLineInfoForCharPosition(startCharOfStatement, &cacheLine, &column, &lineByteOffset, doSlowLookup);
  2734. // Update the tracking variables to jump to the line position (only need to jump if not on the first line).
  2735. if (cacheLine > 0)
  2736. {
  2737. line += cacheLine;
  2738. lineCharOffset = startCharOfStatement - column;
  2739. }
  2740. }
  2741. if (this->GetSourceContextInfo()->IsDynamic() && this->m_isDynamicFunction)
  2742. {
  2743. line -= JavascriptFunction::numberLinesPrependedToAnonymousFunction;
  2744. }
  2745. if(_line)
  2746. {
  2747. *_line = line;
  2748. }
  2749. if(_charOffset)
  2750. {
  2751. *_charOffset = column;
  2752. // If we are at the beginning of the host code, adjust the offset based on the host provided offset
  2753. if (this->GetHostSrcInfo()->dlnHost == line)
  2754. {
  2755. *_charOffset += (LONG)this->GetHostStartColumn();
  2756. }
  2757. }
  2758. return true;
  2759. }
  2760. bool FunctionBody::GetStatementIndexAndLengthAt(int byteCodeOffset, UINT32* statementIndex, UINT32* statementLength)
  2761. {
  2762. Assert(statementIndex != nullptr);
  2763. Assert(statementLength != nullptr);
  2764. Assert(this->IsInDebugMode());
  2765. StatementMap * statement = GetEnclosingStatementMapFromByteCode(byteCodeOffset, false);
  2766. Assert(statement != nullptr);
  2767. // Bailout if we are unable to find a statement.
  2768. // We shouldn't be missing these when a debugger is attached but we don't want to AV on retail builds.
  2769. if (statement == nullptr)
  2770. {
  2771. return false;
  2772. }
  2773. Assert(m_utf8SourceInfo);
  2774. const SRCINFO * srcInfo = GetUtf8SourceInfo()->GetSrcInfo();
  2775. // Offset from the beginning of the document minus any host-supplied source characters.
  2776. // Host supplied characters are inserted (for example) around onload:
  2777. // onload="foo('somestring', 0)" -> function onload(event).{.foo('somestring', 0).}
  2778. ULONG offsetFromDocumentBegin = srcInfo ? srcInfo->ulCharOffset - srcInfo->ichMinHost : 0;
  2779. *statementIndex = statement->sourceSpan.Begin() + offsetFromDocumentBegin;
  2780. *statementLength = statement->sourceSpan.End() - statement->sourceSpan.Begin();
  2781. return true;
  2782. }
  2783. void FunctionBody::RecordFrameDisplayRegister(RegSlot slot)
  2784. {
  2785. AssertMsg(slot != 0, "The assumption that the Frame Display Register cannot be at the 0 slot is wrong.");
  2786. SetFrameDisplayRegister(slot);
  2787. }
  2788. void FunctionBody::RecordObjectRegister(RegSlot slot)
  2789. {
  2790. AssertMsg(slot != 0, "The assumption that the Object Register cannot be at the 0 slot is wrong.");
  2791. SetObjectRegister(slot);
  2792. }
  2793. Js::RootObjectBase * FunctionBody::GetRootObject() const
  2794. {
  2795. // Safe to be used by the JIT thread
  2796. Assert(this->GetConstTable() != nullptr);
  2797. return (Js::RootObjectBase *)PointerValue(this->GetConstTable()[Js::FunctionBody::RootObjectRegSlot - FunctionBody::FirstRegSlot]);
  2798. }
  2799. Js::RootObjectBase * FunctionBody::LoadRootObject() const
  2800. {
  2801. if (this->IsES6ModuleCode() || this->GetModuleID() == kmodGlobal)
  2802. {
  2803. return JavascriptOperators::OP_LdRoot(this->GetScriptContext());
  2804. }
  2805. return JavascriptOperators::GetModuleRoot(this->GetModuleID(), this->GetScriptContext());
  2806. }
  2807. #if ENABLE_NATIVE_CODEGEN
  2808. FunctionEntryPointInfo * FunctionBody::GetEntryPointFromNativeAddress(DWORD_PTR codeAddress)
  2809. {
  2810. FunctionEntryPointInfo * entryPoint = nullptr;
  2811. this->MapEntryPoints([&entryPoint, &codeAddress](int index, FunctionEntryPointInfo * currentEntryPoint)
  2812. {
  2813. // We need to do a second check for IsNativeCode because the entry point could be in the process of
  2814. // being recorded on the background thread
  2815. if (currentEntryPoint->IsInNativeAddressRange(codeAddress))
  2816. {
  2817. entryPoint = currentEntryPoint;
  2818. }
  2819. });
  2820. return entryPoint;
  2821. }
  2822. LoopEntryPointInfo * FunctionBody::GetLoopEntryPointInfoFromNativeAddress(DWORD_PTR codeAddress, uint loopNum) const
  2823. {
  2824. LoopEntryPointInfo * entryPoint = nullptr;
  2825. LoopHeader * loopHeader = this->GetLoopHeader(loopNum);
  2826. Assert(loopHeader);
  2827. loopHeader->MapEntryPoints([&](int index, LoopEntryPointInfo * currentEntryPoint)
  2828. {
  2829. if (currentEntryPoint->IsCodeGenDone() &&
  2830. codeAddress >= currentEntryPoint->GetNativeAddress() &&
  2831. codeAddress < currentEntryPoint->GetNativeAddress() + currentEntryPoint->GetCodeSize())
  2832. {
  2833. entryPoint = currentEntryPoint;
  2834. }
  2835. });
  2836. return entryPoint;
  2837. }
  2838. int FunctionBody::GetStatementIndexFromNativeOffset(SmallSpanSequence *pThrowSpanSequence, uint32 nativeOffset)
  2839. {
  2840. int statementIndex = -1;
  2841. if (pThrowSpanSequence)
  2842. {
  2843. SmallSpanSequenceIter iter;
  2844. StatementData tmpData;
  2845. if (pThrowSpanSequence->GetMatchingStatementFromBytecode(nativeOffset, iter, tmpData))
  2846. {
  2847. statementIndex = tmpData.sourceBegin; // sourceBegin represents statementIndex here
  2848. }
  2849. else
  2850. {
  2851. // If nativeOffset falls on the last span, GetMatchingStatement would miss it because SmallSpanSequence
  2852. // does not know about the last span end. Since we checked that codeAddress is within our range,
  2853. // we can safely consider it matches the last span.
  2854. statementIndex = iter.accumulatedSourceBegin;
  2855. }
  2856. }
  2857. return statementIndex;
  2858. }
  2859. int FunctionBody::GetStatementIndexFromNativeAddress(SmallSpanSequence *pThrowSpanSequence, DWORD_PTR codeAddress, DWORD_PTR nativeBaseAddress)
  2860. {
  2861. uint32 nativeOffset = (uint32)(codeAddress - nativeBaseAddress);
  2862. return GetStatementIndexFromNativeOffset(pThrowSpanSequence, nativeOffset);
  2863. }
  2864. #endif
  2865. BOOL FunctionBody::GetMatchingStatementMap(StatementData &data, int statementIndex, FunctionBody *inlinee)
  2866. {
  2867. SourceInfo *si = &this->m_sourceInfo;
  2868. if (inlinee)
  2869. {
  2870. si = &inlinee->m_sourceInfo;
  2871. Assert(si);
  2872. }
  2873. if (statementIndex >= 0)
  2874. {
  2875. SmallSpanSequence *pSpanSequence = si->pSpanSequence;
  2876. if (pSpanSequence)
  2877. {
  2878. SmallSpanSequenceIter iter;
  2879. pSpanSequence->Reset(iter);
  2880. if (pSpanSequence->Item(statementIndex, iter, data))
  2881. {
  2882. return TRUE;
  2883. }
  2884. }
  2885. else
  2886. {
  2887. StatementMapList* pStatementMaps = GetStatementMaps();
  2888. Assert(pStatementMaps);
  2889. if (statementIndex >= pStatementMaps->Count())
  2890. {
  2891. return FALSE;
  2892. }
  2893. data.sourceBegin = pStatementMaps->Item(statementIndex)->sourceSpan.begin;
  2894. data.bytecodeBegin = pStatementMaps->Item(statementIndex)->byteCodeSpan.begin;
  2895. return TRUE;
  2896. }
  2897. }
  2898. return FALSE;
  2899. }
  2900. void FunctionBody::FindClosestStatements(int32 characterOffset, StatementLocation *firstStatementLocation, StatementLocation *secondStatementLocation)
  2901. {
  2902. auto statementMaps = this->GetStatementMaps();
  2903. if (statementMaps)
  2904. {
  2905. for(int i = 0; i < statementMaps->Count(); i++)
  2906. {
  2907. regex::Interval* pSourceSpan = &(statementMaps->Item(i)->sourceSpan);
  2908. if (FunctionBody::IsDummyGlobalRetStatement(pSourceSpan))
  2909. {
  2910. // Workaround for handling global return, which is an empty range.
  2911. continue;
  2912. }
  2913. if (pSourceSpan->begin < characterOffset
  2914. && (firstStatementLocation->function == nullptr || firstStatementLocation->statement.begin < pSourceSpan->begin))
  2915. {
  2916. firstStatementLocation->function = this;
  2917. firstStatementLocation->statement = *pSourceSpan;
  2918. firstStatementLocation->bytecodeSpan = statementMaps->Item(i)->byteCodeSpan;
  2919. }
  2920. else if (pSourceSpan->begin >= characterOffset
  2921. && (secondStatementLocation->function == nullptr || secondStatementLocation->statement.begin > pSourceSpan->begin))
  2922. {
  2923. secondStatementLocation->function = this;
  2924. secondStatementLocation->statement = *pSourceSpan;
  2925. secondStatementLocation->bytecodeSpan = statementMaps->Item(i)->byteCodeSpan;
  2926. }
  2927. }
  2928. }
  2929. }
  2930. #if ENABLE_NATIVE_CODEGEN
  2931. BOOL FunctionBody::GetMatchingStatementMapFromNativeAddress(DWORD_PTR codeAddress, StatementData &data, uint loopNum, FunctionBody *inlinee /* = nullptr */)
  2932. {
  2933. SmallSpanSequence * spanSequence = nullptr;
  2934. DWORD_PTR nativeBaseAddress = NULL;
  2935. EntryPointInfo * entryPoint;
  2936. if (loopNum == -1)
  2937. {
  2938. entryPoint = GetEntryPointFromNativeAddress(codeAddress);
  2939. }
  2940. else
  2941. {
  2942. entryPoint = GetLoopEntryPointInfoFromNativeAddress(codeAddress, loopNum);
  2943. }
  2944. if (entryPoint != nullptr)
  2945. {
  2946. spanSequence = entryPoint->GetNativeThrowSpanSequence();
  2947. nativeBaseAddress = entryPoint->GetNativeAddress();
  2948. }
  2949. int statementIndex = GetStatementIndexFromNativeAddress(spanSequence, codeAddress, nativeBaseAddress);
  2950. return GetMatchingStatementMap(data, statementIndex, inlinee);
  2951. }
  2952. BOOL FunctionBody::GetMatchingStatementMapFromNativeOffset(DWORD_PTR codeAddress, uint32 offset, StatementData &data, uint loopNum, FunctionBody *inlinee /* = nullptr */)
  2953. {
  2954. EntryPointInfo * entryPoint;
  2955. if (loopNum == -1)
  2956. {
  2957. entryPoint = GetEntryPointFromNativeAddress(codeAddress);
  2958. }
  2959. else
  2960. {
  2961. entryPoint = GetLoopEntryPointInfoFromNativeAddress(codeAddress, loopNum);
  2962. }
  2963. SmallSpanSequence *spanSequence = entryPoint ? entryPoint->GetNativeThrowSpanSequence() : nullptr;
  2964. int statementIndex = GetStatementIndexFromNativeOffset(spanSequence, offset);
  2965. return GetMatchingStatementMap(data, statementIndex, inlinee);
  2966. }
  2967. #endif
  2968. #if ENABLE_PROFILE_INFO
  2969. void FunctionBody::LoadDynamicProfileInfo()
  2970. {
  2971. SourceDynamicProfileManager * sourceDynamicProfileManager = GetSourceContextInfo()->sourceDynamicProfileManager;
  2972. if (sourceDynamicProfileManager != nullptr)
  2973. {
  2974. this->dynamicProfileInfo = sourceDynamicProfileManager->GetDynamicProfileInfo(this);
  2975. #if DBG_DUMP
  2976. if(this->dynamicProfileInfo)
  2977. {
  2978. if (Configuration::Global.flags.Dump.IsEnabled(DynamicProfilePhase, this->GetSourceContextId(), this->GetLocalFunctionId()))
  2979. {
  2980. Output::Print(_u("Loaded:"));
  2981. this->dynamicProfileInfo->Dump(this);
  2982. }
  2983. }
  2984. #endif
  2985. }
  2986. #ifdef DYNAMIC_PROFILE_MUTATOR
  2987. DynamicProfileMutator::Mutate(this);
  2988. #endif
  2989. }
  2990. bool FunctionBody::NeedEnsureDynamicProfileInfo() const
  2991. {
  2992. // Only need to ensure dynamic profile if we don't already have link up the dynamic profile info
  2993. // and dynamic profile collection is enabled
  2994. return
  2995. !this->m_isFromNativeCodeModule &&
  2996. !this->HasExecutionDynamicProfileInfo() &&
  2997. DynamicProfileInfo::IsEnabled(this);
  2998. }
  2999. DynamicProfileInfo * FunctionBody::EnsureDynamicProfileInfo()
  3000. {
  3001. if (this->NeedEnsureDynamicProfileInfo())
  3002. {
  3003. m_scriptContext->AddDynamicProfileInfo(this, this->dynamicProfileInfo);
  3004. Assert(!this->HasExecutionDynamicProfileInfo());
  3005. this->hasExecutionDynamicProfileInfo = true;
  3006. }
  3007. return this->dynamicProfileInfo;
  3008. }
  3009. DynamicProfileInfo* FunctionBody::AllocateDynamicProfile()
  3010. {
  3011. return DynamicProfileInfo::New(m_scriptContext->GetRecycler(), this);
  3012. }
  3013. #endif
  3014. BOOL FunctionBody::IsNativeOriginalEntryPoint() const
  3015. {
  3016. #if ENABLE_NATIVE_CODEGEN
  3017. JavascriptMethod originalEntryPoint = this->GetOriginalEntryPoint_Unchecked();
  3018. return
  3019. #if defined(_CONTROL_FLOW_GUARD) && !defined(_M_ARM)
  3020. (
  3021. #if ENABLE_OOP_NATIVE_CODEGEN
  3022. JITManager::GetJITManager()->IsOOPJITEnabled()
  3023. ? JITThunkEmitter<SectionAllocWrapper>::IsInThunk(this->GetScriptContext()->GetThreadContext()->GetJITThunkStartAddr(), (uintptr_t)originalEntryPoint)
  3024. :
  3025. #endif
  3026. this->GetScriptContext()->GetThreadContext()->GetJITThunkEmitter()->IsInThunk((uintptr_t)originalEntryPoint)
  3027. ) ||
  3028. #endif
  3029. this->GetScriptContext()->IsNativeAddress((void*)originalEntryPoint);
  3030. #else
  3031. return false;
  3032. #endif
  3033. }
  3034. bool FunctionBody::IsSimpleJitOriginalEntryPoint() const
  3035. {
  3036. #if ENABLE_NATIVE_CODEGEN
  3037. const FunctionEntryPointInfo *const simpleJitEntryPointInfo = GetSimpleJitEntryPointInfo();
  3038. return simpleJitEntryPointInfo && simpleJitEntryPointInfo->GetNativeEntrypoint() == GetOriginalEntryPoint_Unchecked();
  3039. #else
  3040. return false;
  3041. #endif
  3042. }
  3043. void FunctionProxy::Finalize(bool isShutdown)
  3044. {
  3045. this->CleanupFunctionProxyCounters();
  3046. }
  3047. #if DBG
  3048. bool FunctionBody::HasValidSourceInfo()
  3049. {
  3050. SourceContextInfo* sourceContextInfo;
  3051. if (m_scriptContext->GetSourceContextInfoMap())
  3052. {
  3053. if(m_scriptContext->GetSourceContextInfoMap()->TryGetValue(this->GetHostSourceContext(), &sourceContextInfo) &&
  3054. sourceContextInfo == this->GetSourceContextInfo())
  3055. {
  3056. return true;
  3057. }
  3058. }
  3059. Assert(this->IsDynamicScript());
  3060. if(m_scriptContext->GetDynamicSourceContextInfoMap())
  3061. {
  3062. if(m_scriptContext->GetDynamicSourceContextInfoMap()->TryGetValue(this->GetSourceContextInfo()->hash, &sourceContextInfo) &&
  3063. sourceContextInfo == this->GetSourceContextInfo())
  3064. {
  3065. return true;
  3066. }
  3067. }
  3068. // The SourceContextInfo will not be added to the dynamicSourceContextInfoMap, if they are host provided dynamic code. But they are valid source context info
  3069. if (this->GetSourceContextInfo()->isHostDynamicDocument)
  3070. {
  3071. return true;
  3072. }
  3073. return m_scriptContext->IsNoContextSourceContextInfo(this->GetSourceContextInfo());
  3074. }
  3075. // originalEntryPoint: DefaultDeferredParsingThunk, DefaultDeferredDeserializeThunk, DefaultEntryThunk, dynamic interpreter thunk or native entry point
  3076. // directEntryPoint:
  3077. // if (!profiled) - DefaultDeferredParsingThunk, DefaultDeferredDeserializeThunk, DefaultEntryThunk, CheckCodeGenThunk,
  3078. // dynamic interpreter thunk, native entry point
  3079. // if (profiling) - ProfileDeferredParsingThunk, ProfileDeferredDeserializeThunk, ProfileEntryThunk, CheckCodeGenThunk
  3080. bool FunctionProxy::HasValidNonProfileEntryPoint() const
  3081. {
  3082. JavascriptMethod directEntryPoint = this->GetDefaultEntryPointInfo()->jsMethod;
  3083. JavascriptMethod originalEntryPoint = this->GetOriginalEntryPoint_Unchecked();
  3084. FunctionBody* body = this->GetFunctionBody();
  3085. Unused(body); // in some configuration
  3086. #ifdef ASMJS_PLAT
  3087. if (body->GetIsAsmJsFunction())
  3088. {
  3089. #ifdef ENABLE_WASM
  3090. if (body->IsWasmFunction() && body->GetByteCodeCount() == 0)
  3091. {
  3092. // The only valid 2 entrypoints if the function hasn't been parsed
  3093. return directEntryPoint == AsmJsDefaultEntryThunk || directEntryPoint == WasmLibrary::WasmLazyTrapCallback;
  3094. }
  3095. #endif
  3096. // Entrypoints valid only for asm.js/wasm
  3097. if (directEntryPoint == AsmJsDefaultEntryThunk || IsAsmJsCodeGenThunk(directEntryPoint))
  3098. {
  3099. return true;
  3100. }
  3101. }
  3102. #endif
  3103. // Check the direct entry point to see if it is codegen thunk
  3104. // if it is not, the background codegen thread has updated both original entry point and direct entry point
  3105. // and they should still match, same as cases other then code gen
  3106. return IsIntermediateCodeGenThunk(directEntryPoint) || originalEntryPoint == directEntryPoint
  3107. #if ENABLE_PROFILE_INFO
  3108. || (directEntryPoint == DynamicProfileInfo::EnsureDynamicProfileInfoThunk && body->IsNativeOriginalEntryPoint())
  3109. #endif
  3110. ;
  3111. }
  3112. #if defined(ENABLE_SCRIPT_PROFILING) || defined(ENABLE_SCRIPT_DEBUGGING)
  3113. bool FunctionProxy::HasValidProfileEntryPoint() const
  3114. {
  3115. JavascriptMethod directEntryPoint = this->GetDefaultEntryPointInfo()->jsMethod;
  3116. JavascriptMethod originalEntryPoint = this->GetOriginalEntryPoint_Unchecked();
  3117. if (originalEntryPoint == DefaultDeferredParsingThunk)
  3118. {
  3119. return directEntryPoint == ProfileDeferredParsingThunk;
  3120. }
  3121. if (originalEntryPoint == DefaultDeferredDeserializeThunk)
  3122. {
  3123. return directEntryPoint == ProfileDeferredDeserializeThunk;
  3124. }
  3125. if (!this->IsFunctionBody())
  3126. {
  3127. return false;
  3128. }
  3129. #if ENABLE_PROFILE_INFO
  3130. FunctionBody * functionBody = this->GetFunctionBody();
  3131. if (functionBody->IsInterpreterThunk() || functionBody->IsSimpleJitOriginalEntryPoint())
  3132. {
  3133. return directEntryPoint == ProfileEntryThunk || IsIntermediateCodeGenThunk(directEntryPoint);
  3134. }
  3135. #if ENABLE_NATIVE_CODEGEN
  3136. // In the profiler mode, the EnsureDynamicProfileInfoThunk is valid as we would be assigning to appropriate thunk when that thunk called.
  3137. return functionBody->IsNativeOriginalEntryPoint() &&
  3138. (directEntryPoint == DynamicProfileInfo::EnsureDynamicProfileInfoThunk || directEntryPoint == ProfileEntryThunk);
  3139. #endif
  3140. #else
  3141. return true;
  3142. #endif
  3143. }
  3144. #endif
  3145. bool FunctionProxy::HasValidEntryPoint() const
  3146. {
  3147. if (this->IsWasmFunction() ||
  3148. (!m_scriptContext->HadProfiled() &&
  3149. !(this->m_scriptContext->IsScriptContextInDebugMode() && m_scriptContext->IsExceptionWrapperForBuiltInsEnabled())))
  3150. {
  3151. return this->HasValidNonProfileEntryPoint();
  3152. }
  3153. #if defined(ENABLE_SCRIPT_PROFILING) || defined(ENABLE_SCRIPT_DEBUGGING)
  3154. if (m_scriptContext->IsProfiling())
  3155. {
  3156. return this->HasValidProfileEntryPoint();
  3157. }
  3158. return this->HasValidNonProfileEntryPoint() || this->HasValidProfileEntryPoint();
  3159. #else
  3160. return this->HasValidNonProfileEntryPoint();
  3161. #endif
  3162. }
  3163. #endif
  3164. void ParseableFunctionInfo::SetDeferredParsingEntryPoint()
  3165. {
  3166. #if defined(ENABLE_SCRIPT_PROFILING) || defined(ENABLE_SCRIPT_DEBUGGING)
  3167. Assert(m_scriptContext->DeferredParsingThunk == ProfileDeferredParsingThunk
  3168. || m_scriptContext->DeferredParsingThunk == DefaultDeferredParsingThunk);
  3169. #else
  3170. Assert(m_scriptContext->DeferredParsingThunk == DefaultDeferredParsingThunk);
  3171. #endif
  3172. this->SetEntryPoint(this->GetDefaultEntryPointInfo(), m_scriptContext->DeferredParsingThunk);
  3173. this->SetOriginalEntryPoint(DefaultDeferredParsingThunk);
  3174. }
  3175. void ParseableFunctionInfo::SetInitialDefaultEntryPoint()
  3176. {
  3177. #if defined(ENABLE_SCRIPT_PROFILING) || defined(ENABLE_SCRIPT_DEBUGGING)
  3178. Assert(m_scriptContext->CurrentThunk == ProfileEntryThunk || m_scriptContext->CurrentThunk == DefaultEntryThunk);
  3179. Assert(this->GetOriginalEntryPoint_Unchecked() == DefaultDeferredParsingThunk ||
  3180. this->GetOriginalEntryPoint_Unchecked() == ProfileDeferredParsingThunk ||
  3181. this->GetOriginalEntryPoint_Unchecked() == DefaultDeferredDeserializeThunk ||
  3182. this->GetOriginalEntryPoint_Unchecked() == ProfileDeferredDeserializeThunk ||
  3183. this->GetOriginalEntryPoint_Unchecked() == DefaultEntryThunk ||
  3184. this->GetOriginalEntryPoint_Unchecked() == ProfileEntryThunk);
  3185. #else
  3186. Assert(m_scriptContext->CurrentThunk == DefaultEntryThunk);
  3187. Assert(this->GetOriginalEntryPoint_Unchecked() == DefaultDeferredParsingThunk ||
  3188. this->GetOriginalEntryPoint_Unchecked() == DefaultDeferredDeserializeThunk ||
  3189. this->GetOriginalEntryPoint_Unchecked() == DefaultEntryThunk);
  3190. #endif
  3191. Assert(this->m_defaultEntryPointInfo != nullptr);
  3192. // CONSIDER: we can optimize this to generate the dynamic interpreter thunk up front
  3193. // If we know that we are in the defer parsing thunk already
  3194. this->SetEntryPoint(this->GetDefaultEntryPointInfo(), m_scriptContext->CurrentThunk);
  3195. this->SetOriginalEntryPoint(DefaultEntryThunk);
  3196. }
  3197. #if ENABLE_NATIVE_CODEGEN
  3198. void FunctionBody::SetCheckCodeGenEntryPoint(FunctionEntryPointInfo* entryPointInfo, JavascriptMethod entryPoint)
  3199. {
  3200. Assert(IsIntermediateCodeGenThunk(entryPoint));
  3201. Assert(
  3202. this->GetEntryPoint(entryPointInfo) == m_scriptContext->CurrentThunk ||
  3203. (entryPointInfo == this->m_defaultEntryPointInfo && this->IsInterpreterThunk()) ||
  3204. (
  3205. GetSimpleJitEntryPointInfo() &&
  3206. GetEntryPoint(entryPointInfo) == GetSimpleJitEntryPointInfo()->GetNativeEntrypoint()
  3207. ));
  3208. this->SetEntryPoint(entryPointInfo, entryPoint);
  3209. }
  3210. #endif
  3211. #if DYNAMIC_INTERPRETER_THUNK
  3212. void FunctionBody::GenerateDynamicInterpreterThunk()
  3213. {
  3214. AssertOrFailFastMsg(!m_isWasmFunction || GetByteCodeCount() > 0, "The wasm function should have been parsed before generating the dynamic interpreter thunk");
  3215. if (this->m_dynamicInterpreterThunk == nullptr)
  3216. {
  3217. // NOTE: Etw rundown thread may be reading this->dynamicInterpreterThunk concurrently. We don't need to synchronize
  3218. // access as it is ok for etw rundown to get either null or updated new value.
  3219. if (m_isAsmJsFunction)
  3220. {
  3221. this->SetOriginalEntryPoint(this->m_scriptContext->GetNextDynamicAsmJsInterpreterThunk(&this->m_dynamicInterpreterThunk));
  3222. }
  3223. else
  3224. {
  3225. this->SetOriginalEntryPoint(this->m_scriptContext->GetNextDynamicInterpreterThunk(&this->m_dynamicInterpreterThunk));
  3226. }
  3227. if (this->m_dynamicInterpreterThunk != nullptr)
  3228. {
  3229. JS_ETW(EtwTrace::LogMethodInterpreterThunkLoadEvent(this));
  3230. }
  3231. }
  3232. else
  3233. {
  3234. this->SetOriginalEntryPoint((JavascriptMethod)InterpreterThunkEmitter::ConvertToEntryPoint(this->m_dynamicInterpreterThunk));
  3235. }
  3236. #if DBG
  3237. if (GetScriptContext()->GetThreadContext()->NoDynamicThunks())
  3238. {
  3239. Assert(this->m_dynamicInterpreterThunk == nullptr);
  3240. #ifdef ASMJS_PLAT
  3241. if (m_isAsmJsFunction)
  3242. {
  3243. Assert(this->GetOriginalEntryPoint_Unchecked() == (JavascriptMethod)&Js::InterpreterStackFrame::StaticInterpreterAsmThunk);
  3244. }
  3245. else
  3246. #endif
  3247. {
  3248. Assert(this->GetOriginalEntryPoint_Unchecked() == (JavascriptMethod)&Js::InterpreterStackFrame::StaticInterpreterThunk);
  3249. }
  3250. }
  3251. #endif
  3252. }
  3253. JavascriptMethod FunctionBody::EnsureDynamicInterpreterThunk(FunctionEntryPointInfo* entryPointInfo)
  3254. {
  3255. // This may be first call to the function, make sure we have dynamic profile info
  3256. //
  3257. // We need to ensure dynamic profile info even if we didn't generate a dynamic interpreter thunk
  3258. // This happens when we go through CheckCodeGen thunk, to DelayDynamicInterpreterThunk, to here
  3259. // but the background codegen thread updated the entry point with the native entry point.
  3260. this->EnsureDynamicProfileInfo();
  3261. Assert(HasValidEntryPoint());
  3262. AssertMsg(!m_isWasmFunction || GetByteCodeCount() > 0, "Wasm function should be parsed by this point");
  3263. if (InterpreterStackFrame::IsDelayDynamicInterpreterThunk(this->GetEntryPoint(entryPointInfo)))
  3264. {
  3265. // We are not doing code gen on this function, just change the entry point directly
  3266. Assert(InterpreterStackFrame::IsDelayDynamicInterpreterThunk(this->GetOriginalEntryPoint_Unchecked()));
  3267. GenerateDynamicInterpreterThunk();
  3268. this->SetEntryPoint(entryPointInfo, this->GetOriginalEntryPoint_Unchecked());
  3269. }
  3270. else if (this->GetEntryPoint(entryPointInfo) == ProfileEntryThunk)
  3271. {
  3272. // We are not doing codegen on this function, just change the entry point directly
  3273. // Don't replace the profile entry thunk
  3274. Assert(InterpreterStackFrame::IsDelayDynamicInterpreterThunk(this->GetOriginalEntryPoint_Unchecked()));
  3275. GenerateDynamicInterpreterThunk();
  3276. }
  3277. else if (InterpreterStackFrame::IsDelayDynamicInterpreterThunk(this->GetOriginalEntryPoint_Unchecked()))
  3278. {
  3279. JsUtil::JobProcessor * jobProcessor = this->GetScriptContext()->GetThreadContext()->GetJobProcessor();
  3280. if (jobProcessor->ProcessesInBackground())
  3281. {
  3282. JsUtil::BackgroundJobProcessor * backgroundJobProcessor = static_cast<JsUtil::BackgroundJobProcessor *>(jobProcessor);
  3283. AutoCriticalSection autocs(backgroundJobProcessor->GetCriticalSection());
  3284. // Check again under lock
  3285. if (InterpreterStackFrame::IsDelayDynamicInterpreterThunk(this->GetOriginalEntryPoint_Unchecked()))
  3286. {
  3287. // If the original entry point is DelayDynamicInterpreterThunk then there must be a version of this
  3288. // function being codegen'd.
  3289. Assert(IsIntermediateCodeGenThunk((JavascriptMethod)this->GetEntryPoint(this->GetDefaultEntryPointInfo())) || IsAsmJsCodeGenThunk((JavascriptMethod)this->GetEntryPoint(this->GetDefaultEntryPointInfo())));
  3290. GenerateDynamicInterpreterThunk();
  3291. }
  3292. }
  3293. else
  3294. {
  3295. // If the original entry point is DelayDynamicInterpreterThunk then there must be a version of this
  3296. // function being codegen'd.
  3297. Assert(IsIntermediateCodeGenThunk((JavascriptMethod)this->GetEntryPoint(this->GetDefaultEntryPointInfo())) || IsAsmJsCodeGenThunk((JavascriptMethod)this->GetEntryPoint(this->GetDefaultEntryPointInfo())));
  3298. GenerateDynamicInterpreterThunk();
  3299. }
  3300. }
  3301. return this->GetOriginalEntryPoint_Unchecked();
  3302. }
  3303. #endif
  3304. #if ENABLE_NATIVE_CODEGEN
  3305. void FunctionBody::SetNativeEntryPoint(FunctionEntryPointInfo* entryPointInfo, JavascriptMethod originalEntryPoint, JavascriptMethod directEntryPoint)
  3306. {
  3307. if (entryPointInfo->IsNativeEntryPointProcessed())
  3308. {
  3309. return;
  3310. }
  3311. bool isAsmJs = this->GetIsAsmjsMode();
  3312. Assert(IsIntermediateCodeGenThunk(entryPointInfo->jsMethod) || CONFIG_FLAG(Prejit) || this->m_isFromNativeCodeModule || isAsmJs);
  3313. entryPointInfo->EnsureIsReadyToCall();
  3314. // keep originalEntryPoint updated with the latest known good native entry point
  3315. if (entryPointInfo == this->GetDefaultEntryPointInfo())
  3316. {
  3317. this->SetOriginalEntryPoint(originalEntryPoint);
  3318. }
  3319. if (entryPointInfo->entryPointIndex == 0 && this->NeedEnsureDynamicProfileInfo())
  3320. {
  3321. entryPointInfo->jsMethod = DynamicProfileInfo::EnsureDynamicProfileInfoThunk;
  3322. }
  3323. else
  3324. {
  3325. entryPointInfo->jsMethod = directEntryPoint;
  3326. }
  3327. this->CaptureDynamicProfileState(entryPointInfo);
  3328. if(entryPointInfo->GetJitMode() == ExecutionMode::SimpleJit)
  3329. {
  3330. Assert(GetExecutionMode() == ExecutionMode::SimpleJit);
  3331. SetSimpleJitEntryPointInfo(entryPointInfo);
  3332. ResetSimpleJitCallCount();
  3333. }
  3334. else
  3335. {
  3336. Assert(entryPointInfo->GetJitMode() == ExecutionMode::FullJit);
  3337. Assert(isAsmJs || GetExecutionMode() == ExecutionMode::FullJit);
  3338. entryPointInfo->callsCount =
  3339. static_cast<uint8>(
  3340. min(
  3341. static_cast<uint>(static_cast<uint8>(CONFIG_FLAG(MinBailOutsBeforeRejit))) *
  3342. (Js::FunctionEntryPointInfo::GetDecrCallCountPerBailout() - 1),
  3343. 0xffu));
  3344. }
  3345. TraceExecutionMode();
  3346. JS_ETW(EtwTrace::LogMethodNativeLoadEvent(this, entryPointInfo));
  3347. #ifdef VTUNE_PROFILING
  3348. VTuneChakraProfile::LogMethodNativeLoadEvent(this, entryPointInfo);
  3349. #endif
  3350. #ifdef _M_ARM
  3351. // For ARM we need to make sure that pipeline is synchronized with memory/cache for newly jitted code.
  3352. _InstructionSynchronizationBarrier();
  3353. #endif
  3354. entryPointInfo->SetNativeEntryPointProcessed();
  3355. }
  3356. void FunctionBody::DefaultSetNativeEntryPoint(FunctionEntryPointInfo* entryPointInfo, FunctionBody * functionBody, JavascriptMethod entryPoint)
  3357. {
  3358. Assert(functionBody->m_scriptContext->CurrentThunk == DefaultEntryThunk);
  3359. functionBody->SetNativeEntryPoint(entryPointInfo, entryPoint, entryPoint);
  3360. }
  3361. void FunctionBody::ProfileSetNativeEntryPoint(FunctionEntryPointInfo* entryPointInfo, FunctionBody * functionBody, JavascriptMethod entryPoint)
  3362. {
  3363. #ifdef ENABLE_WASM
  3364. // Do not profile WebAssembly functions
  3365. if (functionBody->IsWasmFunction())
  3366. {
  3367. functionBody->SetNativeEntryPoint(entryPointInfo, entryPoint, entryPoint);
  3368. return;
  3369. }
  3370. #endif
  3371. Assert(functionBody->m_scriptContext->CurrentThunk == ProfileEntryThunk);
  3372. functionBody->SetNativeEntryPoint(entryPointInfo, entryPoint, ProfileEntryThunk);
  3373. }
  3374. Js::JavascriptMethod FunctionBody::GetLoopBodyEntryPoint(Js::LoopHeader * loopHeader, int entryPointIndex)
  3375. {
  3376. #if DBG
  3377. this->GetLoopNumber(loopHeader);
  3378. #endif
  3379. return loopHeader->GetEntryPointInfo(entryPointIndex)->jsMethod;
  3380. }
  3381. void FunctionBody::SetLoopBodyEntryPoint(Js::LoopHeader * loopHeader, EntryPointInfo* entryPointInfo, Js::JavascriptMethod entryPoint, uint loopNum)
  3382. {
  3383. #if DBG_DUMP
  3384. if (PHASE_TRACE1(Js::JITLoopBodyPhase))
  3385. {
  3386. DumpFunctionId(true);
  3387. Output::Print(_u(": %-20s LoopBody EntryPt Loop: %2d Address : %x\n"), GetDisplayName(), loopNum, entryPoint);
  3388. Output::Flush();
  3389. }
  3390. #endif
  3391. Assert(((LoopEntryPointInfo*)entryPointInfo)->loopHeader == loopHeader);
  3392. Assert(reinterpret_cast<void*>(entryPointInfo->jsMethod) == nullptr);
  3393. entryPointInfo->jsMethod = entryPoint;
  3394. ((Js::LoopEntryPointInfo*)entryPointInfo)->totalJittedLoopIterations =
  3395. static_cast<uint8>(
  3396. min(
  3397. static_cast<uint>(static_cast<uint8>(CONFIG_FLAG(MinBailOutsBeforeRejitForLoops))) *
  3398. (Js::LoopEntryPointInfo::GetDecrLoopCountPerBailout() - 1),
  3399. 0xffu));
  3400. // reset the counter to 1 less than the threshold for TJLoopBody
  3401. if (loopHeader->GetCurrentEntryPointInfo()->GetIsAsmJSFunction())
  3402. {
  3403. loopHeader->interpretCount = entryPointInfo->GetFunctionBody()->GetLoopInterpretCount(loopHeader) - 1;
  3404. }
  3405. JS_ETW(EtwTrace::LogLoopBodyLoadEvent(this, ((LoopEntryPointInfo*)entryPointInfo), ((uint16)loopNum)));
  3406. #ifdef VTUNE_PROFILING
  3407. VTuneChakraProfile::LogLoopBodyLoadEvent(this, ((LoopEntryPointInfo*)entryPointInfo), ((uint16)loopNum));
  3408. #endif
  3409. }
  3410. #endif
  3411. void FunctionBody::MarkScript(ByteBlock *byteCodeBlock, ByteBlock* auxBlock, ByteBlock* auxContextBlock,
  3412. uint byteCodeCount, uint byteCodeInLoopCount, uint byteCodeWithoutLDACount)
  3413. {
  3414. CheckNotExecuting();
  3415. CheckEmpty();
  3416. #ifdef PERF_COUNTERS
  3417. DWORD byteCodeSize = byteCodeBlock->GetLength()
  3418. + (auxBlock? auxBlock->GetLength() : 0)
  3419. + (auxContextBlock? auxContextBlock->GetLength() : 0);
  3420. PERF_COUNTER_ADD(Code, DynamicByteCodeSize, byteCodeSize);
  3421. #endif
  3422. SetByteCodeCount(byteCodeCount);
  3423. SetByteCodeInLoopCount(byteCodeInLoopCount);
  3424. SetByteCodeWithoutLDACount(byteCodeWithoutLDACount);
  3425. executionState.InitializeExecutionModeAndLimits(this);
  3426. this->SetAuxiliaryData(auxBlock);
  3427. this->SetAuxiliaryContextData(auxContextBlock);
  3428. // Memory barrier needed here to make sure the background codegen thread's inliner
  3429. // gets all the assignment before it sees that the function has been parse
  3430. MemoryBarrier();
  3431. this->byteCodeBlock = byteCodeBlock;
  3432. PERF_COUNTER_ADD(Code, TotalByteCodeSize, byteCodeSize);
  3433. // If this is a defer parse function body, we would not have registered it
  3434. // on the function bodies list so we should register it now
  3435. if (!this->m_isFuncRegistered)
  3436. {
  3437. this->GetUtf8SourceInfo()->SetFunctionBody(this);
  3438. }
  3439. }
  3440. uint
  3441. FunctionBody::GetLoopNumber(LoopHeader const * loopHeader) const
  3442. {
  3443. LoopHeader* loopHeaderArray = this->GetLoopHeaderArray();
  3444. Assert(loopHeader >= loopHeaderArray);
  3445. uint loopNum = (uint)(loopHeader - loopHeaderArray);
  3446. Assert(loopNum < GetLoopCount());
  3447. return loopNum;
  3448. }
  3449. uint
  3450. FunctionBody::GetLoopNumberWithLock(LoopHeader const * loopHeader) const
  3451. {
  3452. LoopHeader* loopHeaderArray = this->GetLoopHeaderArrayWithLock();
  3453. Assert(loopHeader >= loopHeaderArray);
  3454. uint loopNum = (uint)(loopHeader - loopHeaderArray);
  3455. Assert(loopNum < GetLoopCount());
  3456. return loopNum;
  3457. }
  3458. #ifdef ENABLE_SCRIPT_DEBUGGING
  3459. bool FunctionBody::InstallProbe(int offset)
  3460. {
  3461. if (offset < 0 || ((uint)offset + 1) >= byteCodeBlock->GetLength())
  3462. {
  3463. return false;
  3464. }
  3465. byte* pbyteCodeBlockBuffer = this->byteCodeBlock->GetBuffer();
  3466. if(!GetProbeBackingBlock())
  3467. {
  3468. // The probe backing block is set on a different thread than the main thread
  3469. // The recycler doesn't like allocations from a different thread, so we allocate
  3470. // the backing byte code block in the arena
  3471. ArenaAllocator *pArena = m_scriptContext->AllocatorForDiagnostics();
  3472. Assert(pArena);
  3473. ByteBlock* probeBackingBlock = ByteBlock::NewFromArena(pArena, pbyteCodeBlockBuffer, byteCodeBlock->GetLength());
  3474. SetProbeBackingBlock(probeBackingBlock);
  3475. }
  3476. // Make sure Break opcode only need one byte
  3477. Assert(OpCodeUtil::IsSmallEncodedOpcode(OpCode::Break));
  3478. #if ENABLE_NATIVE_CODEGEN
  3479. Assert(!OpCodeAttr::HasMultiSizeLayout(OpCode::Break));
  3480. #endif
  3481. *(byte *)(pbyteCodeBlockBuffer + offset) = (byte)OpCode::Break;
  3482. ++m_sourceInfo.m_probeCount;
  3483. return true;
  3484. }
  3485. bool FunctionBody::UninstallProbe(int offset)
  3486. {
  3487. if (offset < 0 || ((uint)offset + 1) >= byteCodeBlock->GetLength())
  3488. {
  3489. return false;
  3490. }
  3491. byte* pbyteCodeBlockBuffer = byteCodeBlock->GetBuffer();
  3492. Js::OpCode originalOpCode = ByteCodeReader::PeekByteOp(GetProbeBackingBlock()->GetBuffer() + offset);
  3493. *(pbyteCodeBlockBuffer + offset) = (byte)originalOpCode;
  3494. --m_sourceInfo.m_probeCount;
  3495. AssertMsg(m_sourceInfo.m_probeCount >= 0, "Probe (Break Point) count became negative!");
  3496. return true;
  3497. }
  3498. bool FunctionBody::ProbeAtOffset(int offset, OpCode* pOriginalOpcode)
  3499. {
  3500. if (!GetProbeBackingBlock())
  3501. {
  3502. return false;
  3503. }
  3504. if (offset < 0 || ((uint)offset + 1) >= this->byteCodeBlock->GetLength())
  3505. {
  3506. AssertMsg(false, "ProbeAtOffset called with out of bounds offset");
  3507. return false;
  3508. }
  3509. Js::OpCode runningOpCode = ByteCodeReader::PeekByteOp(this->byteCodeBlock->GetBuffer() + offset);
  3510. Js::OpCode originalOpcode = ByteCodeReader::PeekByteOp(GetProbeBackingBlock()->GetBuffer() + offset);
  3511. if ( runningOpCode != originalOpcode)
  3512. {
  3513. *pOriginalOpcode = originalOpcode;
  3514. return true;
  3515. }
  3516. else
  3517. {
  3518. // e.g. inline break or a step hit and is checking for a bp
  3519. return false;
  3520. }
  3521. }
  3522. #endif
  3523. void FunctionBody::SetStackNestedFuncParent(FunctionInfo * parentFunctionInfo)
  3524. {
  3525. FunctionBody * parentFunctionBody = parentFunctionInfo->GetFunctionBody();
  3526. RecyclerWeakReference<FunctionInfo>* parent = this->GetStackNestedFuncParent();
  3527. if (parent != nullptr)
  3528. {
  3529. Assert(parent->Get() == parentFunctionInfo);
  3530. return;
  3531. }
  3532. // Redeferral invalidates this assertion, as we may be recompiling with a different view of nested functions and
  3533. // thus making different stack-nested-function decisions. I'm inclined to allow this, since things that have been
  3534. // re-deferred will likely not be executed again, so it makes sense to exclude them from our analysis.
  3535. // Assert(CanDoStackNestedFunc());
  3536. Assert(parentFunctionBody->DoStackNestedFunc());
  3537. this->SetAuxPtr<AuxPointerType::StackNestedFuncParent>(this->GetScriptContext()->GetRecycler()->CreateWeakReferenceHandle(parentFunctionInfo));
  3538. }
  3539. FunctionInfo * FunctionBody::GetStackNestedFuncParentStrongRef()
  3540. {
  3541. Assert(this->GetStackNestedFuncParent() != nullptr);
  3542. return this->GetStackNestedFuncParent()->Get();
  3543. }
  3544. RecyclerWeakReference<FunctionInfo> * FunctionBody::GetStackNestedFuncParent()
  3545. {
  3546. return this->GetAuxPtr<AuxPointerType::StackNestedFuncParent>();
  3547. }
  3548. FunctionInfo * FunctionBody::GetAndClearStackNestedFuncParent()
  3549. {
  3550. if (this->GetAuxPtr<AuxPointerType::StackNestedFuncParent>())
  3551. {
  3552. FunctionInfo * parentFunctionInfo = GetStackNestedFuncParentStrongRef();
  3553. ClearStackNestedFuncParent();
  3554. return parentFunctionInfo;
  3555. }
  3556. return nullptr;
  3557. }
  3558. void FunctionBody::ClearStackNestedFuncParent()
  3559. {
  3560. this->SetAuxPtr<AuxPointerType::StackNestedFuncParent>(nullptr);
  3561. }
  3562. void FunctionBody::CreateCacheIdToPropertyIdMap(uint rootObjectLoadInlineCacheStart, uint rootObjectLoadMethodInlineCacheStart,
  3563. uint rootObjectStoreInlineCacheStart,
  3564. uint totalFieldAccessInlineCacheCount, uint isInstInlineCacheCount)
  3565. {
  3566. Assert(this->GetRootObjectLoadInlineCacheStart() == 0);
  3567. Assert(this->GetRootObjectLoadMethodInlineCacheStart() == 0);
  3568. Assert(this->GetRootObjectStoreInlineCacheStart() == 0);
  3569. Assert(this->GetInlineCacheCount() == 0);
  3570. Assert(this->GetIsInstInlineCacheCount() == 0);
  3571. this->SetRootObjectLoadInlineCacheStart(rootObjectLoadInlineCacheStart);
  3572. this->SetRootObjectLoadMethodInlineCacheStart(rootObjectLoadMethodInlineCacheStart);
  3573. this->SetRootObjectStoreInlineCacheStart(rootObjectStoreInlineCacheStart);
  3574. this->SetInlineCacheCount(totalFieldAccessInlineCacheCount);
  3575. this->SetIsInstInlineCacheCount(isInstInlineCacheCount);
  3576. this->CreateCacheIdToPropertyIdMap();
  3577. }
  3578. void FunctionBody::CreateCacheIdToPropertyIdMap()
  3579. {
  3580. Assert(this->cacheIdToPropertyIdMap == nullptr);
  3581. Assert(this->inlineCaches == nullptr);
  3582. uint count = this->GetInlineCacheCount() ;
  3583. if (count!= 0)
  3584. {
  3585. this->cacheIdToPropertyIdMap =
  3586. RecyclerNewArrayLeaf(this->m_scriptContext->GetRecycler(), PropertyId, count);
  3587. #if DBG
  3588. for (uint i = 0; i < count; i++)
  3589. {
  3590. this->cacheIdToPropertyIdMap[i] = Js::Constants::NoProperty;
  3591. }
  3592. #endif
  3593. }
  3594. }
  3595. #if DBG
  3596. void FunctionBody::VerifyCacheIdToPropertyIdMap()
  3597. {
  3598. uint count = this->GetInlineCacheCount();
  3599. for (uint i = 0; i < count; i++)
  3600. {
  3601. Assert(this->cacheIdToPropertyIdMap[i] != Js::Constants::NoProperty);
  3602. }
  3603. }
  3604. #endif
  3605. void FunctionBody::SetPropertyIdForCacheId(uint cacheId, PropertyId propertyId)
  3606. {
  3607. Assert(this->cacheIdToPropertyIdMap != nullptr);
  3608. Assert(cacheId < this->GetInlineCacheCount());
  3609. Assert(this->cacheIdToPropertyIdMap[cacheId] == Js::Constants::NoProperty);
  3610. this->cacheIdToPropertyIdMap[cacheId] = propertyId;
  3611. }
  3612. void FunctionBody::CreateReferencedPropertyIdMap(uint referencedPropertyIdCount)
  3613. {
  3614. this->SetReferencedPropertyIdCount(referencedPropertyIdCount);
  3615. this->CreateReferencedPropertyIdMap();
  3616. }
  3617. void FunctionBody::CreateReferencedPropertyIdMap()
  3618. {
  3619. Assert(this->GetReferencedPropertyIdMap() == nullptr);
  3620. uint count = this->GetReferencedPropertyIdCount();
  3621. if (count!= 0)
  3622. {
  3623. this->SetReferencedPropertyIdMap(RecyclerNewArrayLeaf(this->m_scriptContext->GetRecycler(), PropertyId, count));
  3624. #if DBG
  3625. for (uint i = 0; i < count; i++)
  3626. {
  3627. this->GetReferencedPropertyIdMap()[i] = Js::Constants::NoProperty;
  3628. }
  3629. #endif
  3630. }
  3631. }
  3632. #if DBG
  3633. void FunctionBody::VerifyReferencedPropertyIdMap()
  3634. {
  3635. uint count = this->GetReferencedPropertyIdCount();
  3636. for (uint i = 0; i < count; i++)
  3637. {
  3638. Assert(this->GetReferencedPropertyIdMap()[i] != Js::Constants::NoProperty);
  3639. }
  3640. }
  3641. #endif
  3642. PropertyId FunctionBody::GetReferencedPropertyId(uint index)
  3643. {
  3644. if (index < (uint)TotalNumberOfBuiltInProperties)
  3645. {
  3646. return index;
  3647. }
  3648. uint mapIndex = index - TotalNumberOfBuiltInProperties;
  3649. return GetReferencedPropertyIdWithMapIndex(mapIndex);
  3650. }
  3651. PropertyId FunctionBody::GetReferencedPropertyIdWithLock(uint index)
  3652. {
  3653. if (index < (uint)TotalNumberOfBuiltInProperties)
  3654. {
  3655. return index;
  3656. }
  3657. uint mapIndex = index - TotalNumberOfBuiltInProperties;
  3658. return GetReferencedPropertyIdWithMapIndexWithLock(mapIndex);
  3659. }
  3660. PropertyId FunctionBody::GetReferencedPropertyIdWithMapIndex(uint mapIndex)
  3661. {
  3662. Assert(this->GetReferencedPropertyIdMap());
  3663. Assert(mapIndex < this->GetReferencedPropertyIdCount());
  3664. return this->GetReferencedPropertyIdMap()[mapIndex];
  3665. }
  3666. PropertyId FunctionBody::GetReferencedPropertyIdWithMapIndexWithLock(uint mapIndex)
  3667. {
  3668. Assert(this->GetReferencedPropertyIdMapWithLock());
  3669. Assert(mapIndex < this->GetReferencedPropertyIdCount());
  3670. return this->GetReferencedPropertyIdMapWithLock()[mapIndex];
  3671. }
  3672. void FunctionBody::SetReferencedPropertyIdWithMapIndex(uint mapIndex, PropertyId propertyId)
  3673. {
  3674. Assert(propertyId >= TotalNumberOfBuiltInProperties);
  3675. Assert(mapIndex < this->GetReferencedPropertyIdCount());
  3676. Assert(this->GetReferencedPropertyIdMap() != nullptr);
  3677. Assert(this->GetReferencedPropertyIdMap()[mapIndex] == Js::Constants::NoProperty);
  3678. this->GetReferencedPropertyIdMap()[mapIndex] = propertyId;
  3679. }
  3680. void FunctionBody::CreateConstantTable()
  3681. {
  3682. Assert(this->GetConstTable() == nullptr);
  3683. Assert(GetConstantCount() > FirstRegSlot);
  3684. this->SetConstTable(RecyclerNewArrayZ(this->m_scriptContext->GetRecycler(), Field(Var), GetConstantCount()));
  3685. // Initialize with the root object, which will always be recorded here.
  3686. Js::RootObjectBase * rootObject = this->LoadRootObject();
  3687. if (rootObject)
  3688. {
  3689. this->RecordConstant(RootObjectRegSlot, rootObject);
  3690. }
  3691. else
  3692. {
  3693. Assert(false);
  3694. this->RecordConstant(RootObjectRegSlot, this->m_scriptContext->GetLibrary()->GetUndefined());
  3695. }
  3696. }
  3697. void FunctionBody::RecordConstant(RegSlot location, Var var)
  3698. {
  3699. Assert(location < GetConstantCount());
  3700. Assert(this->GetConstTable());
  3701. Assert(var != nullptr);
  3702. Assert(this->GetConstTable()[location - FunctionBody::FirstRegSlot] == nullptr);
  3703. this->GetConstTable()[location - FunctionBody::FirstRegSlot] = var;
  3704. }
  3705. void FunctionBody::RecordNullObject(RegSlot location)
  3706. {
  3707. ScriptContext *scriptContext = this->GetScriptContext();
  3708. Var nullObject = JavascriptOperators::OP_LdNull(scriptContext);
  3709. this->RecordConstant(location, nullObject);
  3710. }
  3711. void FunctionBody::RecordUndefinedObject(RegSlot location)
  3712. {
  3713. ScriptContext *scriptContext = this->GetScriptContext();
  3714. Var undefObject = JavascriptOperators::OP_LdUndef(scriptContext);
  3715. this->RecordConstant(location, undefObject);
  3716. }
  3717. void FunctionBody::RecordTrueObject(RegSlot location)
  3718. {
  3719. ScriptContext *scriptContext = this->GetScriptContext();
  3720. Var trueObject = JavascriptBoolean::OP_LdTrue(scriptContext);
  3721. this->RecordConstant(location, trueObject);
  3722. }
  3723. void FunctionBody::RecordFalseObject(RegSlot location)
  3724. {
  3725. ScriptContext *scriptContext = this->GetScriptContext();
  3726. Var falseObject = JavascriptBoolean::OP_LdFalse(scriptContext);
  3727. this->RecordConstant(location, falseObject);
  3728. }
  3729. void FunctionBody::RecordIntConstant(RegSlot location, unsigned int val)
  3730. {
  3731. ScriptContext *scriptContext = this->GetScriptContext();
  3732. Var intConst = JavascriptNumber::ToVar((int32)val, scriptContext);
  3733. this->RecordConstant(location, intConst);
  3734. }
  3735. void FunctionBody::RecordStrConstant(RegSlot location, LPCOLESTR psz, uint32 cch, bool forcePropertyString)
  3736. {
  3737. ScriptContext *scriptContext = this->GetScriptContext();
  3738. PropertyRecord const * propertyRecord;
  3739. if (forcePropertyString)
  3740. {
  3741. scriptContext->GetOrAddPropertyRecord(psz, cch, &propertyRecord);
  3742. }
  3743. else
  3744. {
  3745. scriptContext->FindPropertyRecord(psz, cch, &propertyRecord);
  3746. }
  3747. Var str;
  3748. if (propertyRecord == nullptr)
  3749. {
  3750. str = JavascriptString::NewCopyBuffer(psz, cch, scriptContext);
  3751. }
  3752. else
  3753. {
  3754. // If a particular string constant already has a propertyId, just create a property string for it
  3755. // as it might be likely that it is used for a property lookup
  3756. str = scriptContext->GetPropertyString(propertyRecord->GetPropertyId());
  3757. }
  3758. this->RecordConstant(location, str);
  3759. }
  3760. void FunctionBody::RecordFloatConstant(RegSlot location, double d)
  3761. {
  3762. ScriptContext *scriptContext = this->GetScriptContext();
  3763. Var floatConst = JavascriptNumber::ToVarIntCheck(d, scriptContext);
  3764. this->RecordConstant(location, floatConst);
  3765. }
  3766. void FunctionBody::RecordNullDisplayConstant(RegSlot location)
  3767. {
  3768. this->RecordConstant(location, (Js::Var)&Js::NullFrameDisplay);
  3769. }
  3770. void FunctionBody::RecordStrictNullDisplayConstant(RegSlot location)
  3771. {
  3772. this->RecordConstant(location, (Js::Var)&Js::StrictNullFrameDisplay);
  3773. }
  3774. void FunctionBody::InitConstantSlots(Var *dstSlots)
  3775. {
  3776. // Initialize the given slots from the constant table.
  3777. uint32 constCount = GetConstantCount();
  3778. Assert(constCount > FunctionBody::FirstRegSlot);
  3779. js_memcpy_s(dstSlots, (constCount - FunctionBody::FirstRegSlot) * sizeof(Var),
  3780. this->GetConstTable(), (constCount - FunctionBody::FirstRegSlot) * sizeof(Var));
  3781. }
  3782. Var FunctionBody::GetConstantVar(RegSlot location)
  3783. {
  3784. Assert(this->GetConstTable());
  3785. Assert(location < GetConstantCount());
  3786. Assert(location != 0);
  3787. return this->GetConstTable()[location - FunctionBody::FirstRegSlot];
  3788. }
  3789. #if DBG_DUMP
  3790. void FunctionBody::Dump()
  3791. {
  3792. Js::ByteCodeDumper::Dump(this);
  3793. }
  3794. void FunctionBody::DumpScopes()
  3795. {
  3796. if(this->GetScopeObjectChain())
  3797. {
  3798. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  3799. Output::Print(_u("%s (%s) :\n"), this->GetDisplayName(), this->GetDebugNumberSet(debugStringBuffer));
  3800. this->GetScopeObjectChain()->pScopeChain->Map( [=] (uint index, DebuggerScope* scope )
  3801. {
  3802. scope->Dump();
  3803. });
  3804. }
  3805. }
  3806. #if ENABLE_NATIVE_CODEGEN
  3807. void EntryPointInfo::DumpNativeOffsetMaps()
  3808. {
  3809. // Native Offsets
  3810. if (this->HasNativeEntryPointData())
  3811. {
  3812. auto& nativeOffsetMaps = this->GetNativeEntryPointData()->GetNativeOffsetMaps();
  3813. if (nativeOffsetMaps.Count() > 0)
  3814. {
  3815. Output::Print(_u("Native Map: baseAddr: 0x%0Ix, size: 0x%0Ix\nstatementId, offset range, address range\n"),
  3816. this->GetNativeAddress(),
  3817. this->GetCodeSize());
  3818. int count = nativeOffsetMaps.Count();
  3819. for (int i = 0; i < count; i++)
  3820. {
  3821. const NativeEntryPointData::NativeOffsetMap* map = &nativeOffsetMaps.Item(i);
  3822. Output::Print(_u("S%4d, (%5d, %5d) (0x%012Ix, 0x%012Ix)\n"), map->statementIndex,
  3823. map->nativeOffsetSpan.begin,
  3824. map->nativeOffsetSpan.end,
  3825. map->nativeOffsetSpan.begin + this->GetNativeAddress(),
  3826. map->nativeOffsetSpan.end + this->GetNativeAddress());
  3827. }
  3828. }
  3829. }
  3830. }
  3831. #endif
  3832. void FunctionBody::DumpStatementMaps()
  3833. {
  3834. // Source Map to ByteCode
  3835. StatementMapList * pStatementMaps = this->GetStatementMaps();
  3836. if (pStatementMaps)
  3837. {
  3838. Output::Print(_u("Statement Map:\nstatementId, SourceSpan, ByteCodeSpan\n"));
  3839. int count = pStatementMaps->Count();
  3840. for(int i = 0; i < count; i++)
  3841. {
  3842. StatementMap* map = pStatementMaps->Item(i);
  3843. Output::Print(_u("S%4d, (C%5d, C%5d) (B%5d, B%5d) Inner=%d\n"), i,
  3844. map->sourceSpan.begin,
  3845. map->sourceSpan.end,
  3846. map->byteCodeSpan.begin,
  3847. map->byteCodeSpan.end,
  3848. map->isSubexpression);
  3849. }
  3850. }
  3851. }
  3852. #if ENABLE_NATIVE_CODEGEN
  3853. void EntryPointInfo::DumpNativeThrowSpanSequence()
  3854. {
  3855. // Native Throw Map
  3856. SmallSpanSequence * nativeThrowSpanSequence = this->GetNativeEntryPointData()->GetNativeThrowSpanSequence();
  3857. if (nativeThrowSpanSequence)
  3858. {
  3859. Output::Print(_u("Native Throw Map: baseAddr: 0x%0Ix, size: 0x%Ix\nstatementId, offset range, address range\n"),
  3860. this->GetNativeAddress(),
  3861. this->GetCodeSize());
  3862. int count = nativeThrowSpanSequence->Count();
  3863. SmallSpanSequenceIter iter;
  3864. for (int i = 0; i < count; i++)
  3865. {
  3866. StatementData data;
  3867. if (nativeThrowSpanSequence->Item(i, iter, data))
  3868. {
  3869. Output::Print(_u("S%4d, (%5d -----) (0x%012Ix --------)\n"), data.sourceBegin, // statementIndex
  3870. data.bytecodeBegin, // nativeOffset
  3871. data.bytecodeBegin + this->GetNativeAddress());
  3872. }
  3873. }
  3874. }
  3875. }
  3876. #endif
  3877. void FunctionBody::PrintStatementSourceLine(uint statementIndex)
  3878. {
  3879. if (m_isWasmFunction)
  3880. {
  3881. // currently no source view support for wasm
  3882. return;
  3883. }
  3884. const uint startOffset = GetStatementStartOffset(statementIndex);
  3885. // startOffset should only be 0 if statementIndex is 0, otherwise it is EOF and we should skip printing anything
  3886. if (startOffset != 0 || statementIndex == 0)
  3887. {
  3888. PrintStatementSourceLineFromStartOffset(startOffset);
  3889. }
  3890. }
  3891. void FunctionBody::PrintStatementSourceLineFromStartOffset(uint cchStartOffset)
  3892. {
  3893. ULONG line;
  3894. LONG col;
  3895. LPCUTF8 source = GetStartOfDocument(_u("FunctionBody::PrintStatementSourceLineFromStartOffset"));
  3896. Utf8SourceInfo* sourceInfo = this->GetUtf8SourceInfo();
  3897. Assert(sourceInfo != nullptr);
  3898. LPCUTF8 sourceInfoSrc = sourceInfo->GetSource(_u("FunctionBody::PrintStatementSourceLineFromStartOffset"));
  3899. if(!sourceInfoSrc)
  3900. {
  3901. Assert(sourceInfo->GetIsLibraryCode());
  3902. return;
  3903. }
  3904. if( source != sourceInfoSrc )
  3905. {
  3906. Output::Print(_u("\nDETECTED MISMATCH:\n"));
  3907. Output::Print(_u("GetUtf8SourceInfo()->GetSource(): 0x%08X: %.*s ...\n"), sourceInfo, 16, sourceInfo);
  3908. Output::Print(_u("GetStartOfDocument(): 0x%08X: %.*s ...\n"), source, 16, source);
  3909. AssertMsg(false, "Non-matching start of document");
  3910. }
  3911. GetLineCharOffsetFromStartChar(cchStartOffset, &line, &col, false /*canAllocateLineCache*/);
  3912. if (sourceInfo->GetSourceHolder() != ISourceHolder::GetEmptySourceHolder())
  3913. {
  3914. WORD color = 0;
  3915. if (Js::Configuration::Global.flags.DumpLineNoInColor)
  3916. {
  3917. color = Output::SetConsoleForeground(12);
  3918. }
  3919. Output::Print(_u("\n\n Line %3d: "), line + 1);
  3920. // Need to match up cchStartOffset to appropriate cbStartOffset given function's cbStartOffset and cchStartOffset
  3921. size_t i = utf8::CharacterIndexToByteIndex(source, sourceInfo->GetCbLength(), cchStartOffset, this->m_cbStartOffset, this->m_cchStartOffset);
  3922. size_t lastOffset = StartOffset() + LengthInBytes();
  3923. for (;i < lastOffset && source[i] != '\n' && source[i] != '\r'; i++)
  3924. {
  3925. Output::Print(_u("%C"), source[i]);
  3926. }
  3927. Output::Print(_u("\n"));
  3928. Output::Print(_u(" Col %4d:%s^\n"), col + 1, ((col+1)<10000) ? _u(" ") : _u(""));
  3929. if (color != 0)
  3930. {
  3931. Output::SetConsoleForeground(color);
  3932. }
  3933. }
  3934. }
  3935. #endif // DBG_DUMP
  3936. /**
  3937. * Get the source code offset for the given <statementIndex>.
  3938. */
  3939. uint FunctionBody::GetStatementStartOffset(const uint statementIndex)
  3940. {
  3941. uint startOffset = 0;
  3942. if (statementIndex != Js::Constants::NoStatementIndex)
  3943. {
  3944. const Js::FunctionBody::SourceInfo * sourceInfo = &(this->m_sourceInfo);
  3945. if (sourceInfo->pSpanSequence != nullptr)
  3946. {
  3947. Js::SmallSpanSequenceIter iter;
  3948. sourceInfo->pSpanSequence->Reset(iter);
  3949. Js::StatementData data;
  3950. sourceInfo->pSpanSequence->Item(statementIndex, iter, data);
  3951. startOffset = data.sourceBegin;
  3952. }
  3953. else
  3954. {
  3955. int index = statementIndex;
  3956. Js::FunctionBody::StatementMap * statementMap = GetNextNonSubexpressionStatementMap(GetStatementMaps(), index);
  3957. startOffset = statementMap->sourceSpan.Begin();
  3958. }
  3959. }
  3960. return startOffset;
  3961. }
  3962. #ifdef IR_VIEWER
  3963. /* BEGIN potentially reusable code */
  3964. /*
  3965. This code could be reused for locating source code in a debugger or to
  3966. retrieve the text of source statements.
  3967. Currently this code is used to retrieve the text of a source code statement
  3968. in the IR_VIEWER feature.
  3969. */
  3970. /**
  3971. * Given a statement's starting offset in the source code, calculate the beginning and end of a statement,
  3972. * as well as the line and column number where the statement appears.
  3973. *
  3974. * @param startOffset (input) The offset into the source code where this statement begins.
  3975. * @param sourceBegin (output) The beginning of the statement in the source string.
  3976. * @param sourceEnd (output) The end of the statement in the source string.
  3977. * @param line (output) The line number where the statement appeared in the source.
  3978. * @param col (output) The column number where the statement appeared in the source.
  3979. */
  3980. void FunctionBody::GetSourceLineFromStartOffset(const uint startOffset, LPCUTF8 *sourceBegin, LPCUTF8 *sourceEnd,
  3981. ULONG * line, LONG * col)
  3982. {
  3983. //
  3984. // get source info
  3985. //
  3986. LPCUTF8 source = GetStartOfDocument(_u("IR Viewer FunctionBody::GetSourceLineFromStartOffset"));
  3987. Utf8SourceInfo* sourceInfo = this->GetUtf8SourceInfo();
  3988. Assert(sourceInfo != nullptr);
  3989. LPCUTF8 sourceInfoSrc = sourceInfo->GetSource(_u("IR Viewer FunctionBody::GetSourceLineFromStartOffset"));
  3990. if (!sourceInfoSrc)
  3991. {
  3992. Assert(sourceInfo->GetIsLibraryCode());
  3993. return;
  3994. }
  3995. if (source != sourceInfoSrc)
  3996. {
  3997. Output::Print(_u("\nDETECTED MISMATCH:\n"));
  3998. Output::Print(_u("GetUtf8SourceInfo()->GetSource(): 0x%08X: %.*s ...\n"), sourceInfo, 16, sourceInfo);
  3999. Output::Print(_u("GetStartOfDocument(): 0x%08X: %.*s ...\n"), source, 16, source);
  4000. AssertMsg(false, "Non-matching start of document");
  4001. }
  4002. //
  4003. // calculate source line info
  4004. //
  4005. size_t cbStartOffset = utf8::CharacterIndexToByteIndex(source, sourceInfo->GetCbLength(), (const charcount_t)startOffset, (size_t)this->m_cbStartOffset, (charcount_t)this->m_cchStartOffset);
  4006. GetLineCharOffsetFromStartChar(startOffset, line, col);
  4007. size_t lastOffset = StartOffset() + LengthInBytes();
  4008. size_t i = 0;
  4009. for (i = cbStartOffset; i < lastOffset && source[i] != '\n' && source[i] != '\r'; i++)
  4010. {
  4011. // do nothing; scan until end of statement
  4012. }
  4013. size_t cbEndOffset = i;
  4014. //
  4015. // return
  4016. //
  4017. *sourceBegin = &source[cbStartOffset];
  4018. *sourceEnd = &source[cbEndOffset];
  4019. }
  4020. /**
  4021. * Given a statement index and output parameters, calculate the beginning and end of a statement,
  4022. * as well as the line and column number where the statement appears.
  4023. *
  4024. * @param statementIndex (input) The statement's index (as used by the StatementBoundary pragma).
  4025. * @param sourceBegin (output) The beginning of the statement in the source string.
  4026. * @param sourceEnd (output) The end of the statement in the source string.
  4027. * @param line (output) The line number where the statement appeared in the source.
  4028. * @param col (output) The column number where the statement appeared in the source.
  4029. */
  4030. void FunctionBody::GetStatementSourceInfo(const uint statementIndex, LPCUTF8 *sourceBegin, LPCUTF8 *sourceEnd,
  4031. ULONG * line, LONG * col)
  4032. {
  4033. const size_t startOffset = GetStatementStartOffset(statementIndex);
  4034. // startOffset should only be 0 if statementIndex is 0, otherwise it is EOF and we should return empty string
  4035. if (startOffset != 0 || statementIndex == 0)
  4036. {
  4037. GetSourceLineFromStartOffset(startOffset, sourceBegin, sourceEnd, line, col);
  4038. }
  4039. else
  4040. {
  4041. *sourceBegin = nullptr;
  4042. *sourceEnd = nullptr;
  4043. *line = 0;
  4044. *col = 0;
  4045. return;
  4046. }
  4047. }
  4048. /* END potentially reusable code */
  4049. #endif /* IR_VIEWER */
  4050. #if ENABLE_TTD
  4051. void FunctionBody::GetSourceLineFromStartOffset_TTD(const uint startOffset, ULONG* line, LONG* col)
  4052. {
  4053. GetLineCharOffsetFromStartChar(startOffset, line, col);
  4054. }
  4055. #endif
  4056. #ifdef IR_VIEWER
  4057. Js::DynamicObject * FunctionBody::GetIRDumpBaseObject()
  4058. {
  4059. if (!this->m_irDumpBaseObject)
  4060. {
  4061. this->m_irDumpBaseObject = this->m_scriptContext->GetLibrary()->CreateObject();
  4062. }
  4063. return this->m_irDumpBaseObject;
  4064. }
  4065. #endif /* IR_VIEWER */
  4066. #if ENABLE_NATIVE_CODEGEN
  4067. #ifdef VTUNE_PROFILING
  4068. #include "jitprofiling.h"
  4069. int EntryPointInfo::GetNativeOffsetMapCount() const
  4070. {
  4071. return this->GetNativeEntryPointData()->GetNativeOffsetMaps().Count();
  4072. }
  4073. uint EntryPointInfo::PopulateLineInfo(void* pInfo, FunctionBody* body)
  4074. {
  4075. auto& nativeOffsetMaps = this->GetNativeEntryPointData()->GetNativeOffsetMaps();
  4076. LineNumberInfo* pLineInfo = (LineNumberInfo*)pInfo;
  4077. ULONG functionLineNumber = body->GetLineNumber();
  4078. pLineInfo[0].Offset = 0;
  4079. pLineInfo[0].LineNumber = functionLineNumber;
  4080. int lineNumber = 0;
  4081. int j = 1; // start with 1 since offset 0 has already been populated with function line number
  4082. int count = nativeOffsetMaps.Count();
  4083. for(int i = 0; i < count; i++)
  4084. {
  4085. const NativeEntryPointData::NativeOffsetMap* map = &nativeOffsetMaps.Item(i);
  4086. uint32 statementIndex = map->statementIndex;
  4087. if (statementIndex == 0)
  4088. {
  4089. // statementIndex is 0, first line in the function, populate with function line number
  4090. pLineInfo[j].Offset = map->nativeOffsetSpan.begin;
  4091. pLineInfo[j].LineNumber = functionLineNumber;
  4092. j++;
  4093. }
  4094. lineNumber = body->GetSourceLineNumber(statementIndex);
  4095. if (lineNumber != 0)
  4096. {
  4097. pLineInfo[j].Offset = map->nativeOffsetSpan.end;
  4098. pLineInfo[j].LineNumber = lineNumber;
  4099. j++;
  4100. }
  4101. }
  4102. return j;
  4103. }
  4104. ULONG FunctionBody::GetSourceLineNumber(uint statementIndex)
  4105. {
  4106. ULONG line = 0;
  4107. if (statementIndex != Js::Constants::NoStatementIndex)
  4108. {
  4109. uint startOffset = GetStartOffset(statementIndex);
  4110. if (startOffset != 0 || statementIndex == 0)
  4111. {
  4112. GetLineCharOffsetFromStartChar(startOffset, &line, nullptr, false /*canAllocateLineCache*/);
  4113. line = line + 1;
  4114. }
  4115. }
  4116. return line;
  4117. }
  4118. uint FunctionBody::GetStartOffset(uint statementIndex) const
  4119. {
  4120. uint startOffset = 0;
  4121. const Js::FunctionBody::SourceInfo * sourceInfo = &this->m_sourceInfo;
  4122. if (sourceInfo->pSpanSequence != nullptr)
  4123. {
  4124. Js::SmallSpanSequenceIter iter;
  4125. sourceInfo->pSpanSequence->Reset(iter);
  4126. Js::StatementData data;
  4127. sourceInfo->pSpanSequence->Item(statementIndex, iter, data);
  4128. startOffset = data.sourceBegin;
  4129. }
  4130. else
  4131. {
  4132. int index = statementIndex;
  4133. Js::FunctionBody::StatementMap * statementMap = GetNextNonSubexpressionStatementMap(GetStatementMaps(), index);
  4134. startOffset = statementMap->sourceSpan.Begin();
  4135. }
  4136. return startOffset;
  4137. }
  4138. #endif
  4139. #endif
  4140. void ParseableFunctionInfo::SetIsNonUserCode(bool set)
  4141. {
  4142. // Mark current function as a non-user code, so that we can distinguish cases where exceptions are
  4143. // caught in non-user code (see ProbeContainer::HasAllowedForException).
  4144. SetFlags(set, Flags_NonUserCode);
  4145. // Propagate setting for all functions in this scope (nested).
  4146. this->ForEachNestedFunc([&](FunctionProxy* proxy, uint32 index)
  4147. {
  4148. ParseableFunctionInfo * pBody = proxy->GetParseableFunctionInfo();
  4149. if (pBody != nullptr)
  4150. {
  4151. pBody->SetIsNonUserCode(set);
  4152. }
  4153. return true;
  4154. });
  4155. }
  4156. void FunctionBody::InsertSymbolToRegSlotList(JsUtil::CharacterBuffer<WCHAR> const& propName, RegSlot reg, RegSlot totalRegsCount)
  4157. {
  4158. if (totalRegsCount > 0)
  4159. {
  4160. PropertyId propertyId = GetOrAddPropertyIdTracked(propName);
  4161. InsertSymbolToRegSlotList(reg, propertyId, totalRegsCount);
  4162. }
  4163. }
  4164. void FunctionBody::InsertSymbolToRegSlotList(RegSlot reg, PropertyId propertyId, RegSlot totalRegsCount)
  4165. {
  4166. if (totalRegsCount > 0)
  4167. {
  4168. if (this->GetPropertyIdOnRegSlotsContainer() == nullptr)
  4169. {
  4170. this->SetPropertyIdOnRegSlotsContainer(PropertyIdOnRegSlotsContainer::New(m_scriptContext->GetRecycler()));
  4171. }
  4172. if (this->GetPropertyIdOnRegSlotsContainer()->propertyIdsForRegSlots == nullptr)
  4173. {
  4174. this->GetPropertyIdOnRegSlotsContainer()->CreateRegSlotsArray(m_scriptContext->GetRecycler(), totalRegsCount);
  4175. }
  4176. Assert(this->GetPropertyIdOnRegSlotsContainer() != nullptr);
  4177. this->GetPropertyIdOnRegSlotsContainer()->Insert(reg, propertyId);
  4178. }
  4179. }
  4180. void FunctionBody::SetPropertyIdsOfFormals(PropertyIdArray * formalArgs)
  4181. {
  4182. Assert(formalArgs);
  4183. if (this->GetPropertyIdOnRegSlotsContainer() == nullptr)
  4184. {
  4185. this->SetPropertyIdOnRegSlotsContainer(PropertyIdOnRegSlotsContainer::New(m_scriptContext->GetRecycler()));
  4186. }
  4187. this->GetPropertyIdOnRegSlotsContainer()->SetFormalArgs(formalArgs);
  4188. }
  4189. #ifdef ENABLE_SCRIPT_PROFILING
  4190. HRESULT FunctionBody::RegisterFunction(BOOL fChangeMode, BOOL fOnlyCurrent)
  4191. {
  4192. if (!this->IsFunctionParsed())
  4193. {
  4194. return S_OK;
  4195. }
  4196. HRESULT hr = this->ReportFunctionCompiled();
  4197. if (FAILED(hr))
  4198. {
  4199. return hr;
  4200. }
  4201. if (fChangeMode)
  4202. {
  4203. this->SetEntryToProfileMode();
  4204. }
  4205. if (!fOnlyCurrent)
  4206. {
  4207. for (uint uIndex = 0; uIndex < this->GetNestedCount(); uIndex++)
  4208. {
  4209. Js::ParseableFunctionInfo * pBody = this->GetNestedFunctionForExecution(uIndex);
  4210. if (pBody == nullptr || !pBody->IsFunctionParsed())
  4211. {
  4212. continue;
  4213. }
  4214. hr = pBody->GetFunctionBody()->RegisterFunction(fChangeMode);
  4215. if (FAILED(hr))
  4216. {
  4217. break;
  4218. }
  4219. }
  4220. }
  4221. return hr;
  4222. }
  4223. HRESULT FunctionBody::ReportScriptCompiled()
  4224. {
  4225. AssertMsg(m_scriptContext != nullptr, "Script Context is null when reporting function information");
  4226. PROFILER_SCRIPT_TYPE type = IsDynamicScript() ? PROFILER_SCRIPT_TYPE_DYNAMIC : PROFILER_SCRIPT_TYPE_USER;
  4227. IDebugDocumentContext *pDebugDocumentContext = nullptr;
  4228. this->m_scriptContext->GetDocumentContext(this, &pDebugDocumentContext);
  4229. HRESULT hr = m_scriptContext->OnScriptCompiled((PROFILER_TOKEN) this->GetUtf8SourceInfo()->GetSourceInfoId(), type, pDebugDocumentContext);
  4230. RELEASEPTR(pDebugDocumentContext);
  4231. return hr;
  4232. }
  4233. HRESULT FunctionBody::ReportFunctionCompiled()
  4234. {
  4235. // Some assumptions by Logger interface.
  4236. // to send NULL as a name in case the name is anonymous and hint is anonymous code.
  4237. const char16 *pwszName = GetExternalDisplayName();
  4238. IDebugDocumentContext *pDebugDocumentContext = nullptr;
  4239. this->m_scriptContext->GetDocumentContext(this, &pDebugDocumentContext);
  4240. SetHasFunctionCompiledSent(true);
  4241. HRESULT hr = m_scriptContext->OnFunctionCompiled(m_functionNumber, (PROFILER_TOKEN) this->GetUtf8SourceInfo()->GetSourceInfoId(), pwszName, nullptr, pDebugDocumentContext);
  4242. RELEASEPTR(pDebugDocumentContext);
  4243. #if DBG
  4244. if (m_iProfileSession >= m_scriptContext->GetProfileSession())
  4245. {
  4246. OUTPUT_TRACE_DEBUGONLY(Js::ScriptProfilerPhase, _u("FunctionBody::ReportFunctionCompiled, Duplicate compile event (%d < %d) for FunctionNumber : %d\n"),
  4247. m_iProfileSession, m_scriptContext->GetProfileSession(), m_functionNumber);
  4248. }
  4249. AssertMsg(m_iProfileSession < m_scriptContext->GetProfileSession(), "Duplicate compile event sent");
  4250. m_iProfileSession = m_scriptContext->GetProfileSession();
  4251. #endif
  4252. return hr;
  4253. }
  4254. void FunctionBody::SetEntryToProfileMode()
  4255. {
  4256. #if ENABLE_NATIVE_CODEGEN
  4257. AssertMsg(this->m_scriptContext->CurrentThunk == ProfileEntryThunk, "ScriptContext not in profile mode");
  4258. #if DBG
  4259. AssertMsg(m_iProfileSession == m_scriptContext->GetProfileSession(), "Changing mode to profile for function that didn't send compile event");
  4260. #endif
  4261. // This is always done when bg thread is paused hence we don't need any kind of thread-synchronization at this point.
  4262. // Change entry points to Profile Thunk
  4263. // If the entrypoint is CodeGenOnDemand or CodeGen - then we don't change the entry points
  4264. ProxyEntryPointInfo* defaultEntryPointInfo = this->GetDefaultEntryPointInfo();
  4265. if (!IsIntermediateCodeGenThunk(defaultEntryPointInfo->jsMethod)
  4266. && defaultEntryPointInfo->jsMethod != DynamicProfileInfo::EnsureDynamicProfileInfoThunk)
  4267. {
  4268. if (this->GetOriginalEntryPoint_Unchecked() == DefaultDeferredParsingThunk)
  4269. {
  4270. defaultEntryPointInfo->jsMethod = ProfileDeferredParsingThunk;
  4271. }
  4272. else if (this->GetOriginalEntryPoint_Unchecked() == DefaultDeferredDeserializeThunk)
  4273. {
  4274. defaultEntryPointInfo->jsMethod = ProfileDeferredDeserializeThunk;
  4275. }
  4276. else
  4277. {
  4278. defaultEntryPointInfo->jsMethod = ProfileEntryThunk;
  4279. }
  4280. }
  4281. // Update old entry points on the deferred prototype type so that they match current defaultEntryPointInfo.
  4282. // to make sure that new JavascriptFunction instances use profile thunk.
  4283. if (this->deferredPrototypeType)
  4284. {
  4285. this->deferredPrototypeType->SetEntryPoint(this->GetDefaultEntryPointInfo()->jsMethod);
  4286. this->deferredPrototypeType->SetEntryPointInfo(this->GetDefaultEntryPointInfo());
  4287. }
  4288. if (this->undeferredFunctionType)
  4289. {
  4290. this->undeferredFunctionType->SetEntryPoint(this->GetDefaultEntryPointInfo()->jsMethod);
  4291. this->undeferredFunctionType->SetEntryPointInfo(this->GetDefaultEntryPointInfo());
  4292. }
  4293. #if DBG
  4294. if (!this->HasValidEntryPoint())
  4295. {
  4296. OUTPUT_TRACE_DEBUGONLY(Js::ScriptProfilerPhase, _u("FunctionBody::SetEntryToProfileMode, Assert due to HasValidEntryPoint(), directEntrypoint : 0x%0IX, originalentrypoint : 0x%0IX\n"),
  4297. this->GetDefaultEntryPointInfo()->jsMethod, this->GetOriginalEntryPoint());
  4298. AssertMsg(false, "Not a valid EntryPoint");
  4299. }
  4300. #endif
  4301. #endif //ENABLE_NATIVE_CODEGEN
  4302. }
  4303. #endif // ENABLE_SCRIPT_PROFILING
  4304. #if DBG
  4305. void FunctionBody::MustBeInDebugMode()
  4306. {
  4307. Assert(GetUtf8SourceInfo()->IsInDebugMode());
  4308. Assert(m_sourceInfo.pSpanSequence == nullptr);
  4309. Assert(this->GetStatementMaps() != nullptr);
  4310. }
  4311. #endif
  4312. void ParseableFunctionInfo::CleanupToReparse()
  4313. {
  4314. #if DBG
  4315. if (this->IsFunctionBody())
  4316. {
  4317. GetFunctionBody()->UnlockCounters();
  4318. }
  4319. #endif
  4320. // The current function is already compiled. In order to prep this function to ready for debug mode, most of the previous information need to be thrown away.
  4321. // Clean up the nested functions
  4322. this->ForEachNestedFunc([&](FunctionProxy* proxy, uint32 index)
  4323. {
  4324. // Note: redeferred functions may have fully compiled children. If we find a redeferred function, keep walking.
  4325. if (proxy && ((proxy->CanBeDeferred() && proxy->GetFunctionInfo()->GetCompileCount() > 0) || proxy->IsFunctionBody()))
  4326. {
  4327. proxy->GetParseableFunctionInfo()->CleanupToReparse();
  4328. }
  4329. return true;
  4330. });
  4331. this->CleanupToReparseHelper();
  4332. if (this->IsFunctionBody())
  4333. {
  4334. this->GetFunctionBody()->CleanupToReparseHelper();
  4335. }
  4336. }
  4337. void FunctionBody::CleanupToReparseHelper()
  4338. {
  4339. this->CleanupRecyclerData(/* isShutdown */ false, true /* capture entry point cleanup stack trace */);
  4340. this->entryPoints->ClearAndZero();
  4341. // Store the originalEntryPoint to restore it back immediately.
  4342. this->CreateNewDefaultEntryPoint();
  4343. this->SetOriginalEntryPoint(this->GetScriptContext()->CurrentThunk);
  4344. if (this->m_defaultEntryPointInfo)
  4345. {
  4346. this->GetDefaultFunctionEntryPointInfo()->entryPointIndex = 0;
  4347. }
  4348. this->SetAuxiliaryData(nullptr);
  4349. this->SetAuxiliaryContextData(nullptr);
  4350. AssertMsg(!this->byteCodeBlock || !this->IsWasmFunction(), "We should never reset the bytecode block for Wasm");
  4351. this->byteCodeBlock = nullptr;
  4352. this->SetLoopHeaderArray(nullptr);
  4353. this->SetConstTable(nullptr);
  4354. this->SetCodeGenRuntimeData(nullptr);
  4355. this->cacheIdToPropertyIdMap = nullptr;
  4356. this->SetFormalsPropIdArray(nullptr);
  4357. this->SetReferencedPropertyIdMap(nullptr);
  4358. this->SetLiteralRegexs(nullptr);
  4359. this->SetSlotIdInCachedScopeToNestedIndexArray(nullptr);
  4360. this->SetStatementMaps(nullptr);
  4361. this->SetCodeGenGetSetRuntimeData(nullptr);
  4362. this->SetPropertyIdOnRegSlotsContainer(nullptr);
  4363. this->profiledLdLenCount = 0;
  4364. this->profiledLdElemCount = 0;
  4365. this->profiledStElemCount = 0;
  4366. this->profiledCallSiteCount = 0;
  4367. this->profiledArrayCallSiteCount = 0;
  4368. this->profiledDivOrRemCount = 0;
  4369. this->profiledSwitchCount = 0;
  4370. this->profiledReturnTypeCount = 0;
  4371. this->profiledSlotCount = 0;
  4372. this->SetLoopCount(0);
  4373. this->m_envDepth = (uint16)-1;
  4374. this->SetByteCodeCount(0);
  4375. this->SetByteCodeWithoutLDACount(0);
  4376. this->SetByteCodeInLoopCount(0);
  4377. #if ENABLE_PROFILE_INFO
  4378. if (this->dynamicProfileInfo != nullptr)
  4379. {
  4380. SourceContextInfo * sourceContextInfo = GetSourceContextInfo();
  4381. if(sourceContextInfo && sourceContextInfo->sourceDynamicProfileManager)
  4382. {
  4383. sourceContextInfo->sourceDynamicProfileManager->RemoveDynamicProfileInfo(GetFunctionInfo()->GetLocalFunctionId());
  4384. }
  4385. #ifdef DYNAMIC_PROFILE_STORAGE
  4386. DynamicProfileInfoList * profileInfoList = GetScriptContext()->GetProfileInfoList();
  4387. if (profileInfoList)
  4388. {
  4389. FOREACH_SLISTBASE_ENTRY_EDITING(Field(DynamicProfileInfo*), info, profileInfoList, iter)
  4390. {
  4391. if (info->HasFunctionBody() && info->GetFunctionBody() == this)
  4392. {
  4393. iter.UnlinkCurrent();
  4394. break;
  4395. }
  4396. }
  4397. NEXT_SLISTBASE_ENTRY_EDITING;
  4398. }
  4399. #endif
  4400. this->dynamicProfileInfo = nullptr;
  4401. }
  4402. #endif
  4403. this->hasExecutionDynamicProfileInfo = false;
  4404. this->SetFirstTmpRegister(Constants::NoRegister);
  4405. this->SetVarCount(0);
  4406. this->SetConstantCount(0);
  4407. this->SetLocalClosureRegister(Constants::NoRegister);
  4408. this->SetParamClosureRegister(Constants::NoRegister);
  4409. this->SetLocalFrameDisplayRegister(Constants::NoRegister);
  4410. this->SetEnvRegister(Constants::NoRegister);
  4411. this->SetThisRegisterForEventHandler(Constants::NoRegister);
  4412. this->SetFirstInnerScopeRegister(Constants::NoRegister);
  4413. this->SetFuncExprScopeRegister(Constants::NoRegister);
  4414. this->SetInnerScopeCount(0);
  4415. this->hasCachedScopePropIds = false;
  4416. this->ResetObjectLiteralTypes();
  4417. this->SetInlineCacheCount(0);
  4418. this->SetRootObjectLoadInlineCacheStart(0);
  4419. this->SetRootObjectLoadMethodInlineCacheStart(0);
  4420. this->SetRootObjectStoreInlineCacheStart(0);
  4421. this->SetIsInstInlineCacheCount(0);
  4422. this->m_inlineCachesOnFunctionObject = false;
  4423. this->SetReferencedPropertyIdCount(0);
  4424. #if ENABLE_PROFILE_INFO
  4425. this->SetPolymorphicCallSiteInfoHead(nullptr);
  4426. #endif
  4427. this->executionState.SetInterpretedCount(0);
  4428. this->m_hasDoneAllNonLocalReferenced = false;
  4429. this->SetDebuggerScopeIndex(0);
  4430. this->m_isAsmJsScheduledForFullJIT = false;
  4431. this->m_asmJsTotalLoopCount = 0;
  4432. recentlyBailedOutOfJittedLoopBody = false;
  4433. SetLoopInterpreterLimit(CONFIG_FLAG(LoopInterpretCount));
  4434. ReinitializeExecutionModeAndLimits();
  4435. Assert(this->m_sourceInfo.m_probeCount == 0);
  4436. this->m_sourceInfo.m_probeBackingBlock = nullptr;
  4437. #if DBG
  4438. // This could be non-zero if the function threw exception before. Reset it.
  4439. this->m_DEBUG_executionCount = 0;
  4440. #endif
  4441. if (this->m_sourceInfo.pSpanSequence != nullptr)
  4442. {
  4443. HeapDelete(this->m_sourceInfo.pSpanSequence);
  4444. this->m_sourceInfo.pSpanSequence = nullptr;
  4445. }
  4446. if (this->m_sourceInfo.m_auxStatementData != nullptr)
  4447. {
  4448. // This must be consistent with how we allocate the data for this and inner structures.
  4449. // We are using recycler, thus it's enough just to set to NULL.
  4450. Assert(m_scriptContext->GetRecycler()->IsValidObject(m_sourceInfo.m_auxStatementData));
  4451. m_sourceInfo.m_auxStatementData = nullptr;
  4452. }
  4453. }
  4454. void ParseableFunctionInfo::CleanupToReparseHelper()
  4455. {
  4456. #if DYNAMIC_INTERPRETER_THUNK
  4457. if (m_isAsmJsFunction && m_dynamicInterpreterThunk)
  4458. {
  4459. m_scriptContext->ReleaseDynamicAsmJsInterpreterThunk((BYTE*)this->m_dynamicInterpreterThunk, true);
  4460. this->m_dynamicInterpreterThunk = nullptr;
  4461. }
  4462. #endif
  4463. this->SetScopeInfo(nullptr);
  4464. this->SetPropertyIdsForScopeSlotArray(nullptr, 0);
  4465. this->GetUtf8SourceInfo()->DeleteLineOffsetCache();
  4466. // Reset to default.
  4467. this->flags = this->IsClassConstructor() ? Flags_None : Flags_HasNoExplicitReturnValue;
  4468. ResetInParams();
  4469. this->m_isAsmjsMode = false;
  4470. this->m_isAsmJsFunction = false;
  4471. }
  4472. #ifdef ENABLE_SCRIPT_DEBUGGING
  4473. void FunctionBody::SetEntryToDeferParseForDebugger()
  4474. {
  4475. ProxyEntryPointInfo* defaultEntryPointInfo = this->GetDefaultEntryPointInfo();
  4476. if (defaultEntryPointInfo->jsMethod != DefaultDeferredParsingThunk
  4477. #if defined(ENABLE_SCRIPT_PROFILING) || defined(ENABLE_SCRIPT_DEBUGGING)
  4478. && defaultEntryPointInfo->jsMethod != ProfileDeferredParsingThunk
  4479. #endif
  4480. )
  4481. {
  4482. #if defined(ENABLE_SCRIPT_PROFILING) || defined(ENABLE_SCRIPT_DEBUGGING)
  4483. // Just change the thunk, the cleanup will be done once the function gets called.
  4484. if (this->m_scriptContext->CurrentThunk == ProfileEntryThunk)
  4485. {
  4486. defaultEntryPointInfo->jsMethod = ProfileDeferredParsingThunk;
  4487. }
  4488. else
  4489. #endif
  4490. {
  4491. defaultEntryPointInfo->jsMethod = DefaultDeferredParsingThunk;
  4492. }
  4493. this->SetOriginalEntryPoint(DefaultDeferredParsingThunk);
  4494. // Abandon the shared type so a new function will get a new one
  4495. this->deferredPrototypeType = nullptr;
  4496. this->undeferredFunctionType = nullptr;
  4497. this->SetAttributes((FunctionInfo::Attributes) (this->GetAttributes() | FunctionInfo::Attributes::DeferredParse));
  4498. }
  4499. // Set other state back to before parse as well
  4500. this->SetStackNestedFunc(false);
  4501. this->SetAuxPtr<AuxPointerType::StackNestedFuncParent>(nullptr);
  4502. this->SetReparsed(true);
  4503. #if DBG
  4504. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  4505. OUTPUT_VERBOSE_TRACE(Js::DebuggerPhase, _u("Regenerate Due To Debug Mode: function %s (%s) from script context %p\n"),
  4506. this->GetDisplayName(), this->GetDebugNumberSet(debugStringBuffer), m_scriptContext);
  4507. this->UnlockCounters(); // asuming background jit is stopped and allow the counter setters access again
  4508. #endif
  4509. }
  4510. #endif
  4511. void FunctionBody::ClearEntryPoints()
  4512. {
  4513. if (this->entryPoints)
  4514. {
  4515. this->MapEntryPoints([] (int index, FunctionEntryPointInfo* entryPoint)
  4516. {
  4517. if (nullptr != entryPoint)
  4518. {
  4519. // Finalize = Free up work item if it hasn't been released yet + entry point clean up
  4520. // isShutdown is false because cleanup is called only in the !isShutdown case
  4521. entryPoint->Finalize(/*isShutdown*/ false);
  4522. }
  4523. });
  4524. this->MapLoopHeaders([] (uint loopNumber, LoopHeader* header)
  4525. {
  4526. header->MapEntryPoints([] (int index, LoopEntryPointInfo* entryPoint)
  4527. {
  4528. entryPoint->Cleanup(/*isShutdown*/ false, true /* capture cleanup stack */);
  4529. });
  4530. });
  4531. }
  4532. this->entryPoints->ClearAndZero();
  4533. }
  4534. //
  4535. // For library code all references to jitted entry points need to be removed
  4536. //
  4537. void FunctionBody::ResetEntryPoint()
  4538. {
  4539. ClearEntryPoints();
  4540. this->CreateNewDefaultEntryPoint();
  4541. this->SetOriginalEntryPoint(DefaultEntryThunk);
  4542. m_defaultEntryPointInfo->jsMethod = m_scriptContext->CurrentThunk;
  4543. if (this->deferredPrototypeType)
  4544. {
  4545. // Update old entry points on the deferred prototype type,
  4546. // as they may point to old native code gen regions which age gone now.
  4547. this->deferredPrototypeType->SetEntryPoint(this->GetDefaultEntryPointInfo()->jsMethod);
  4548. this->deferredPrototypeType->SetEntryPointInfo(this->GetDefaultEntryPointInfo());
  4549. }
  4550. if (this->undeferredFunctionType)
  4551. {
  4552. this->undeferredFunctionType->SetEntryPoint(this->GetDefaultEntryPointInfo()->jsMethod);
  4553. this->undeferredFunctionType->SetEntryPointInfo(this->GetDefaultEntryPointInfo());
  4554. }
  4555. ReinitializeExecutionModeAndLimits();
  4556. }
  4557. void FunctionBody::AddDeferParseAttribute()
  4558. {
  4559. this->SetAttributes((FunctionInfo::Attributes) (this->GetAttributes() | FunctionInfo::Attributes::DeferredParse));
  4560. }
  4561. void FunctionBody::RemoveDeferParseAttribute()
  4562. {
  4563. this->SetAttributes((FunctionInfo::Attributes) (this->GetAttributes() & (~FunctionInfo::Attributes::DeferredParse)));
  4564. }
  4565. Js::DebuggerScope * FunctionBody::GetDiagCatchScopeObjectAt(int byteCodeOffset)
  4566. {
  4567. if (GetScopeObjectChain())
  4568. {
  4569. for (int i = 0; i < GetScopeObjectChain()->pScopeChain->Count(); i++)
  4570. {
  4571. Js::DebuggerScope *debuggerScope = GetScopeObjectChain()->pScopeChain->Item(i);
  4572. Assert(debuggerScope);
  4573. if (debuggerScope->IsCatchScope() && debuggerScope->IsOffsetInScope(byteCodeOffset))
  4574. {
  4575. return debuggerScope;
  4576. }
  4577. }
  4578. }
  4579. return nullptr;
  4580. }
  4581. ushort SmallSpanSequence::GetDiff(int current, int prev)
  4582. {
  4583. int diff = current - prev;
  4584. if ((diff) < SHRT_MIN || (diff) >= SHRT_MAX)
  4585. {
  4586. diff = SHRT_MAX;
  4587. if (!this->pActualOffsetList)
  4588. {
  4589. this->pActualOffsetList = JsUtil::GrowingUint32HeapArray::Create(4);
  4590. }
  4591. this->pActualOffsetList->Add(current);
  4592. }
  4593. return (ushort)diff;
  4594. }
  4595. // Get Values of the beginning of the statement at particular index.
  4596. BOOL SmallSpanSequence::GetRangeAt(int index, SmallSpanSequenceIter &iter, int * pCountOfMissed, StatementData & data)
  4597. {
  4598. Assert((uint32)index < pStatementBuffer->Count());
  4599. SmallSpan span(pStatementBuffer->ItemInBuffer((uint32)index));
  4600. int countOfMissed = 0;
  4601. if ((short)span.sourceBegin == SHRT_MAX)
  4602. {
  4603. // Look in ActualOffset store
  4604. Assert(this->pActualOffsetList);
  4605. Assert(this->pActualOffsetList->Count() > 0);
  4606. Assert(this->pActualOffsetList->Count() > (uint32)iter.indexOfActualOffset);
  4607. data.sourceBegin = this->pActualOffsetList->ItemInBuffer((uint32)iter.indexOfActualOffset);
  4608. countOfMissed++;
  4609. }
  4610. else
  4611. {
  4612. data.sourceBegin = iter.accumulatedSourceBegin + (short)span.sourceBegin;
  4613. }
  4614. if (span.bytecodeBegin == SHRT_MAX)
  4615. {
  4616. // Look in ActualOffset store
  4617. Assert(this->pActualOffsetList);
  4618. Assert(this->pActualOffsetList->Count() > 0);
  4619. Assert(this->pActualOffsetList->Count() > (uint32)(iter.indexOfActualOffset + countOfMissed));
  4620. data.bytecodeBegin = this->pActualOffsetList->ItemInBuffer((uint32)iter.indexOfActualOffset + countOfMissed);
  4621. countOfMissed++;
  4622. }
  4623. else
  4624. {
  4625. data.bytecodeBegin = iter.accumulatedBytecodeBegin + span.bytecodeBegin;
  4626. }
  4627. if (pCountOfMissed)
  4628. {
  4629. *pCountOfMissed = countOfMissed;
  4630. }
  4631. return TRUE;
  4632. }
  4633. void SmallSpanSequence::Reset(SmallSpanSequenceIter &iter)
  4634. {
  4635. iter.accumulatedIndex = 0;
  4636. iter.accumulatedSourceBegin = baseValue;
  4637. iter.accumulatedBytecodeBegin = 0;
  4638. iter.indexOfActualOffset = 0;
  4639. }
  4640. BOOL SmallSpanSequence::GetMatchingStatementFromBytecode(int bytecode, SmallSpanSequenceIter &iter, StatementData & data)
  4641. {
  4642. if (Count() > 0 && bytecode >= 0)
  4643. {
  4644. // Support only in forward direction
  4645. if (bytecode < iter.accumulatedBytecodeBegin
  4646. || iter.accumulatedIndex <= 0 || (uint32)iter.accumulatedIndex >= Count())
  4647. {
  4648. // re-initialize the accumulators
  4649. Reset(iter);
  4650. }
  4651. while ((uint32)iter.accumulatedIndex < Count())
  4652. {
  4653. int countOfMissed = 0;
  4654. if (!GetRangeAt(iter.accumulatedIndex, iter, &countOfMissed, data))
  4655. {
  4656. Assert(FALSE);
  4657. break;
  4658. }
  4659. if (data.bytecodeBegin >= bytecode)
  4660. {
  4661. if (data.bytecodeBegin > bytecode)
  4662. {
  4663. // Not exactly at the current bytecode, so it falls in between previous statement.
  4664. data.sourceBegin = iter.accumulatedSourceBegin;
  4665. data.bytecodeBegin = iter.accumulatedBytecodeBegin;
  4666. }
  4667. return TRUE;
  4668. }
  4669. // Look for the next
  4670. iter.accumulatedSourceBegin = data.sourceBegin;
  4671. iter.accumulatedBytecodeBegin = data.bytecodeBegin;
  4672. iter.accumulatedIndex++;
  4673. if (countOfMissed)
  4674. {
  4675. iter.indexOfActualOffset += countOfMissed;
  4676. }
  4677. }
  4678. if (iter.accumulatedIndex != -1)
  4679. {
  4680. // Give the last one.
  4681. Assert(data.bytecodeBegin < bytecode);
  4682. return TRUE;
  4683. }
  4684. }
  4685. // Failed to give the correct one, init to default
  4686. iter.accumulatedIndex = -1;
  4687. return FALSE;
  4688. }
  4689. BOOL SmallSpanSequence::Item(int index, SmallSpanSequenceIter &iter, StatementData & data)
  4690. {
  4691. if (!pStatementBuffer || (uint32)index >= pStatementBuffer->Count())
  4692. {
  4693. return FALSE;
  4694. }
  4695. if (iter.accumulatedIndex <= 0 || iter.accumulatedIndex > index)
  4696. {
  4697. Reset(iter);
  4698. }
  4699. while (iter.accumulatedIndex <= index)
  4700. {
  4701. Assert((uint32)iter.accumulatedIndex < pStatementBuffer->Count());
  4702. int countOfMissed = 0;
  4703. if (!GetRangeAt(iter.accumulatedIndex, iter, &countOfMissed, data))
  4704. {
  4705. Assert(FALSE);
  4706. break;
  4707. }
  4708. // We store the next index
  4709. iter.accumulatedSourceBegin = data.sourceBegin;
  4710. iter.accumulatedBytecodeBegin = data.bytecodeBegin;
  4711. iter.accumulatedIndex++;
  4712. if (countOfMissed)
  4713. {
  4714. iter.indexOfActualOffset += countOfMissed;
  4715. }
  4716. if ((iter.accumulatedIndex - 1) == index)
  4717. {
  4718. return TRUE;
  4719. }
  4720. }
  4721. return FALSE;
  4722. }
  4723. BOOL SmallSpanSequence::Seek(int index, StatementData & data)
  4724. {
  4725. // This method will not alter any state of the variables, so this will just do plain search
  4726. // from the beginning to look for that index.
  4727. SmallSpanSequenceIter iter;
  4728. Reset(iter);
  4729. return Item(index, iter, data);
  4730. }
  4731. PropertyIdOnRegSlotsContainer * PropertyIdOnRegSlotsContainer::New(Recycler * recycler)
  4732. {
  4733. return RecyclerNew(recycler, PropertyIdOnRegSlotsContainer);
  4734. }
  4735. PropertyIdOnRegSlotsContainer::PropertyIdOnRegSlotsContainer()
  4736. : propertyIdsForRegSlots(nullptr), length(0), propertyIdsForFormalArgs(nullptr), formalsUpperBound(Js::Constants::NoRegister)
  4737. {
  4738. }
  4739. void PropertyIdOnRegSlotsContainer::CreateRegSlotsArray(Recycler * recycler, uint _length)
  4740. {
  4741. Assert(propertyIdsForRegSlots == nullptr);
  4742. propertyIdsForRegSlots = RecyclerNewArrayLeafZ(recycler, PropertyId, _length);
  4743. length = _length;
  4744. }
  4745. void PropertyIdOnRegSlotsContainer::SetFormalArgs(PropertyIdArray * formalArgs)
  4746. {
  4747. propertyIdsForFormalArgs = formalArgs;
  4748. }
  4749. //
  4750. // Helper methods for PropertyIdOnRegSlotsContainer
  4751. void PropertyIdOnRegSlotsContainer::Insert(RegSlot reg, PropertyId propId)
  4752. {
  4753. //
  4754. // Reg is being used as an index;
  4755. Assert(propertyIdsForRegSlots);
  4756. Assert(reg < length);
  4757. //
  4758. // the current reg is unaccounted for const reg count. while fetching calculate the actual regslot value.
  4759. Assert(propertyIdsForRegSlots[reg] == 0 || propertyIdsForRegSlots[reg] == propId);
  4760. propertyIdsForRegSlots[reg] = propId;
  4761. }
  4762. void PropertyIdOnRegSlotsContainer::FetchItemAt(uint index, FunctionBody *pFuncBody, __out PropertyId *pPropId, __out RegSlot *pRegSlot)
  4763. {
  4764. Assert(index < length);
  4765. Assert(pPropId);
  4766. Assert(pRegSlot);
  4767. Assert(pFuncBody);
  4768. *pPropId = propertyIdsForRegSlots[index];
  4769. *pRegSlot = pFuncBody->MapRegSlot(index);
  4770. }
  4771. bool PropertyIdOnRegSlotsContainer::IsRegSlotFormal(RegSlot reg)
  4772. {
  4773. if (propertyIdsForFormalArgs != nullptr && reg < length)
  4774. {
  4775. PropertyId propId = propertyIdsForRegSlots[reg];
  4776. for (uint32 i = 0; i < propertyIdsForFormalArgs->count; i++)
  4777. {
  4778. if (propertyIdsForFormalArgs->elements[i] == propId)
  4779. {
  4780. return true;
  4781. }
  4782. }
  4783. }
  4784. return false;
  4785. }
  4786. ScopeType FrameDisplay::GetScopeType(void* scope)
  4787. {
  4788. if(Js::ActivationObject::Is(scope))
  4789. {
  4790. return ScopeType_ActivationObject;
  4791. }
  4792. if(Js::ScopeSlots::Is(scope))
  4793. {
  4794. return ScopeType_SlotArray;
  4795. }
  4796. return ScopeType_WithScope;
  4797. }
  4798. // ScopeSlots
  4799. bool ScopeSlots::IsDebuggerScopeSlotArray()
  4800. {
  4801. return DebuggerScope::Is(slotArray[ScopeMetadataSlotIndex]);
  4802. }
  4803. // DebuggerScope
  4804. bool DebuggerScope::Is(void* ptr)
  4805. {
  4806. if (!ptr)
  4807. {
  4808. return false;
  4809. }
  4810. return VirtualTableInfo<DebuggerScope>::HasVirtualTable(ptr);
  4811. }
  4812. // Get the sibling for the current debugger scope.
  4813. DebuggerScope * DebuggerScope::GetSiblingScope(RegSlot location, FunctionBody *functionBody)
  4814. {
  4815. bool isBlockSlotOrObject = scopeType == Js::DiagExtraScopesType::DiagBlockScopeInSlot || scopeType == Js::DiagExtraScopesType::DiagBlockScopeInObject;
  4816. bool isCatchSlotOrObject = scopeType == Js::DiagExtraScopesType::DiagCatchScopeInSlot || scopeType == Js::DiagExtraScopesType::DiagCatchScopeInObject;
  4817. // This is expected to be called only when the current scope is either slot or activation object.
  4818. Assert(isBlockSlotOrObject || isCatchSlotOrObject);
  4819. if (siblingScope == nullptr)
  4820. {
  4821. // If the sibling isn't there, attempt to retrieve it if we're reparsing or create it anew if this is the first parse.
  4822. siblingScope = functionBody->RecordStartScopeObject(isBlockSlotOrObject ? Js::DiagExtraScopesType::DiagBlockScopeDirect : Js::DiagExtraScopesType::DiagCatchScopeDirect, GetStart(), location);
  4823. }
  4824. return siblingScope;
  4825. }
  4826. // Adds a new property to be tracked in the debugger scope.
  4827. // location - The slot array index or register slot location of where the property is stored.
  4828. // propertyId - The property ID of the property.
  4829. // flags - Flags that help describe the property.
  4830. void DebuggerScope::AddProperty(RegSlot location, Js::PropertyId propertyId, DebuggerScopePropertyFlags flags)
  4831. {
  4832. DebuggerScopeProperty scopeProperty;
  4833. scopeProperty.location = location;
  4834. scopeProperty.propId = propertyId;
  4835. // This offset is uninitialized until the property is initialized (with a ld opcode, for example).
  4836. scopeProperty.byteCodeInitializationOffset = Constants::InvalidByteCodeOffset;
  4837. scopeProperty.flags = flags;
  4838. // Delay allocate the property list so we don't take up memory if there are no properties in this scope.
  4839. // Scopes are created during non-debug mode as well so we want to keep them as small as possible.
  4840. this->EnsurePropertyListIsAllocated();
  4841. // The property doesn't exist yet, so add it.
  4842. this->scopeProperties->Add(scopeProperty);
  4843. }
  4844. bool DebuggerScope::HasProperty(Js::PropertyId propertyId)
  4845. {
  4846. int i = -1;
  4847. return GetPropertyIndex(propertyId, i);
  4848. }
  4849. bool DebuggerScope::GetPropertyIndex(Js::PropertyId propertyId, int& index)
  4850. {
  4851. if (!this->HasProperties())
  4852. {
  4853. index = -1;
  4854. return false;
  4855. }
  4856. bool found = this->scopeProperties->MapUntil( [&](int i, const DebuggerScopeProperty& scopeProperty) {
  4857. if(scopeProperty.propId == propertyId)
  4858. {
  4859. index = scopeProperty.location;
  4860. return true;
  4861. }
  4862. return false;
  4863. });
  4864. if(!found)
  4865. {
  4866. return false;
  4867. }
  4868. return true;
  4869. }
  4870. #if DBG
  4871. void DebuggerScope::Dump()
  4872. {
  4873. int indent = (GetScopeDepth() - 1) * 4;
  4874. Output::Print(indent, _u("Begin scope: Address: %p Type: %s Location: %d Sibling: %p Range: [%d, %d]\n "), this, GetDebuggerScopeTypeString(scopeType), scopeLocation, PointerValue(this->siblingScope), range.begin, range.end);
  4875. if (this->HasProperties())
  4876. {
  4877. this->scopeProperties->Map( [=] (int i, Js::DebuggerScopeProperty& scopeProperty) {
  4878. Output::Print(indent, _u("%s(%d) Location: %d Const: %s Initialized: %d\n"), ThreadContext::GetContextForCurrentThread()->GetPropertyName(scopeProperty.propId)->GetBuffer(),
  4879. scopeProperty.propId, scopeProperty.location, scopeProperty.IsConst() ? _u("true"): _u("false"), scopeProperty.byteCodeInitializationOffset);
  4880. });
  4881. }
  4882. Output::Print(_u("\n"));
  4883. }
  4884. // Returns the debugger scope type in string format.
  4885. PCWSTR DebuggerScope::GetDebuggerScopeTypeString(DiagExtraScopesType scopeType)
  4886. {
  4887. switch (scopeType)
  4888. {
  4889. case DiagExtraScopesType::DiagBlockScopeDirect:
  4890. return _u("DiagBlockScopeDirect");
  4891. case DiagExtraScopesType::DiagBlockScopeInObject:
  4892. return _u("DiagBlockScopeInObject");
  4893. case DiagExtraScopesType::DiagBlockScopeInSlot:
  4894. return _u("DiagBlockScopeInSlot");
  4895. case DiagExtraScopesType::DiagBlockScopeRangeEnd:
  4896. return _u("DiagBlockScopeRangeEnd");
  4897. case DiagExtraScopesType::DiagCatchScopeDirect:
  4898. return _u("DiagCatchScopeDirect");
  4899. case DiagExtraScopesType::DiagCatchScopeInObject:
  4900. return _u("DiagCatchScopeInObject");
  4901. case DiagExtraScopesType::DiagCatchScopeInSlot:
  4902. return _u("DiagCatchScopeInSlot");
  4903. case DiagExtraScopesType::DiagUnknownScope:
  4904. return _u("DiagUnknownScope");
  4905. case DiagExtraScopesType::DiagWithScope:
  4906. return _u("DiagWithScope");
  4907. case DiagExtraScopesType::DiagParamScope:
  4908. return _u("DiagParamScope");
  4909. case DiagExtraScopesType::DiagParamScopeInObject:
  4910. return _u("DiagParamScopeInObject");
  4911. default:
  4912. AssertMsg(false, "Missing a debug scope type.");
  4913. return _u("");
  4914. }
  4915. }
  4916. #endif
  4917. #if ENABLE_TTD
  4918. Js::PropertyId DebuggerScope::GetPropertyIdForSlotIndex_TTD(uint32 slotIndex) const
  4919. {
  4920. const Js::DebuggerScopeProperty& scopeProperty = this->scopeProperties->Item(slotIndex);
  4921. return scopeProperty.propId;
  4922. }
  4923. #endif
  4924. // Updates the current offset of where the property is first initialized. This is used to
  4925. // detect whether or not a property is in a dead zone when broken in the debugger.
  4926. // location - The slot array index or register slot location of where the property is stored.
  4927. // propertyId - The property ID of the property.
  4928. // byteCodeOffset - The offset to set the initialization point at.
  4929. // isFunctionDeclaration - Whether or not the property is a function declaration or not. Used for verification.
  4930. // <returns> - True if the property was found and updated for the current scope, else false.
  4931. bool DebuggerScope::UpdatePropertyInitializationOffset(
  4932. RegSlot location,
  4933. Js::PropertyId propertyId,
  4934. int byteCodeOffset,
  4935. bool isFunctionDeclaration /*= false*/)
  4936. {
  4937. if (UpdatePropertyInitializationOffsetInternal(location, propertyId, byteCodeOffset, isFunctionDeclaration))
  4938. {
  4939. return true;
  4940. }
  4941. if (siblingScope != nullptr && siblingScope->UpdatePropertyInitializationOffsetInternal(location, propertyId, byteCodeOffset, isFunctionDeclaration))
  4942. {
  4943. return true;
  4944. }
  4945. return false;
  4946. }
  4947. bool DebuggerScope::UpdatePropertyInitializationOffsetInternal(
  4948. RegSlot location,
  4949. Js::PropertyId propertyId,
  4950. int byteCodeOffset,
  4951. bool isFunctionDeclaration /*= false*/)
  4952. {
  4953. if (scopeProperties == nullptr)
  4954. {
  4955. return false;
  4956. }
  4957. for (int i = 0; i < scopeProperties->Count(); ++i)
  4958. {
  4959. DebuggerScopeProperty propertyItem = scopeProperties->Item(i);
  4960. if (propertyItem.propId == propertyId && propertyItem.location == location)
  4961. {
  4962. if (propertyItem.byteCodeInitializationOffset == Constants::InvalidByteCodeOffset)
  4963. {
  4964. propertyItem.byteCodeInitializationOffset = byteCodeOffset;
  4965. scopeProperties->SetExistingItem(i, propertyItem);
  4966. }
  4967. #if DBG
  4968. else
  4969. {
  4970. // If the bytecode initialization offset is not Constants::InvalidByteCodeOffset,
  4971. // it means we have two or more functions declared in the same scope with the same name
  4972. // and one has already been marked. We track each location with a property entry
  4973. // on the debugging side (when calling DebuggerScope::AddProperty()) as opposed to scanning
  4974. // and checking if the property already exists each time we add in order to avoid duplicates.
  4975. AssertMsg(isFunctionDeclaration, "Only function declarations can be defined more than once in the same scope with the same name.");
  4976. AssertMsg(propertyItem.byteCodeInitializationOffset == byteCodeOffset, "The bytecode offset for all function declarations should be identical for this scope.");
  4977. }
  4978. #endif // DBG
  4979. return true;
  4980. }
  4981. }
  4982. return false;
  4983. }
  4984. // Updates the debugger scopes fields due to a regeneration of bytecode (happens during debugger attach or detach, for
  4985. // example).
  4986. void DebuggerScope::UpdateDueToByteCodeRegeneration(DiagExtraScopesType scopeType, int start, RegSlot scopeLocation)
  4987. {
  4988. #if DBG
  4989. if (this->scopeType != Js::DiagUnknownScope)
  4990. {
  4991. // If the scope is unknown, it was deserialized without a scope type. Otherwise, it should not have changed.
  4992. // The scope type can change on a re-parse in certain scenarios related to eval detection in legacy mode -> Winblue: 272122
  4993. AssertMsg(this->scopeType == scopeType, "The debugger scope type should not have changed when generating bytecode again.");
  4994. }
  4995. #endif // DBG
  4996. this->scopeType = scopeType;
  4997. this->SetBegin(start);
  4998. if(this->scopeProperties)
  4999. {
  5000. this->scopeProperties->Clear();
  5001. }
  5002. // Reset the scope location as it may have changed during bytecode generation from the last run.
  5003. this->SetScopeLocation(scopeLocation);
  5004. if (siblingScope)
  5005. {
  5006. // If we had a sibling scope during initial parsing, clear it now so that it will be reset
  5007. // when it is retrieved during this bytecode generation pass, in GetSiblingScope().
  5008. // GetSiblingScope() will ensure that the FunctionBody currentDebuggerScopeIndex value is
  5009. // updated accordingly to account for future scopes coming after the sibling.
  5010. // Calling of GetSiblingScope() will happen when register properties are added to this scope
  5011. // via TrackRegisterPropertyForDebugger().
  5012. siblingScope = nullptr;
  5013. }
  5014. }
  5015. void DebuggerScope::UpdatePropertiesInForInOrOfCollectionScope()
  5016. {
  5017. if (this->scopeProperties != nullptr)
  5018. {
  5019. this->scopeProperties->All([&](Js::DebuggerScopeProperty& propertyItem)
  5020. {
  5021. propertyItem.flags |= DebuggerScopePropertyFlags_ForInOrOfCollection;
  5022. return true;
  5023. });
  5024. }
  5025. }
  5026. void DebuggerScope::EnsurePropertyListIsAllocated()
  5027. {
  5028. if (this->scopeProperties == nullptr)
  5029. {
  5030. this->scopeProperties = RecyclerNew(this->recycler, DebuggerScopePropertyList, this->recycler);
  5031. }
  5032. }
  5033. // Checks if the passed in ByteCodeGenerator offset is in this scope's being/end range.
  5034. bool DebuggerScope::IsOffsetInScope(int offset) const
  5035. {
  5036. Assert(this->range.end != -1);
  5037. return this->range.Includes(offset);
  5038. }
  5039. // Determines if the DebuggerScope contains a property with the passed in ID and
  5040. // location in the internal property list.
  5041. // propertyId - The ID of the property to search for.
  5042. // location - The slot array index or register to search for.
  5043. // outScopeProperty - Optional parameter that will return the property, if found.
  5044. bool DebuggerScope::Contains(Js::PropertyId propertyId, RegSlot location) const
  5045. {
  5046. DebuggerScopeProperty tempProperty;
  5047. return TryGetProperty(propertyId, location, &tempProperty);
  5048. }
  5049. // Gets whether or not the scope is a block scope (non-catch or with).
  5050. bool DebuggerScope::IsBlockScope() const
  5051. {
  5052. AssertMsg(this->scopeType != Js::DiagBlockScopeRangeEnd, "Debugger scope type should never be set to range end - only reserved for marking the end of a scope (not persisted).");
  5053. return this->scopeType == Js::DiagBlockScopeDirect
  5054. || this->scopeType == Js::DiagBlockScopeInObject
  5055. || this->scopeType == Js::DiagBlockScopeInSlot
  5056. || this->scopeType == Js::DiagBlockScopeRangeEnd;
  5057. }
  5058. // Gets whether or not the scope is a catch block scope.
  5059. bool DebuggerScope::IsCatchScope() const
  5060. {
  5061. return this->scopeType == Js::DiagCatchScopeDirect
  5062. || this->scopeType == Js::DiagCatchScopeInObject
  5063. || this->scopeType == Js::DiagCatchScopeInSlot;
  5064. }
  5065. // Gets whether or not the scope is a with block scope.
  5066. bool DebuggerScope::IsWithScope() const
  5067. {
  5068. return this->scopeType == Js::DiagWithScope;
  5069. }
  5070. // Gets whether or not the scope is a slot array scope.
  5071. bool DebuggerScope::IsSlotScope() const
  5072. {
  5073. return this->scopeType == Js::DiagBlockScopeInSlot
  5074. || this->scopeType == Js::DiagCatchScopeInSlot;
  5075. }
  5076. bool DebuggerScope::IsParamScope() const
  5077. {
  5078. return this->scopeType == Js::DiagParamScope
  5079. || this->scopeType == Js::DiagParamScopeInObject;
  5080. }
  5081. // Gets whether or not the scope has any properties in it.
  5082. bool DebuggerScope::HasProperties() const
  5083. {
  5084. return this->scopeProperties && this->scopeProperties->Count() > 0;
  5085. }
  5086. // Checks if this scope is an ancestor of the passed in scope.
  5087. bool DebuggerScope::IsAncestorOf(const DebuggerScope* potentialChildScope)
  5088. {
  5089. if (potentialChildScope == nullptr)
  5090. {
  5091. // If the child scope is null, it represents the global scope which
  5092. // cannot be a child of anything.
  5093. return false;
  5094. }
  5095. const DebuggerScope* currentScope = potentialChildScope;
  5096. while (currentScope)
  5097. {
  5098. if (currentScope->GetParentScope() == this)
  5099. {
  5100. return true;
  5101. }
  5102. currentScope = currentScope->GetParentScope();
  5103. }
  5104. return false;
  5105. }
  5106. // Checks if all properties of the scope are currently in a dead zone given the specified offset.
  5107. bool DebuggerScope::AreAllPropertiesInDeadZone(int byteCodeOffset) const
  5108. {
  5109. if (!this->HasProperties())
  5110. {
  5111. return false;
  5112. }
  5113. return this->scopeProperties->All([&](Js::DebuggerScopeProperty& propertyItem)
  5114. {
  5115. return propertyItem.IsInDeadZone(byteCodeOffset);
  5116. });
  5117. }
  5118. // Attempts to get the specified property. Returns true if the property was copied to the structure; false otherwise.
  5119. bool DebuggerScope::TryGetProperty(Js::PropertyId propertyId, RegSlot location, DebuggerScopeProperty* outScopeProperty) const
  5120. {
  5121. Assert(outScopeProperty);
  5122. if (scopeProperties == nullptr)
  5123. {
  5124. return false;
  5125. }
  5126. for (int i = 0; i < scopeProperties->Count(); ++i)
  5127. {
  5128. DebuggerScopeProperty propertyItem = scopeProperties->Item(i);
  5129. if (propertyItem.propId == propertyId && propertyItem.location == location)
  5130. {
  5131. *outScopeProperty = propertyItem;
  5132. return true;
  5133. }
  5134. }
  5135. return false;
  5136. }
  5137. bool DebuggerScope::TryGetValidProperty(Js::PropertyId propertyId, RegSlot location, int offset, DebuggerScopeProperty* outScopeProperty, bool* isInDeadZone) const
  5138. {
  5139. if (TryGetProperty(propertyId, location, outScopeProperty))
  5140. {
  5141. if (IsOffsetInScope(offset))
  5142. {
  5143. if (isInDeadZone != nullptr)
  5144. {
  5145. *isInDeadZone = outScopeProperty->IsInDeadZone(offset);
  5146. }
  5147. return true;
  5148. }
  5149. }
  5150. return false;
  5151. }
  5152. void DebuggerScope::SetBegin(int begin)
  5153. {
  5154. range.begin = begin;
  5155. if (siblingScope != nullptr)
  5156. {
  5157. siblingScope->SetBegin(begin);
  5158. }
  5159. }
  5160. void DebuggerScope::SetEnd(int end)
  5161. {
  5162. range.end = end;
  5163. if (siblingScope != nullptr)
  5164. {
  5165. siblingScope->SetEnd(end);
  5166. }
  5167. }
  5168. // Finds the common ancestor scope between this scope and the passed in scope.
  5169. // Returns nullptr if the scopes are part of different trees.
  5170. DebuggerScope* DebuggerScope::FindCommonAncestor(DebuggerScope* debuggerScope)
  5171. {
  5172. AnalysisAssert(debuggerScope);
  5173. if (this == debuggerScope)
  5174. {
  5175. return debuggerScope;
  5176. }
  5177. if (this->IsAncestorOf(debuggerScope))
  5178. {
  5179. return this;
  5180. }
  5181. if (debuggerScope->IsAncestorOf(this))
  5182. {
  5183. return debuggerScope;
  5184. }
  5185. DebuggerScope* firstNode = this;
  5186. DebuggerScope* secondNode = debuggerScope;
  5187. int firstDepth = firstNode->GetScopeDepth();
  5188. int secondDepth = secondNode->GetScopeDepth();
  5189. // Calculate the depth difference in order to bring the deep node up to the sibling
  5190. // level of the shorter node.
  5191. int depthDifference = abs(firstDepth - secondDepth);
  5192. DebuggerScope*& nodeToBringUp = firstDepth > secondDepth ? firstNode : secondNode;
  5193. while (depthDifference > 0)
  5194. {
  5195. AnalysisAssert(nodeToBringUp);
  5196. nodeToBringUp = nodeToBringUp->GetParentScope();
  5197. --depthDifference;
  5198. }
  5199. // Move up the tree and see where the nodes meet.
  5200. while (firstNode && secondNode)
  5201. {
  5202. if (firstNode == secondNode)
  5203. {
  5204. return firstNode;
  5205. }
  5206. firstNode = firstNode->GetParentScope();
  5207. secondNode = secondNode->GetParentScope();
  5208. }
  5209. // The nodes are not part of the same scope tree.
  5210. return nullptr;
  5211. }
  5212. // Gets the depth of the scope in the parent link tree.
  5213. int DebuggerScope::GetScopeDepth() const
  5214. {
  5215. int depth = 0;
  5216. const DebuggerScope* currentDebuggerScope = this;
  5217. while (currentDebuggerScope)
  5218. {
  5219. currentDebuggerScope = currentDebuggerScope->GetParentScope();
  5220. ++depth;
  5221. }
  5222. return depth;
  5223. }
  5224. bool ScopeObjectChain::TryGetDebuggerScopePropertyInfo(PropertyId propertyId, RegSlot location, int offset, bool* isPropertyInDebuggerScope, bool *isConst, bool* isInDeadZone)
  5225. {
  5226. Assert(pScopeChain);
  5227. Assert(isPropertyInDebuggerScope);
  5228. Assert(isConst);
  5229. *isPropertyInDebuggerScope = false;
  5230. *isConst = false;
  5231. // Search through each block scope until we find the current scope. If the register was found
  5232. // in any of the scopes going down until we reach the scope of the debug break, then it's in scope.
  5233. // if found but not in the scope, the out param will be updated (since it is actually a let or const), so that caller can make a call accordingly.
  5234. for (int i = 0; i < pScopeChain->Count(); i++)
  5235. {
  5236. Js::DebuggerScope *debuggerScope = pScopeChain->Item(i);
  5237. DebuggerScopeProperty debuggerScopeProperty;
  5238. if (!debuggerScope->IsParamScope() && debuggerScope->TryGetProperty(propertyId, location, &debuggerScopeProperty))
  5239. {
  5240. bool isOffsetInScope = debuggerScope->IsOffsetInScope(offset);
  5241. // For the Object scope, all the properties will have the same location (-1) so they can match. Use further check below to determine the propertyInDebuggerScope
  5242. *isPropertyInDebuggerScope = isOffsetInScope || !debuggerScope->IsBlockObjectScope();
  5243. if (isOffsetInScope)
  5244. {
  5245. if (isInDeadZone != nullptr)
  5246. {
  5247. *isInDeadZone = debuggerScopeProperty.IsInDeadZone(offset);
  5248. }
  5249. *isConst = debuggerScopeProperty.IsConst();
  5250. return true;
  5251. }
  5252. }
  5253. }
  5254. return false;
  5255. }
  5256. void FunctionBody::AllocateForInCache()
  5257. {
  5258. uint profiledForInLoopCount = this->GetProfiledForInLoopCount();
  5259. if (profiledForInLoopCount == 0)
  5260. {
  5261. return;
  5262. }
  5263. this->SetAuxPtr<AuxPointerType::ForInCacheArray>(AllocatorNewArrayZ(CacheAllocator, this->GetScriptContext()->GetEnumeratorAllocator(), EnumeratorCache, profiledForInLoopCount));
  5264. }
  5265. EnumeratorCache * FunctionBody::GetForInCache(uint index)
  5266. {
  5267. Assert(index < this->GetProfiledForInLoopCount());
  5268. return &this->GetAuxPtr<AuxPointerType::ForInCacheArray>()[index];
  5269. }
  5270. EnumeratorCache * FunctionBody::GetForInCacheArray()
  5271. {
  5272. return this->GetAuxPtrWithLock<AuxPointerType::ForInCacheArray>();
  5273. }
  5274. void FunctionBody::CleanUpForInCache(bool isShutdown)
  5275. {
  5276. uint profiledForInLoopCount = this->GetProfiledForInLoopCount();
  5277. if (profiledForInLoopCount == 0)
  5278. {
  5279. return;
  5280. }
  5281. EnumeratorCache * forInCacheArray = this->GetAuxPtr<AuxPointerType::ForInCacheArray>();
  5282. if (forInCacheArray)
  5283. {
  5284. if (isShutdown)
  5285. {
  5286. memset(forInCacheArray, 0, sizeof(EnumeratorCache) * profiledForInLoopCount);
  5287. }
  5288. else
  5289. {
  5290. AllocatorDeleteArray(CacheAllocator, this->GetScriptContext()->GetEnumeratorAllocator(), profiledForInLoopCount, forInCacheArray);
  5291. this->SetAuxPtr<AuxPointerType::ForInCacheArray>(nullptr);
  5292. }
  5293. }
  5294. }
  5295. void FunctionBody::AllocateInlineCache()
  5296. {
  5297. Assert(this->inlineCaches == nullptr);
  5298. uint isInstInlineCacheStart = this->GetInlineCacheCount();
  5299. uint totalCacheCount = isInstInlineCacheStart + GetIsInstInlineCacheCount();
  5300. if (totalCacheCount != 0)
  5301. {
  5302. // Root object inline cache are not leaf
  5303. void ** inlineCaches = RecyclerNewArrayZ(this->m_scriptContext->GetRecycler(),
  5304. void*, totalCacheCount);
  5305. #if DBG
  5306. this->m_inlineCacheTypes = RecyclerNewArrayLeafZ(this->m_scriptContext->GetRecycler(),
  5307. byte, totalCacheCount);
  5308. #endif
  5309. uint i = 0;
  5310. uint plainInlineCacheEnd = GetRootObjectLoadInlineCacheStart();
  5311. __analysis_assume(plainInlineCacheEnd <= totalCacheCount);
  5312. for (; i < plainInlineCacheEnd; i++)
  5313. {
  5314. inlineCaches[i] = AllocatorNewZ(InlineCacheAllocator,
  5315. this->m_scriptContext->GetInlineCacheAllocator(), InlineCache);
  5316. }
  5317. Js::RootObjectBase * rootObject = this->GetRootObject();
  5318. ThreadContext * threadContext = this->GetScriptContext()->GetThreadContext();
  5319. uint rootObjectLoadInlineCacheEnd = GetRootObjectLoadMethodInlineCacheStart();
  5320. __analysis_assume(rootObjectLoadInlineCacheEnd <= totalCacheCount);
  5321. for (; i < rootObjectLoadInlineCacheEnd; i++)
  5322. {
  5323. inlineCaches[i] = rootObject->GetInlineCache(
  5324. threadContext->GetPropertyName(this->GetPropertyIdFromCacheId(i)), false, false);
  5325. }
  5326. uint rootObjectLoadMethodInlineCacheEnd = GetRootObjectStoreInlineCacheStart();
  5327. __analysis_assume(rootObjectLoadMethodInlineCacheEnd <= totalCacheCount);
  5328. for (; i < rootObjectLoadMethodInlineCacheEnd; i++)
  5329. {
  5330. inlineCaches[i] = rootObject->GetInlineCache(
  5331. threadContext->GetPropertyName(this->GetPropertyIdFromCacheId(i)), true, false);
  5332. }
  5333. uint rootObjectStoreInlineCacheEnd = isInstInlineCacheStart;
  5334. __analysis_assume(rootObjectStoreInlineCacheEnd <= totalCacheCount);
  5335. for (; i < rootObjectStoreInlineCacheEnd; i++)
  5336. {
  5337. #pragma prefast(suppress:6386, "The analysis assume didn't help prefast figure out this is in range")
  5338. inlineCaches[i] = rootObject->GetInlineCache(
  5339. threadContext->GetPropertyName(this->GetPropertyIdFromCacheId(i)), false, true);
  5340. }
  5341. for (; i < totalCacheCount; i++)
  5342. {
  5343. inlineCaches[i] = AllocatorNewStructZ(CacheAllocator,
  5344. this->m_scriptContext->GetIsInstInlineCacheAllocator(), IsInstInlineCache);
  5345. }
  5346. #if DBG
  5347. this->m_inlineCacheTypes = RecyclerNewArrayLeafZ(this->m_scriptContext->GetRecycler(),
  5348. byte, totalCacheCount);
  5349. #endif
  5350. this->inlineCaches = inlineCaches;
  5351. }
  5352. }
  5353. InlineCache *FunctionBody::GetInlineCache(uint index)
  5354. {
  5355. Assert(this->inlineCaches != nullptr);
  5356. Assert(index < this->GetInlineCacheCount());
  5357. #if DBG
  5358. Assert(this->m_inlineCacheTypes[index] == InlineCacheTypeNone ||
  5359. this->m_inlineCacheTypes[index] == InlineCacheTypeInlineCache);
  5360. this->m_inlineCacheTypes[index] = InlineCacheTypeInlineCache;
  5361. #endif
  5362. return reinterpret_cast<InlineCache *>(this->inlineCaches[index]);
  5363. }
  5364. bool FunctionBody::CanFunctionObjectHaveInlineCaches()
  5365. {
  5366. if (this->DoStackNestedFunc() || this->IsCoroutine())
  5367. {
  5368. return false;
  5369. }
  5370. uint totalCacheCount = this->GetInlineCacheCount() + this->GetIsInstInlineCacheCount();
  5371. if (PHASE_FORCE(Js::ScriptFunctionWithInlineCachePhase, this) && totalCacheCount > 0)
  5372. {
  5373. return true;
  5374. }
  5375. // Only have inline caches on function object for possible inlining candidates.
  5376. // Since we don't know the size of the top function, check against the maximum possible inline threshold
  5377. // Negative inline byte code size threshold will disable inline cache on function object.
  5378. const int byteCodeSizeThreshold = CONFIG_FLAG(InlineThreshold) + CONFIG_FLAG(InlineThresholdAdjustCountInSmallFunction);
  5379. if (byteCodeSizeThreshold < 0 || this->GetByteCodeWithoutLDACount() > (uint)byteCodeSizeThreshold)
  5380. {
  5381. return false;
  5382. }
  5383. // Negative FuncObjectInlineCacheThreshold will disable inline cache on function object.
  5384. if (CONFIG_FLAG(FuncObjectInlineCacheThreshold) < 0 || totalCacheCount > (uint)CONFIG_FLAG(FuncObjectInlineCacheThreshold) || totalCacheCount == 0)
  5385. {
  5386. return false;
  5387. }
  5388. return true;
  5389. }
  5390. void** FunctionBody::GetInlineCaches()
  5391. {
  5392. return this->inlineCaches;
  5393. }
  5394. #if DBG
  5395. byte* FunctionBody::GetInlineCacheTypes()
  5396. {
  5397. return this->m_inlineCacheTypes;
  5398. }
  5399. #endif
  5400. IsInstInlineCache *FunctionBody::GetIsInstInlineCache(uint index)
  5401. {
  5402. Assert(this->inlineCaches != nullptr);
  5403. Assert(index < GetIsInstInlineCacheCount());
  5404. index += this->GetInlineCacheCount();
  5405. #if DBG
  5406. Assert(this->m_inlineCacheTypes[index] == InlineCacheTypeNone ||
  5407. this->m_inlineCacheTypes[index] == InlineCacheTypeIsInst);
  5408. this->m_inlineCacheTypes[index] = InlineCacheTypeIsInst;
  5409. #endif
  5410. return reinterpret_cast<IsInstInlineCache *>(this->inlineCaches[index]);
  5411. }
  5412. PolymorphicInlineCache * FunctionBody::GetPolymorphicInlineCache(uint index)
  5413. {
  5414. return this->polymorphicInlineCaches.GetInlineCache(this, index);
  5415. }
  5416. PolymorphicInlineCache * FunctionBody::CreateNewPolymorphicInlineCache(uint index, PropertyId propertyId, InlineCache * inlineCache)
  5417. {
  5418. Assert(GetPolymorphicInlineCache(index) == nullptr);
  5419. // Only create polymorphic inline caches for non-root inline cache indexes
  5420. if (index < GetRootObjectLoadInlineCacheStart()
  5421. #if DBG
  5422. && !PHASE_OFF1(Js::PolymorphicInlineCachePhase)
  5423. #endif
  5424. )
  5425. {
  5426. PolymorphicInlineCache * polymorphicInlineCache = CreatePolymorphicInlineCache(index, MinPolymorphicInlineCacheSize);
  5427. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  5428. if (PHASE_VERBOSE_TRACE1(Js::PolymorphicInlineCachePhase))
  5429. {
  5430. this->DumpFullFunctionName();
  5431. Output::Print(_u(": New PIC, index = %d, size = %d\n"), index, MinPolymorphicInlineCacheSize);
  5432. }
  5433. #endif
  5434. #if PHASE_PRINT_INTRUSIVE_TESTTRACE1
  5435. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  5436. #endif
  5437. PHASE_PRINT_INTRUSIVE_TESTTRACE1(
  5438. Js::PolymorphicInlineCachePhase,
  5439. _u("TestTrace PIC: New, Function %s (%s), 0x%x, index = %d, size = %d\n"), this->GetDisplayName(), this->GetDebugNumberSet(debugStringBuffer), polymorphicInlineCache, index, MinPolymorphicInlineCacheSize);
  5440. uint indexInPolymorphicCache = polymorphicInlineCache->GetInlineCacheIndexForType(inlineCache->GetType());
  5441. inlineCache->CopyTo(propertyId, m_scriptContext, &(polymorphicInlineCache->GetInlineCaches()[indexInPolymorphicCache]));
  5442. polymorphicInlineCache->UpdateInlineCachesFillInfo(indexInPolymorphicCache, true /*set*/);
  5443. return polymorphicInlineCache;
  5444. }
  5445. return nullptr;
  5446. }
  5447. PolymorphicInlineCache * FunctionBody::CreateBiggerPolymorphicInlineCache(uint index, PropertyId propertyId)
  5448. {
  5449. PolymorphicInlineCache * polymorphicInlineCache = GetPolymorphicInlineCache(index);
  5450. Assert(polymorphicInlineCache && polymorphicInlineCache->CanAllocateBigger());
  5451. uint16 polymorphicInlineCacheSize = polymorphicInlineCache->GetSize();
  5452. uint16 newPolymorphicInlineCacheSize = PolymorphicInlineCache::GetNextSize(polymorphicInlineCacheSize);
  5453. Assert(newPolymorphicInlineCacheSize > polymorphicInlineCacheSize);
  5454. PolymorphicInlineCache * newPolymorphicInlineCache = CreatePolymorphicInlineCache(index, newPolymorphicInlineCacheSize);
  5455. polymorphicInlineCache->CopyTo(propertyId, m_scriptContext, newPolymorphicInlineCache);
  5456. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  5457. if (PHASE_VERBOSE_TRACE1(Js::PolymorphicInlineCachePhase))
  5458. {
  5459. this->DumpFullFunctionName();
  5460. Output::Print(_u(": Bigger PIC, index = %d, oldSize = %d, newSize = %d\n"), index, polymorphicInlineCacheSize, newPolymorphicInlineCacheSize);
  5461. }
  5462. #endif
  5463. #if PHASE_PRINT_INTRUSIVE_TESTTRACE1
  5464. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  5465. #endif
  5466. PHASE_PRINT_INTRUSIVE_TESTTRACE1(
  5467. Js::PolymorphicInlineCachePhase,
  5468. _u("TestTrace PIC: Bigger, Function %s (%s), 0x%x, index = %d, size = %d\n"), this->GetDisplayName(), this->GetDebugNumberSet(debugStringBuffer), newPolymorphicInlineCache, index, newPolymorphicInlineCacheSize);
  5469. return newPolymorphicInlineCache;
  5470. }
  5471. void FunctionBody::ResetInlineCaches()
  5472. {
  5473. SetInlineCacheCount(0);
  5474. SetRootObjectLoadInlineCacheStart(0);
  5475. SetRootObjectStoreInlineCacheStart(0);
  5476. SetIsInstInlineCacheCount(0);
  5477. this->inlineCaches = nullptr;
  5478. this->polymorphicInlineCaches.Reset();
  5479. }
  5480. PolymorphicInlineCache * FunctionBody::CreatePolymorphicInlineCache(uint index, uint16 size)
  5481. {
  5482. Recycler * recycler = this->m_scriptContext->GetRecycler();
  5483. PolymorphicInlineCache * newPolymorphicInlineCache = FunctionBodyPolymorphicInlineCache::New(size, this);
  5484. this->polymorphicInlineCaches.SetInlineCache(recycler, this, index, newPolymorphicInlineCache);
  5485. return newPolymorphicInlineCache;
  5486. }
  5487. uint FunctionBody::NewObjectLiteral()
  5488. {
  5489. Assert(this->GetObjectLiteralTypes() == nullptr);
  5490. return IncObjLiteralCount();
  5491. }
  5492. Field(DynamicType*)* FunctionBody::GetObjectLiteralTypeRef(uint index)
  5493. {
  5494. Assert(index < GetObjLiteralCount());
  5495. auto literalTypes = this->GetObjectLiteralTypes();
  5496. Assert(literalTypes != nullptr);
  5497. return literalTypes + index;
  5498. }
  5499. Field(DynamicType*)* FunctionBody::GetObjectLiteralTypeRefWithLock(uint index)
  5500. {
  5501. Assert(index < GetObjLiteralCount());
  5502. auto literalTypes = this->GetObjectLiteralTypesWithLock();
  5503. Assert(literalTypes != nullptr);
  5504. return literalTypes + index;
  5505. }
  5506. void FunctionBody::AllocateObjectLiteralTypeArray()
  5507. {
  5508. Assert(this->GetObjectLiteralTypes() == nullptr);
  5509. uint objLiteralCount = GetObjLiteralCount();
  5510. if (objLiteralCount == 0)
  5511. {
  5512. return;
  5513. }
  5514. this->SetObjectLiteralTypes(RecyclerNewArrayZ(this->GetScriptContext()->GetRecycler(), DynamicType *, objLiteralCount));
  5515. }
  5516. uint FunctionBody::NewLiteralRegex()
  5517. {
  5518. if (this->GetLiteralRegexes() != nullptr)
  5519. {
  5520. // This is a function nested in a redeferred function, so we won't regenerate byte code and won't make use of the index.
  5521. // The regex count is already correct, so don't increment it.
  5522. return 0;
  5523. }
  5524. return IncLiteralRegexCount();
  5525. }
  5526. void FunctionBody::AllocateLiteralRegexArray()
  5527. {
  5528. Assert(!this->GetLiteralRegexes());
  5529. uint32 literalRegexCount = GetLiteralRegexCount();
  5530. if (literalRegexCount == 0)
  5531. {
  5532. return;
  5533. }
  5534. this->SetLiteralRegexs(RecyclerNewArrayZ(m_scriptContext->GetRecycler(), UnifiedRegex::RegexPattern *, literalRegexCount));
  5535. }
  5536. #ifdef ASMJS_PLAT
  5537. AsmJsFunctionInfo* FunctionBody::AllocateAsmJsFunctionInfo()
  5538. {
  5539. Assert( !this->GetAsmJsFunctionInfo() );
  5540. this->SetAuxPtr<AuxPointerType::AsmJsFunctionInfo>(RecyclerNew( m_scriptContext->GetRecycler(), AsmJsFunctionInfo));
  5541. return this->GetAsmJsFunctionInfo();
  5542. }
  5543. AsmJsModuleInfo* FunctionBody::AllocateAsmJsModuleInfo()
  5544. {
  5545. Assert( !this->GetAsmJsModuleInfo() );
  5546. Recycler* rec = m_scriptContext->GetRecycler();
  5547. this->SetAuxPtr<AuxPointerType::AsmJsModuleInfo>(RecyclerNew(rec, AsmJsModuleInfo, rec));
  5548. return this->GetAsmJsModuleInfo();
  5549. }
  5550. #endif
  5551. PropertyIdArray * FunctionBody::AllocatePropertyIdArrayForFormals(uint32 size, uint32 count, byte extraSlots)
  5552. {
  5553. //TODO: saravind: Should the allocation be a Leaf Allocation?
  5554. PropertyIdArray * formalsPropIdArray = RecyclerNewPlus(GetScriptContext()->GetRecycler(), size, Js::PropertyIdArray, count, extraSlots);
  5555. SetFormalsPropIdArray(formalsPropIdArray);
  5556. return formalsPropIdArray;
  5557. }
  5558. UnifiedRegex::RegexPattern *FunctionBody::GetLiteralRegex(const uint index)
  5559. {
  5560. Assert(index < GetLiteralRegexCount());
  5561. Assert(this->GetLiteralRegexes());
  5562. return this->GetLiteralRegexes()[index];
  5563. }
  5564. UnifiedRegex::RegexPattern *FunctionBody::GetLiteralRegexWithLock(const uint index)
  5565. {
  5566. Assert(index < GetLiteralRegexCount());
  5567. Assert(this->GetLiteralRegexesWithLock());
  5568. return this->GetLiteralRegexesWithLock()[index];
  5569. }
  5570. void FunctionBody::SetLiteralRegex(const uint index, UnifiedRegex::RegexPattern *const pattern)
  5571. {
  5572. Assert(index < GetLiteralRegexCount());
  5573. Assert(this->GetLiteralRegexes());
  5574. auto literalRegexes = this->GetLiteralRegexes();
  5575. if (literalRegexes[index] && literalRegexes[index] == pattern)
  5576. {
  5577. return;
  5578. }
  5579. Assert(!literalRegexes[index]);
  5580. literalRegexes[index] = pattern;
  5581. }
  5582. void FunctionBody::ResetObjectLiteralTypes()
  5583. {
  5584. this->SetObjectLiteralTypes(nullptr);
  5585. this->SetObjLiteralCount(0);
  5586. }
  5587. void FunctionBody::ResetLiteralRegexes()
  5588. {
  5589. SetLiteralRegexCount(0);
  5590. this->SetLiteralRegexs(nullptr);
  5591. }
  5592. Js::AuxArray<uint32> * FunctionBody::AllocateSlotIdInCachedScopeToNestedIndexArray(uint32 slotCount)
  5593. {
  5594. Js::AuxArray<uint32> * slotIdToNestedIndexArray = RecyclerNewPlusLeaf(GetScriptContext()->GetRecycler(), slotCount * sizeof(uint32), Js::AuxArray<uint32>, slotCount);
  5595. SetSlotIdInCachedScopeToNestedIndexArray(slotIdToNestedIndexArray);
  5596. return slotIdToNestedIndexArray;
  5597. }
  5598. void FunctionBody::ResetProfileIds()
  5599. {
  5600. #if ENABLE_PROFILE_INFO
  5601. Assert(!HasDynamicProfileInfo()); // profile data relies on the profile ID counts; it should not have been created yet
  5602. Assert(!this->GetCodeGenRuntimeData()); // relies on 'profiledCallSiteCount'
  5603. profiledCallSiteCount = 0;
  5604. profiledArrayCallSiteCount = 0;
  5605. profiledReturnTypeCount = 0;
  5606. profiledSlotCount = 0;
  5607. profiledLdLenCount = 0;
  5608. profiledLdElemCount = 0;
  5609. profiledStElemCount = 0;
  5610. #endif
  5611. }
  5612. void FunctionBody::ResetByteCodeGenState()
  5613. {
  5614. // Byte code generation failed for this function. Revert any intermediate state being tracked in the function body, in
  5615. // case byte code generation is attempted again for this function body.
  5616. DebugOnly(this->UnlockCounters());
  5617. ResetInlineCaches();
  5618. ResetObjectLiteralTypes();
  5619. ResetLiteralRegexes();
  5620. ResetLoops();
  5621. ResetProfileIds();
  5622. ResetSlotIdInCachedScopeToNestedIndexArray();
  5623. SetFirstTmpRegister(Constants::NoRegister);
  5624. SetLocalClosureRegister(Constants::NoRegister);
  5625. SetParamClosureRegister(Constants::NoRegister);
  5626. SetLocalFrameDisplayRegister(Constants::NoRegister);
  5627. SetEnvRegister(Constants::NoRegister);
  5628. SetThisRegisterForEventHandler(Constants::NoRegister);
  5629. SetFirstInnerScopeRegister(Constants::NoRegister);
  5630. SetFuncExprScopeRegister(Constants::NoRegister);
  5631. SetInnerScopeCount(0);
  5632. hasCachedScopePropIds = false;
  5633. this->SetConstantCount(0);
  5634. this->SetConstTable(nullptr);
  5635. AssertMsg(!this->byteCodeBlock || !this->IsWasmFunction(), "We should never reset the bytecode block for Wasm");
  5636. this->byteCodeBlock = nullptr;
  5637. // Also, remove the function body from the source info to prevent any further processing
  5638. // of the function such as attempts to set breakpoints.
  5639. if (GetIsFuncRegistered())
  5640. {
  5641. this->GetUtf8SourceInfo()->RemoveFunctionBody(this);
  5642. }
  5643. // There is other state that is set by the byte code generator but the state should be the same each time byte code
  5644. // generation is done for the function, so it doesn't need to be reverted
  5645. }
  5646. void FunctionBody::ResetByteCodeGenVisitState()
  5647. {
  5648. // This function body is about to be visited by the byte code generator after defer-parsing it. Since the previous visit
  5649. // pass may have failed, we need to restore state that is tracked on the function body by the visit pass.
  5650. // Note: do not reset literal regexes if the function has already been compiled (e.g., is a parsed function enclosed by a
  5651. // redeferred function) as we will not use the count of literals anyway, and the counters may be accessed by the background thread.
  5652. DebugOnly(this->UnlockCounters());
  5653. if (this->byteCodeBlock == nullptr)
  5654. {
  5655. ResetLiteralRegexes();
  5656. }
  5657. }
  5658. #if ENABLE_NATIVE_CODEGEN
  5659. const FunctionCodeGenRuntimeData *FunctionBody::GetInlineeCodeGenRuntimeData(const ProfileId profiledCallSiteId) const
  5660. {
  5661. Assert(profiledCallSiteId < profiledCallSiteCount);
  5662. auto codeGenRuntimeData = this->GetCodeGenRuntimeDataWithLock();
  5663. return codeGenRuntimeData ? codeGenRuntimeData[profiledCallSiteId] : nullptr;
  5664. }
  5665. const FunctionCodeGenRuntimeData *FunctionBody::GetInlineeCodeGenRuntimeDataForTargetInlinee(const ProfileId profiledCallSiteId, Js::FunctionBody *inlineeFuncBody) const
  5666. {
  5667. Assert(profiledCallSiteId < profiledCallSiteCount);
  5668. auto codeGenRuntimeData = this->GetCodeGenRuntimeDataWithLock();
  5669. if (!codeGenRuntimeData)
  5670. {
  5671. return nullptr;
  5672. }
  5673. const FunctionCodeGenRuntimeData *runtimeData = codeGenRuntimeData[profiledCallSiteId];
  5674. while (runtimeData && runtimeData->GetFunctionBody() != inlineeFuncBody)
  5675. {
  5676. runtimeData = runtimeData->GetNext();
  5677. }
  5678. return runtimeData;
  5679. }
  5680. template<Js::FunctionProxy::AuxPointerType auxType>
  5681. FunctionCodeGenRuntimeData * FunctionBody::EnsureCodeGenRuntimeDataCommon(
  5682. Recycler *const recycler,
  5683. __in_range(0, profiledCallSiteCount - 1) const ProfileId profiledCallSiteId,
  5684. FunctionBody *const inlinee)
  5685. {
  5686. Assert(recycler);
  5687. Assert(profiledCallSiteId < profiledCallSiteCount);
  5688. Assert(inlinee);
  5689. if (this->GetAuxPtr(auxType) == nullptr)
  5690. {
  5691. FunctionCodeGenRuntimeData ** codeGenRuntimeData = RecyclerNewArrayZ(recycler, FunctionCodeGenRuntimeData *, profiledCallSiteCount);
  5692. this->SetAuxPtr(auxType, codeGenRuntimeData);
  5693. }
  5694. Field(FunctionCodeGenRuntimeData *)* codeGenRuntimeData = this->GetAuxPtr<auxType>();
  5695. Field(FunctionCodeGenRuntimeData *) const inlineeData = codeGenRuntimeData[profiledCallSiteId];
  5696. if (inlineeData == nullptr)
  5697. {
  5698. FunctionCodeGenRuntimeData * runtimeData = RecyclerNew(recycler, FunctionCodeGenRuntimeData, inlinee);
  5699. codeGenRuntimeData[profiledCallSiteId] = runtimeData;
  5700. return runtimeData;
  5701. }
  5702. // Find the right code gen runtime data
  5703. FunctionCodeGenRuntimeData * next = inlineeData;
  5704. while (next && (next->GetFunctionBody() != inlinee))
  5705. {
  5706. next = next->GetNext();
  5707. }
  5708. if (next)
  5709. {
  5710. return next;
  5711. }
  5712. FunctionCodeGenRuntimeData * runtimeData = RecyclerNew(recycler, FunctionCodeGenRuntimeData, inlinee);
  5713. runtimeData->SetupRuntimeDataChain(inlineeData);
  5714. codeGenRuntimeData[profiledCallSiteId] = runtimeData;
  5715. return runtimeData;
  5716. }
  5717. FunctionCodeGenRuntimeData *FunctionBody::EnsureInlineeCodeGenRuntimeData(
  5718. Recycler *const recycler,
  5719. __in_range(0, profiledCallSiteCount - 1) const ProfileId profiledCallSiteId,
  5720. FunctionBody *const inlinee)
  5721. {
  5722. return EnsureCodeGenRuntimeDataCommon<AuxPointerType::CodeGenRuntimeData>(recycler, profiledCallSiteId, inlinee);
  5723. }
  5724. FunctionCodeGenRuntimeData * FunctionBody::EnsureCallbackInlineeCodeGenRuntimeData(
  5725. Recycler *const recycler,
  5726. __in_range(0, profiledCallSiteCount - 1) const ProfileId profiledCallSiteId,
  5727. FunctionBody *const inlinee)
  5728. {
  5729. return EnsureCodeGenRuntimeDataCommon<AuxPointerType::CodeGenCallbackRuntimeData>(recycler, profiledCallSiteId, inlinee);
  5730. }
  5731. const FunctionCodeGenRuntimeData *FunctionBody::GetLdFldInlineeCodeGenRuntimeData(const InlineCacheIndex inlineCacheIndex) const
  5732. {
  5733. Assert(inlineCacheIndex < this->GetInlineCacheCount());
  5734. auto data = this->GetCodeGenGetSetRuntimeDataWithLock();
  5735. return (data != nullptr) ? data[inlineCacheIndex] : nullptr;
  5736. }
  5737. FunctionCodeGenRuntimeData *FunctionBody::EnsureLdFldInlineeCodeGenRuntimeData(
  5738. Recycler *const recycler,
  5739. const InlineCacheIndex inlineCacheIndex,
  5740. FunctionBody *const inlinee)
  5741. {
  5742. Assert(recycler);
  5743. Assert(inlineCacheIndex < this->GetInlineCacheCount());
  5744. Assert(inlinee);
  5745. if (this->GetCodeGenGetSetRuntimeData() == nullptr)
  5746. {
  5747. const auto codeGenRuntimeData = RecyclerNewArrayZ(recycler, FunctionCodeGenRuntimeData *, this->GetInlineCacheCount());
  5748. this->SetCodeGenGetSetRuntimeData(codeGenRuntimeData);
  5749. }
  5750. auto codeGenGetSetRuntimeData = this->GetCodeGenGetSetRuntimeData();
  5751. const auto inlineeData = codeGenGetSetRuntimeData[inlineCacheIndex];
  5752. if (inlineeData)
  5753. {
  5754. return inlineeData;
  5755. }
  5756. return codeGenGetSetRuntimeData[inlineCacheIndex] = RecyclerNew(recycler, FunctionCodeGenRuntimeData, inlinee);
  5757. }
  5758. const FunctionCodeGenRuntimeData * FunctionBody::GetCallbackInlineeCodeGenRuntimeData(const ProfileId profiledCallSiteId) const
  5759. {
  5760. Assert(profiledCallSiteId < profiledCallSiteCount);
  5761. Field(FunctionCodeGenRuntimeData*)* codeGenRuntimeData = this->GetCodeGenCallbackRuntimeDataWithLock();
  5762. return codeGenRuntimeData ? codeGenRuntimeData[profiledCallSiteId] : nullptr;
  5763. }
  5764. #endif
  5765. void FunctionBody::AllocateLoopHeaders()
  5766. {
  5767. Assert(this->GetLoopHeaderArray() == nullptr);
  5768. uint loopCount = GetLoopCount();
  5769. if (loopCount != 0)
  5770. {
  5771. this->SetLoopHeaderArray(RecyclerNewArrayZ(this->m_scriptContext->GetRecycler(), LoopHeader, loopCount));
  5772. auto loopHeaderArray = this->GetLoopHeaderArray();
  5773. for (uint i = 0; i < loopCount; i++)
  5774. {
  5775. loopHeaderArray[i].Init(this);
  5776. }
  5777. }
  5778. }
  5779. void FunctionBody::ReleaseLoopHeaders()
  5780. {
  5781. #if ENABLE_NATIVE_CODEGEN
  5782. this->MapLoopHeaders([](uint loopNumber, LoopHeader * loopHeader)
  5783. {
  5784. loopHeader->ReleaseEntryPoints();
  5785. });
  5786. #endif
  5787. }
  5788. void FunctionBody::ResetLoops()
  5789. {
  5790. SetLoopCount(0);
  5791. this->SetLoopHeaderArray(nullptr);
  5792. }
  5793. void FunctionBody::RestoreOldDefaultEntryPoint(FunctionEntryPointInfo* oldEntryPointInfo,
  5794. JavascriptMethod oldOriginalEntryPoint,
  5795. FunctionEntryPointInfo* newEntryPointInfo)
  5796. {
  5797. Assert(newEntryPointInfo);
  5798. this->SetDefaultFunctionEntryPointInfo(oldEntryPointInfo, oldOriginalEntryPoint);
  5799. this->entryPoints->RemoveAt(newEntryPointInfo->entryPointIndex);
  5800. }
  5801. FunctionEntryPointInfo* FunctionBody::CreateNewDefaultEntryPoint()
  5802. {
  5803. Recycler *const recycler = this->m_scriptContext->GetRecycler();
  5804. const JavascriptMethod currentThunk = m_scriptContext->CurrentThunk;
  5805. FunctionEntryPointInfo *const entryPointInfo =
  5806. RecyclerNewFinalized(
  5807. recycler,
  5808. FunctionEntryPointInfo,
  5809. this,
  5810. currentThunk,
  5811. m_scriptContext->GetThreadContext());
  5812. AddEntryPointToEntryPointList(entryPointInfo);
  5813. {
  5814. // Allocations in this region may trigger expiry and cause unexpected changes to state
  5815. AUTO_NO_EXCEPTION_REGION;
  5816. Js::JavascriptMethod originalEntryPoint, directEntryPoint;
  5817. #if ENABLE_NATIVE_CODEGEN
  5818. FunctionEntryPointInfo *const simpleJitEntryPointInfo = GetSimpleJitEntryPointInfo();
  5819. if(simpleJitEntryPointInfo && GetExecutionMode() == ExecutionMode::FullJit)
  5820. {
  5821. directEntryPoint =
  5822. originalEntryPoint = simpleJitEntryPointInfo->GetNativeEntrypoint();
  5823. }
  5824. else
  5825. #endif
  5826. {
  5827. #if DYNAMIC_INTERPRETER_THUNK
  5828. // If the dynamic interpreter thunk hasn't been created yet, then the entry point can be set to
  5829. // the default entry point. Otherwise, since the new default entry point is being created to
  5830. // move back to the interpreter, the original entry point is going to be the dynamic interpreter thunk
  5831. originalEntryPoint =
  5832. m_dynamicInterpreterThunk
  5833. ? reinterpret_cast<JavascriptMethod>(InterpreterThunkEmitter::ConvertToEntryPoint(m_dynamicInterpreterThunk))
  5834. : DefaultEntryThunk;
  5835. #else
  5836. originalEntryPoint = DefaultEntryThunk;
  5837. #endif
  5838. directEntryPoint = currentThunk == DefaultEntryThunk ? originalEntryPoint : currentThunk;
  5839. }
  5840. entryPointInfo->jsMethod = directEntryPoint;
  5841. SetDefaultFunctionEntryPointInfo(entryPointInfo, originalEntryPoint);
  5842. }
  5843. return entryPointInfo;
  5844. }
  5845. LoopHeader *FunctionBody::GetLoopHeader(uint index) const
  5846. {
  5847. Assert(this->GetLoopHeaderArray() != nullptr);
  5848. Assert(index < GetLoopCount());
  5849. return &this->GetLoopHeaderArray()[index];
  5850. }
  5851. LoopHeader *FunctionBody::GetLoopHeaderWithLock(uint index) const
  5852. {
  5853. Assert(this->GetLoopHeaderArrayWithLock() != nullptr);
  5854. Assert(index < GetLoopCount());
  5855. return &this->GetLoopHeaderArrayWithLock()[index];
  5856. }
  5857. FunctionEntryPointInfo *FunctionBody::GetSimpleJitEntryPointInfo() const
  5858. {
  5859. return this->GetAuxPtr<AuxPointerType::SimpleJitEntryPointInfo>();
  5860. }
  5861. void FunctionBody::SetSimpleJitEntryPointInfo(FunctionEntryPointInfo *const entryPointInfo)
  5862. {
  5863. this->SetAuxPtr<AuxPointerType::SimpleJitEntryPointInfo>(entryPointInfo);
  5864. }
  5865. uint32 FunctionBody::GetInterpretedCount() const
  5866. {
  5867. return executionState.GetInterpretedCount();
  5868. }
  5869. uint32 FunctionBody::IncreaseInterpretedCount()
  5870. {
  5871. return executionState.IncreaseInterpretedCount();
  5872. }
  5873. void FunctionBody::SetAsmJsExecutionMode()
  5874. {
  5875. executionState.SetAsmJsExecutionMode();
  5876. }
  5877. void FunctionBody::SetDefaultInterpreterExecutionMode()
  5878. {
  5879. executionState.SetDefaultInterpreterExecutionMode();
  5880. }
  5881. ExecutionMode FunctionBody::GetExecutionMode() const
  5882. {
  5883. return executionState.GetExecutionMode();
  5884. }
  5885. ExecutionMode FunctionBody::GetInterpreterExecutionMode(const bool isPostBailout)
  5886. {
  5887. return executionState.GetInterpreterExecutionMode(isPostBailout);
  5888. }
  5889. bool FunctionBody::IsInterpreterExecutionMode() const
  5890. {
  5891. return GetExecutionMode() <= ExecutionMode::ProfilingInterpreter;
  5892. }
  5893. bool FunctionBody::TryTransitionToNextExecutionMode()
  5894. {
  5895. return executionState.TryTransitionToNextExecutionMode();
  5896. }
  5897. void FunctionBody::TryTransitionToNextInterpreterExecutionMode()
  5898. {
  5899. executionState.TryTransitionToNextInterpreterExecutionMode();
  5900. }
  5901. void FunctionBody::SetIsSpeculativeJitCandidate()
  5902. {
  5903. executionState.SetIsSpeculativeJitCandidate();
  5904. }
  5905. bool FunctionBody::TryTransitionToJitExecutionMode()
  5906. {
  5907. return executionState.TryTransitionToJitExecutionMode();
  5908. }
  5909. void FunctionBody::TransitionToSimpleJitExecutionMode()
  5910. {
  5911. executionState.TransitionToSimpleJitExecutionMode();
  5912. }
  5913. void FunctionBody::TransitionToFullJitExecutionMode()
  5914. {
  5915. executionState.TransitionToFullJitExecutionMode();
  5916. }
  5917. void FunctionBody::ReinitializeExecutionModeAndLimits()
  5918. {
  5919. // Do not remove wasCalledFromLoop
  5920. wasCalledFromLoop = false;
  5921. executionState.ReinitializeExecutionModeAndLimits(this);
  5922. }
  5923. void FunctionBody::ResetSimpleJitLimitAndCallCount()
  5924. {
  5925. Assert(GetDefaultFunctionEntryPointInfo() == GetSimpleJitEntryPointInfo());
  5926. executionState.ResetSimpleJitLimit();
  5927. ResetSimpleJitCallCount();
  5928. }
  5929. void FunctionBody::SetSimpleJitCallCount(const uint16 simpleJitLimit) const
  5930. {
  5931. Assert(GetExecutionMode() == ExecutionMode::SimpleJit);
  5932. Assert(GetDefaultFunctionEntryPointInfo() == GetSimpleJitEntryPointInfo());
  5933. // Simple JIT counts down and transitions on overflow
  5934. const uint8 limit = static_cast<uint8>(min(0xffui16, simpleJitLimit));
  5935. GetSimpleJitEntryPointInfo()->callsCount = limit == 0 ? 0 : limit - 1;
  5936. }
  5937. void FunctionBody::ResetSimpleJitCallCount()
  5938. {
  5939. uint32 interpretedCount = GetInterpretedCount();
  5940. uint16 simpleJitLimit = static_cast<uint16>(executionState.GetSimpleJitLimit());
  5941. SetSimpleJitCallCount(
  5942. simpleJitLimit > interpretedCount
  5943. ? simpleJitLimit - static_cast<uint16>(interpretedCount)
  5944. : 0ui16);
  5945. }
  5946. uint16 FunctionBody::GetProfiledIterations() const
  5947. {
  5948. return executionState.GetProfiledIterations();
  5949. }
  5950. void FunctionBody::OnFullJitDequeued(const FunctionEntryPointInfo *const entryPointInfo)
  5951. {
  5952. executionState.AssertIsInitialized();
  5953. Assert(GetExecutionMode() == ExecutionMode::FullJit);
  5954. Assert(entryPointInfo);
  5955. if(entryPointInfo != GetDefaultFunctionEntryPointInfo())
  5956. {
  5957. return;
  5958. }
  5959. // Re-queue the full JIT work item after this many iterations
  5960. executionState.SetFullJitRequeueThreshold(static_cast<uint16>(DEFAULT_CONFIG_FullJitRequeueThreshold));
  5961. }
  5962. void FunctionBody::TraceExecutionMode(const char *const eventDescription) const
  5963. {
  5964. executionState.AssertIsInitialized();
  5965. if(PHASE_TRACE(Phase::ExecutionModePhase, this))
  5966. {
  5967. DoTraceExecutionMode(eventDescription);
  5968. }
  5969. }
  5970. void FunctionBody::TraceInterpreterExecutionMode() const
  5971. {
  5972. executionState.AssertIsInitialized();
  5973. if(!PHASE_TRACE(Phase::ExecutionModePhase, this))
  5974. {
  5975. return;
  5976. }
  5977. switch(GetExecutionMode())
  5978. {
  5979. case ExecutionMode::Interpreter:
  5980. case ExecutionMode::AutoProfilingInterpreter:
  5981. case ExecutionMode::ProfilingInterpreter:
  5982. DoTraceExecutionMode(nullptr);
  5983. break;
  5984. }
  5985. }
  5986. void FunctionBody::DoTraceExecutionMode(const char *const eventDescription) const
  5987. {
  5988. Assert(PHASE_TRACE(Phase::ExecutionModePhase, this));
  5989. executionState.AssertIsInitialized();
  5990. char16 functionIdString[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  5991. Output::Print(
  5992. _u("ExecutionMode - ")
  5993. _u("function: %s (%s), ")
  5994. _u("mode: %S, ")
  5995. _u("size: %u, "),
  5996. GetDisplayName(),
  5997. GetDebugNumberSet(functionIdString),
  5998. ExecutionModeName(executionState.GetExecutionMode()),
  5999. GetByteCodeCount());
  6000. executionState.PrintLimits();
  6001. if(eventDescription)
  6002. {
  6003. Output::Print(_u(", event: %S"), eventDescription);
  6004. }
  6005. Output::Print(_u("\n"));
  6006. Output::Flush();
  6007. }
  6008. bool FunctionBody::DoSimpleJit() const
  6009. {
  6010. return
  6011. !PHASE_OFF(Js::SimpleJitPhase, this) &&
  6012. #ifdef ASMJS_PLAT
  6013. !GetIsAsmjsMode() &&
  6014. #endif
  6015. !GetScriptContext()->GetConfig()->IsNoNative() &&
  6016. !GetScriptContext()->IsScriptContextInDebugMode() &&
  6017. DoInterpreterProfile() &&
  6018. #pragma warning(suppress: 6235) // (<non-zero constant> || <expression>) is always a non-zero constant.
  6019. (!CONFIG_FLAG(NewSimpleJit) || DoInterpreterAutoProfile()) &&
  6020. !IsCoroutine(); // Generator JIT requires bailout which SimpleJit cannot do since it skips GlobOpt
  6021. }
  6022. bool FunctionBody::DoSimpleJitWithLock() const
  6023. {
  6024. return
  6025. !PHASE_OFF(Js::SimpleJitPhase, this) &&
  6026. #ifdef ASMJS_PLAT
  6027. !GetIsAsmjsMode() &&
  6028. #endif
  6029. !GetScriptContext()->GetConfig()->IsNoNative() &&
  6030. !this->IsInDebugMode() &&
  6031. DoInterpreterProfileWithLock() &&
  6032. #pragma warning(suppress: 6235) // (<non-zero constant> || <expression>) is always a non-zero constant.
  6033. (!CONFIG_FLAG(NewSimpleJit) || DoInterpreterAutoProfile()) &&
  6034. !IsCoroutine(); // Generator JIT requires bailout which SimpleJit cannot do since it skips GlobOpt
  6035. }
  6036. bool FunctionBody::DoSimpleJitDynamicProfile() const
  6037. {
  6038. Assert(DoSimpleJitWithLock());
  6039. return !PHASE_OFF(Js::SimpleJitDynamicProfilePhase, this) && !CONFIG_FLAG(NewSimpleJit);
  6040. }
  6041. bool FunctionBody::DoInterpreterProfile() const
  6042. {
  6043. #if ENABLE_PROFILE_INFO
  6044. return !PHASE_OFF(InterpreterProfilePhase, this) && DynamicProfileInfo::IsEnabled(this);
  6045. #else
  6046. return false;
  6047. #endif
  6048. }
  6049. bool FunctionBody::DoInterpreterProfileWithLock() const
  6050. {
  6051. #if ENABLE_PROFILE_INFO
  6052. return !PHASE_OFF(InterpreterProfilePhase, this) && DynamicProfileInfo::IsEnabled(this);
  6053. #else
  6054. return false;
  6055. #endif
  6056. }
  6057. bool FunctionBody::DoInterpreterAutoProfile() const
  6058. {
  6059. Assert(DoInterpreterProfile());
  6060. #ifdef ASMJS_PLAT
  6061. if (this->GetIsAsmjsMode()) return false;
  6062. #endif
  6063. return !PHASE_OFF(InterpreterAutoProfilePhase, this) && !this->IsInDebugMode();
  6064. }
  6065. bool FunctionBody::WasCalledFromLoop() const
  6066. {
  6067. return wasCalledFromLoop;
  6068. }
  6069. void FunctionBody::SetWasCalledFromLoop()
  6070. {
  6071. if(wasCalledFromLoop)
  6072. {
  6073. return;
  6074. }
  6075. wasCalledFromLoop = true;
  6076. if(Configuration::Global.flags.EnforceExecutionModeLimits)
  6077. {
  6078. if(PHASE_TRACE(Phase::ExecutionModePhase, this))
  6079. {
  6080. executionState.CommitExecutedIterations();
  6081. TraceExecutionMode("WasCalledFromLoop (before)");
  6082. }
  6083. }
  6084. else
  6085. {
  6086. // This function is likely going to be called frequently since it's called from a loop. Reduce the full JIT
  6087. // threshold to realize the full JIT perf benefit sooner.
  6088. executionState.CommitExecutedIterations();
  6089. TraceExecutionMode("WasCalledFromLoop (before)");
  6090. uint16 fullJitThreshold = executionState.GetFullJitThreshold();
  6091. if(fullJitThreshold > 1)
  6092. {
  6093. executionState.SetFullJitThreshold(fullJitThreshold / 2, !CONFIG_FLAG(NewSimpleJit));
  6094. }
  6095. }
  6096. {
  6097. // Reduce the loop interpreter limit too, for the same reasons as above
  6098. const uint oldLoopInterpreterLimit = GetLoopInterpreterLimit();
  6099. const uint newLoopInterpreterLimit = GetReducedLoopInterpretCount();
  6100. Assert(newLoopInterpreterLimit <= oldLoopInterpreterLimit);
  6101. SetLoopInterpreterLimit(newLoopInterpreterLimit);
  6102. // Adjust loop headers' interpret counts to ensure that loops will still be profiled a number of times before
  6103. // loop bodies are jitted
  6104. const uint oldLoopProfileThreshold = GetLoopProfileThreshold(oldLoopInterpreterLimit);
  6105. const uint newLoopProfileThreshold = GetLoopProfileThreshold(newLoopInterpreterLimit);
  6106. MapLoopHeaders([=](const uint index, LoopHeader *const loopHeader)
  6107. {
  6108. const uint interpretedCount = loopHeader->interpretCount;
  6109. if(interpretedCount <= newLoopProfileThreshold || interpretedCount >= oldLoopInterpreterLimit)
  6110. {
  6111. // The loop hasn't been profiled yet and wouldn't have started profiling even with the new profile
  6112. // threshold, or it has already been profiled the necessary minimum number of times based on the old limit
  6113. return;
  6114. }
  6115. if(interpretedCount <= oldLoopProfileThreshold)
  6116. {
  6117. // The loop hasn't been profiled yet, but would have started profiling with the new profile threshold. Start
  6118. // profiling on the next iteration.
  6119. loopHeader->interpretCount = newLoopProfileThreshold;
  6120. return;
  6121. }
  6122. // The loop has been profiled some already. Preserve the number of profiled iterations.
  6123. loopHeader->interpretCount = newLoopProfileThreshold + (interpretedCount - oldLoopProfileThreshold);
  6124. });
  6125. }
  6126. TraceExecutionMode("WasCalledFromLoop");
  6127. }
  6128. bool FunctionBody::RecentlyBailedOutOfJittedLoopBody() const
  6129. {
  6130. return recentlyBailedOutOfJittedLoopBody;
  6131. }
  6132. void FunctionBody::SetRecentlyBailedOutOfJittedLoopBody(const bool value)
  6133. {
  6134. recentlyBailedOutOfJittedLoopBody = value;
  6135. }
  6136. uint16 FunctionBody::GetMinProfileIterations()
  6137. {
  6138. return
  6139. static_cast<uint>(
  6140. CONFIG_FLAG(NewSimpleJit)
  6141. ? DEFAULT_CONFIG_MinProfileIterations
  6142. : DEFAULT_CONFIG_MinProfileIterations_OldSimpleJit);
  6143. }
  6144. uint16 FunctionBody::GetMinFunctionProfileIterations()
  6145. {
  6146. return GetMinProfileIterations();
  6147. }
  6148. uint FunctionBody::GetMinLoopProfileIterations(const uint loopInterpreterLimit)
  6149. {
  6150. return min(static_cast<uint>(GetMinProfileIterations()), loopInterpreterLimit);
  6151. }
  6152. uint FunctionBody::GetLoopProfileThreshold(const uint loopInterpreterLimit) const
  6153. {
  6154. return
  6155. DoInterpreterProfile()
  6156. ? DoInterpreterAutoProfile()
  6157. ? loopInterpreterLimit - GetMinLoopProfileIterations(loopInterpreterLimit)
  6158. : 0
  6159. : static_cast<uint>(-1);
  6160. }
  6161. uint FunctionBody::GetReducedLoopInterpretCount()
  6162. {
  6163. const uint loopInterpretCount = CONFIG_FLAG(LoopInterpretCount);
  6164. if(CONFIG_ISENABLED(LoopInterpretCountFlag))
  6165. {
  6166. return loopInterpretCount;
  6167. }
  6168. return max(loopInterpretCount / 3, GetMinLoopProfileIterations(loopInterpretCount));
  6169. }
  6170. uint FunctionBody::GetLoopInterpretCount(LoopHeader* loopHeader) const
  6171. {
  6172. if(loopHeader->isNested)
  6173. {
  6174. Assert(GetLoopInterpreterLimit() >= GetReducedLoopInterpretCount());
  6175. return GetReducedLoopInterpretCount();
  6176. }
  6177. return GetLoopInterpreterLimit();
  6178. }
  6179. bool FunctionBody::DoObjectHeaderInlining()
  6180. {
  6181. return !PHASE_OFF1(ObjectHeaderInliningPhase);
  6182. }
  6183. bool FunctionBody::DoObjectHeaderInliningForConstructors()
  6184. {
  6185. return !PHASE_OFF1(ObjectHeaderInliningForConstructorsPhase) && DoObjectHeaderInlining();
  6186. }
  6187. bool FunctionBody::DoObjectHeaderInliningForConstructor(const uint32 inlineSlotCapacity)
  6188. {
  6189. return inlineSlotCapacity == 0 ? DoObjectHeaderInliningForEmptyObjects() : DoObjectHeaderInliningForConstructors();
  6190. }
  6191. bool FunctionBody::DoObjectHeaderInliningForObjectLiterals()
  6192. {
  6193. return !PHASE_OFF1(ObjectHeaderInliningForObjectLiteralsPhase) && DoObjectHeaderInlining();
  6194. }
  6195. bool FunctionBody::DoObjectHeaderInliningForObjectLiteral(const uint32 inlineSlotCapacity)
  6196. {
  6197. return
  6198. inlineSlotCapacity == 0
  6199. ? DoObjectHeaderInliningForEmptyObjects()
  6200. : DoObjectHeaderInliningForObjectLiterals() &&
  6201. inlineSlotCapacity <= static_cast<uint32>(MaxPreInitializedObjectHeaderInlinedTypeInlineSlotCount);
  6202. }
  6203. bool FunctionBody::DoObjectHeaderInliningForObjectLiteral(
  6204. const PropertyIdArray *const propIds)
  6205. {
  6206. Assert(propIds);
  6207. return
  6208. DoObjectHeaderInliningForObjectLiteral(propIds->count) &&
  6209. PathTypeHandlerBase::UsePathTypeHandlerForObjectLiteral(propIds);
  6210. }
  6211. bool FunctionBody::DoObjectHeaderInliningForEmptyObjects()
  6212. {
  6213. #pragma prefast(suppress:6237, "(<zero> && <expression>) is always zero. <expression> is never evaluated and might have side effects.")
  6214. return PHASE_ON1(ObjectHeaderInliningForEmptyObjectsPhase) && DoObjectHeaderInlining();
  6215. }
  6216. void FunctionBody::Finalize(bool isShutdown)
  6217. {
  6218. #if ENABLE_DEBUG_CONFIG_OPTIONS
  6219. if (Js::Configuration::Global.flags.Instrument.IsEnabled(Js::LinearScanPhase, this->GetSourceContextId(), this->GetLocalFunctionId()))
  6220. {
  6221. this->DumpRegStats(this);
  6222. }
  6223. #endif
  6224. this->Cleanup(isShutdown);
  6225. this->CleanupSourceInfo(isShutdown);
  6226. this->CleanupFunctionProxyCounters();
  6227. }
  6228. void FunctionBody::OnMark()
  6229. {
  6230. this->m_hasActiveReference = true;
  6231. }
  6232. void FunctionBody::CleanupSourceInfo(bool isScriptContextClosing)
  6233. {
  6234. Assert(this->cleanedUp);
  6235. if (!sourceInfoCleanedUp)
  6236. {
  6237. if (GetIsFuncRegistered() && !isScriptContextClosing)
  6238. {
  6239. // If our function is registered, then there must
  6240. // be a Utf8SourceInfo pinned by it.
  6241. Assert(this->m_utf8SourceInfo);
  6242. this->GetUtf8SourceInfo()->RemoveFunctionBody(this);
  6243. }
  6244. if (this->m_sourceInfo.pSpanSequence != nullptr)
  6245. {
  6246. HeapDelete(this->m_sourceInfo.pSpanSequence);
  6247. this->m_sourceInfo.pSpanSequence = nullptr;
  6248. }
  6249. sourceInfoCleanedUp = true;
  6250. }
  6251. }
  6252. template<bool IsScriptContextShutdown>
  6253. void FunctionBody::CleanUpInlineCaches()
  6254. {
  6255. uint unregisteredInlineCacheCount = 0;
  6256. if (nullptr != this->inlineCaches)
  6257. {
  6258. // Inline caches are in this order
  6259. // plain inline cache
  6260. // root object load inline cache
  6261. // root object store inline cache
  6262. // isInst inline cache
  6263. // The inlineCacheCount includes all but isInst inline cache
  6264. uint i = 0;
  6265. uint plainInlineCacheEnd = GetRootObjectLoadInlineCacheStart();
  6266. for (; i < plainInlineCacheEnd; i++)
  6267. {
  6268. if (nullptr != this->inlineCaches[i])
  6269. {
  6270. InlineCache* inlineCache = (InlineCache*)this->inlineCaches[i];
  6271. if (IsScriptContextShutdown)
  6272. {
  6273. inlineCache->Clear();
  6274. }
  6275. else
  6276. {
  6277. if (inlineCache->RemoveFromInvalidationList())
  6278. {
  6279. unregisteredInlineCacheCount++;
  6280. }
  6281. AllocatorDelete(InlineCacheAllocator, this->m_scriptContext->GetInlineCacheAllocator(), inlineCache);
  6282. }
  6283. }
  6284. }
  6285. RootObjectBase * rootObjectBase = this->GetRootObject();
  6286. uint rootObjectLoadInlineCacheEnd = GetRootObjectLoadMethodInlineCacheStart();
  6287. for (; i < rootObjectLoadInlineCacheEnd; i++)
  6288. {
  6289. if (nullptr != this->inlineCaches[i])
  6290. {
  6291. if (IsScriptContextShutdown)
  6292. {
  6293. ((InlineCache*)this->inlineCaches[i])->Clear();
  6294. }
  6295. else
  6296. {
  6297. // A single root object inline caches for a given property is shared by all functions. It is ref counted
  6298. // and doesn't get released to the allocator until there are no more outstanding references. Thus we don't need
  6299. // to (and, in fact, cannot) remove it from the invalidation list here. Instead, we'll do it in ReleaseInlineCache
  6300. // when there are no more outstanding references.
  6301. unregisteredInlineCacheCount += rootObjectBase->ReleaseInlineCache(this->GetPropertyIdFromCacheId(i), false, false, IsScriptContextShutdown);
  6302. }
  6303. }
  6304. }
  6305. uint rootObjectLoadMethodInlineCacheEnd = GetRootObjectStoreInlineCacheStart();
  6306. for (; i < rootObjectLoadMethodInlineCacheEnd; i++)
  6307. {
  6308. if (nullptr != this->inlineCaches[i])
  6309. {
  6310. if (IsScriptContextShutdown)
  6311. {
  6312. ((InlineCache*)this->inlineCaches[i])->Clear();
  6313. }
  6314. else
  6315. {
  6316. // A single root object inline caches for a given property is shared by all functions. It is ref counted
  6317. // and doesn't get released to the allocator until there are no more outstanding references. Thus we don't need
  6318. // to (and, in fact, cannot) remove it from the invalidation list here. Instead, we'll do it in ReleaseInlineCache
  6319. // when there are no more outstanding references.
  6320. unregisteredInlineCacheCount += rootObjectBase->ReleaseInlineCache(this->GetPropertyIdFromCacheId(i), true, false, IsScriptContextShutdown);
  6321. }
  6322. }
  6323. }
  6324. uint rootObjectStoreInlineCacheEnd = this->GetInlineCacheCount();
  6325. for (; i < rootObjectStoreInlineCacheEnd; i++)
  6326. {
  6327. if (nullptr != this->inlineCaches[i])
  6328. {
  6329. if (IsScriptContextShutdown)
  6330. {
  6331. ((InlineCache*)this->inlineCaches[i])->Clear();
  6332. }
  6333. else
  6334. {
  6335. // A single root object inline caches for a given property is shared by all functions. It is ref counted
  6336. // and doesn't get released to the allocator until there are no more outstanding references. Thus we don't need
  6337. // to (and, in fact, cannot) remove it from the invalidation list here. Instead, we'll do it in ReleaseInlineCache
  6338. // when there are no more outstanding references.
  6339. unregisteredInlineCacheCount += rootObjectBase->ReleaseInlineCache(this->GetPropertyIdFromCacheId(i), false, true, IsScriptContextShutdown);
  6340. }
  6341. }
  6342. }
  6343. uint totalCacheCount = GetInlineCacheCount() + GetIsInstInlineCacheCount();
  6344. for (; i < totalCacheCount; i++)
  6345. {
  6346. if (nullptr != this->inlineCaches[i])
  6347. {
  6348. IsInstInlineCache* inlineCache = (IsInstInlineCache*)this->inlineCaches[i];
  6349. if (IsScriptContextShutdown)
  6350. {
  6351. inlineCache->Clear();
  6352. }
  6353. else
  6354. {
  6355. inlineCache->Unregister(this->m_scriptContext);
  6356. AllocatorDelete(CacheAllocator, this->m_scriptContext->GetIsInstInlineCacheAllocator(), inlineCache);
  6357. }
  6358. }
  6359. }
  6360. this->inlineCaches = nullptr;
  6361. }
  6362. auto codeGenRuntimeData = this->GetCodeGenRuntimeData();
  6363. if (nullptr != codeGenRuntimeData)
  6364. {
  6365. for (ProfileId i = 0; i < this->profiledCallSiteCount; i++)
  6366. {
  6367. const FunctionCodeGenRuntimeData* runtimeData = codeGenRuntimeData[i];
  6368. if (nullptr != runtimeData)
  6369. {
  6370. runtimeData->MapInlineCaches([&](InlineCache* inlineCache)
  6371. {
  6372. if (nullptr != inlineCache)
  6373. {
  6374. if (IsScriptContextShutdown)
  6375. {
  6376. inlineCache->Clear();
  6377. }
  6378. else
  6379. {
  6380. if (inlineCache->RemoveFromInvalidationList())
  6381. {
  6382. unregisteredInlineCacheCount++;
  6383. }
  6384. AllocatorDelete(InlineCacheAllocator, this->m_scriptContext->GetInlineCacheAllocator(), inlineCache);
  6385. }
  6386. }
  6387. });
  6388. }
  6389. }
  6390. }
  6391. auto codeGenGetSetRuntimeData = this->GetCodeGenGetSetRuntimeData();
  6392. if (codeGenGetSetRuntimeData != nullptr)
  6393. {
  6394. for (uint i = 0; i < this->GetInlineCacheCount(); i++)
  6395. {
  6396. auto runtimeData = codeGenGetSetRuntimeData[i];
  6397. if (nullptr != runtimeData)
  6398. {
  6399. runtimeData->MapInlineCaches([&](InlineCache* inlineCache)
  6400. {
  6401. if (nullptr != inlineCache)
  6402. {
  6403. if (IsScriptContextShutdown)
  6404. {
  6405. inlineCache->Clear();
  6406. }
  6407. else
  6408. {
  6409. if (inlineCache->RemoveFromInvalidationList())
  6410. {
  6411. unregisteredInlineCacheCount++;
  6412. }
  6413. AllocatorDelete(InlineCacheAllocator, this->m_scriptContext->GetInlineCacheAllocator(), inlineCache);
  6414. }
  6415. }
  6416. });
  6417. }
  6418. }
  6419. }
  6420. if (unregisteredInlineCacheCount > 0)
  6421. {
  6422. AssertMsg(!IsScriptContextShutdown, "Unregistration of inlineCache should only be done if this is not scriptContext shutdown.");
  6423. ThreadContext* threadContext = this->m_scriptContext->GetThreadContext();
  6424. threadContext->NotifyInlineCacheBatchUnregistered(unregisteredInlineCacheCount);
  6425. }
  6426. while (this->GetPolymorphicInlineCachesHead())
  6427. {
  6428. this->GetPolymorphicInlineCachesHead()->Finalize(IsScriptContextShutdown);
  6429. }
  6430. polymorphicInlineCaches.Reset();
  6431. }
  6432. void FunctionBody::CleanupRecyclerData(bool isShutdown, bool doEntryPointCleanupCaptureStack)
  6433. {
  6434. // If we're not shutting down (i.e closing the script context), we need to remove our inline caches from
  6435. // thread context's invalidation lists, and release memory back to the arena. During script context shutdown,
  6436. // we leave everything in place, because the inline cache arena will stay alive until script context is destroyed
  6437. // (i.e it's destructor has been called) and thus the invalidation lists are safe to keep references to caches from this
  6438. // script context. We will, however, zero all inline caches so that we don't have to process them on subsequent
  6439. // collections, which may still happen from other script contexts.
  6440. if (isShutdown)
  6441. {
  6442. CleanUpInlineCaches<true>();
  6443. }
  6444. else
  6445. {
  6446. CleanUpInlineCaches<false>();
  6447. }
  6448. if (this->entryPoints)
  6449. {
  6450. #if defined(ENABLE_DEBUG_CONFIG_OPTIONS) && !(DBG)
  6451. // On fretest builds, capture the stack only if the FreTestDiagMode switch is on
  6452. doEntryPointCleanupCaptureStack = doEntryPointCleanupCaptureStack && Js::Configuration::Global.flags.FreTestDiagMode;
  6453. #endif
  6454. this->MapEntryPoints([=](int index, FunctionEntryPointInfo* entryPoint)
  6455. {
  6456. if (nullptr != entryPoint)
  6457. {
  6458. // Finalize = Free up work item if it hasn't been released yet + entry point clean up
  6459. // isShutdown is false because cleanup is called only in the !isShutdown case
  6460. entryPoint->Finalize(isShutdown);
  6461. #if ENABLE_ENTRYPOINT_CLEANUP_TRACE
  6462. #if ENABLE_DEBUG_STACK_BACK_TRACE
  6463. // Do this separately since calling EntryPoint::Finalize doesn't capture the stack trace
  6464. // and in some calls to CleanupRecyclerData, we do want the stack trace captured.
  6465. if (doEntryPointCleanupCaptureStack)
  6466. {
  6467. entryPoint->CaptureCleanupStackTrace();
  6468. }
  6469. #endif
  6470. #endif
  6471. }
  6472. });
  6473. this->MapLoopHeaders([=](uint loopNumber, LoopHeader* header)
  6474. {
  6475. bool shuttingDown = isShutdown;
  6476. header->MapEntryPoints([=](int index, LoopEntryPointInfo* entryPoint)
  6477. {
  6478. entryPoint->Cleanup(shuttingDown, doEntryPointCleanupCaptureStack);
  6479. });
  6480. });
  6481. }
  6482. #ifdef PERF_COUNTERS
  6483. this->CleanupPerfCounter();
  6484. #endif
  6485. }
  6486. //
  6487. // Removes all references of the function body and causes clean up of entry points.
  6488. // If the cleanup has already occurred before this would be a no-op.
  6489. //
  6490. void FunctionBody::Cleanup(bool isScriptContextClosing)
  6491. {
  6492. if (cleanedUp)
  6493. {
  6494. return;
  6495. }
  6496. DebugOnly(this->UnlockCounters());
  6497. CleanupRecyclerData(isScriptContextClosing, false /* capture entry point cleanup stack trace */);
  6498. CleanUpForInCache(isScriptContextClosing);
  6499. this->SetObjLiteralCount(0);
  6500. this->SetScopeSlotArraySizes(0, 0);
  6501. // Manually clear these values to break any circular references
  6502. // that might prevent the script context from being disposed
  6503. this->auxPtrs = nullptr;
  6504. AssertMsg(isScriptContextClosing || !m_hasActiveReference || !this->byteCodeBlock || !this->IsWasmFunction(), "We should never reset the bytecode block for Wasm when still referenced");
  6505. this->byteCodeBlock = nullptr;
  6506. this->entryPoints = nullptr;
  6507. this->inlineCaches = nullptr;
  6508. this->cacheIdToPropertyIdMap = nullptr;
  6509. this->polymorphicInlineCaches.Reset();
  6510. this->SetConstTable(nullptr);
  6511. #if DYNAMIC_INTERPRETER_THUNK
  6512. if (this->HasInterpreterThunkGenerated())
  6513. {
  6514. JS_ETW(EtwTrace::LogMethodInterpreterThunkUnloadEvent(this));
  6515. if (!isScriptContextClosing)
  6516. {
  6517. if (m_isAsmJsFunction)
  6518. {
  6519. m_scriptContext->ReleaseDynamicAsmJsInterpreterThunk((BYTE*)this->m_dynamicInterpreterThunk, /*addtoFreeList*/ true);
  6520. }
  6521. else
  6522. {
  6523. m_scriptContext->ReleaseDynamicInterpreterThunk((BYTE*)this->m_dynamicInterpreterThunk, /*addtoFreeList*/ true);
  6524. }
  6525. }
  6526. }
  6527. #endif
  6528. this->cleanedUp = true;
  6529. DebugOnly(this->LockDownCounters());
  6530. }
  6531. #ifdef PERF_COUNTERS
  6532. void FunctionBody::CleanupPerfCounter()
  6533. {
  6534. // We might not have the byte code block yet if we defer parsed.
  6535. DWORD byteCodeSize = (this->byteCodeBlock? this->byteCodeBlock->GetLength() : 0)
  6536. + (this->GetAuxiliaryData() ? this->GetAuxiliaryData()->GetLength() : 0)
  6537. + (this->GetAuxiliaryContextData() ? this->GetAuxiliaryContextData()->GetLength() : 0);
  6538. PERF_COUNTER_SUB(Code, DynamicByteCodeSize, byteCodeSize);
  6539. if (this->m_isDeserializedFunction)
  6540. {
  6541. PERF_COUNTER_DEC(Code, DeserializedFunctionBody);
  6542. }
  6543. PERF_COUNTER_SUB(Code, TotalByteCodeSize, byteCodeSize);
  6544. }
  6545. #endif
  6546. void FunctionBody::CaptureDynamicProfileState(FunctionEntryPointInfo* entryPointInfo)
  6547. {
  6548. // DisableJIT-TODO: Move this to be under if DYNAMIC_PROFILE
  6549. #if ENABLE_NATIVE_CODEGEN
  6550. // (See also the FunctionBody member written in CaptureDynamicProfileState.)
  6551. this->SetSavedPolymorphicCacheState(entryPointInfo->GetNativeEntryPointData()->GetPendingPolymorphicCacheState());
  6552. this->savedInlinerVersion = entryPointInfo->GetNativeEntryPointData()->GetPendingInlinerVersion();
  6553. this->savedImplicitCallsFlags = entryPointInfo->GetNativeEntryPointData()->GetPendingImplicitCallFlags();
  6554. #endif
  6555. }
  6556. #if ENABLE_NATIVE_CODEGEN
  6557. BYTE FunctionBody::GetSavedInlinerVersion() const
  6558. {
  6559. Assert(this->dynamicProfileInfo != nullptr);
  6560. return this->savedInlinerVersion;
  6561. }
  6562. uint32 FunctionBody::GetSavedPolymorphicCacheState() const
  6563. {
  6564. Assert(this->dynamicProfileInfo != nullptr);
  6565. return this->savedPolymorphicCacheState;
  6566. }
  6567. void FunctionBody::SetSavedPolymorphicCacheState(uint32 state)
  6568. {
  6569. this->savedPolymorphicCacheState = state;
  6570. }
  6571. #endif
  6572. void FunctionBody::SetHasHotLoop()
  6573. {
  6574. if(hasHotLoop)
  6575. {
  6576. return;
  6577. }
  6578. hasHotLoop = true;
  6579. if(Configuration::Global.flags.EnforceExecutionModeLimits)
  6580. {
  6581. return;
  6582. }
  6583. executionState.CommitExecutedIterations();
  6584. TraceExecutionMode("HasHotLoop (before)");
  6585. if(executionState.GetFullJitThreshold() > 1)
  6586. {
  6587. executionState.SetFullJitThreshold(1, true);
  6588. }
  6589. TraceExecutionMode("HasHotLoop");
  6590. }
  6591. bool FunctionBody::IsInlineApplyDisabled()
  6592. {
  6593. return this->disableInlineApply;
  6594. }
  6595. void FunctionBody::SetDisableInlineApply(bool set)
  6596. {
  6597. this->disableInlineApply = set;
  6598. }
  6599. void FunctionBody::InitDisableInlineApply()
  6600. {
  6601. SetDisableInlineApply(
  6602. (this->GetLocalFunctionId() != Js::Constants::NoFunctionId && PHASE_OFF(Js::InlinePhase, this)) ||
  6603. PHASE_OFF(Js::InlineApplyPhase, this));
  6604. }
  6605. bool FunctionBody::CheckCalleeContextForInlining(FunctionProxy* calleeFunctionProxy)
  6606. {
  6607. return this->GetScriptContext() == calleeFunctionProxy->GetScriptContext() &&
  6608. this->GetSecondaryHostSourceContext() == calleeFunctionProxy->GetSecondaryHostSourceContext();
  6609. }
  6610. #if ENABLE_NATIVE_CODEGEN
  6611. ImplicitCallFlags FunctionBody::GetSavedImplicitCallsFlags() const
  6612. {
  6613. Assert(this->dynamicProfileInfo != nullptr);
  6614. return this->savedImplicitCallsFlags;
  6615. }
  6616. bool FunctionBody::HasNonBuiltInCallee()
  6617. {
  6618. for (ProfileId i = 0; i < profiledCallSiteCount; i++)
  6619. {
  6620. Assert(HasDynamicProfileInfo());
  6621. if (dynamicProfileInfo->MayHaveNonBuiltinCallee(i))
  6622. {
  6623. return true;
  6624. }
  6625. }
  6626. return false;
  6627. }
  6628. #endif
  6629. #ifdef ENABLE_SCRIPT_DEBUGGING
  6630. void FunctionBody::CheckAndRegisterFuncToDiag(ScriptContext *scriptContext)
  6631. {
  6632. // We will register function if, this is not host managed and it was not registered before.
  6633. if (GetHostSourceContext() == Js::Constants::NoHostSourceContext
  6634. && !m_isFuncRegisteredToDiag
  6635. && !scriptContext->GetDebugContext()->GetProbeContainer()->IsContextRegistered(GetSecondaryHostSourceContext()))
  6636. {
  6637. FunctionBody *pFunc = scriptContext->GetDebugContext()->GetProbeContainer()->GetGlobalFunc(scriptContext, GetSecondaryHostSourceContext());
  6638. if (pFunc)
  6639. {
  6640. // Existing behavior here is to ignore the OOM and since RegisterFuncToDiag
  6641. // can throw now, we simply ignore the OOM here
  6642. try
  6643. {
  6644. // Register the function to the PDM as eval code (the debugger app will show file as 'eval code')
  6645. pFunc->RegisterFuncToDiag(scriptContext, Constants::EvalCode);
  6646. }
  6647. catch (Js::OutOfMemoryException)
  6648. {
  6649. }
  6650. scriptContext->GetDebugContext()->GetProbeContainer()->RegisterContextToDiag(GetSecondaryHostSourceContext(), scriptContext->AllocatorForDiagnostics());
  6651. m_isFuncRegisteredToDiag = true;
  6652. }
  6653. }
  6654. else
  6655. {
  6656. m_isFuncRegisteredToDiag = true;
  6657. }
  6658. }
  6659. #endif
  6660. DebuggerScope* FunctionBody::RecordStartScopeObject(DiagExtraScopesType scopeType, int start, RegSlot scopeLocation, int* index)
  6661. {
  6662. Recycler* recycler = m_scriptContext->GetRecycler();
  6663. if (!GetScopeObjectChain())
  6664. {
  6665. SetScopeObjectChain(RecyclerNew(recycler, ScopeObjectChain, recycler));
  6666. }
  6667. // Check if we need to create the scope object or if it already exists from a previous bytecode
  6668. // generator pass.
  6669. DebuggerScope* debuggerScope = nullptr;
  6670. int currentDebuggerScopeIndex = this->GetNextDebuggerScopeIndex();
  6671. if (!this->TryGetDebuggerScopeAt(currentDebuggerScopeIndex, debuggerScope))
  6672. {
  6673. // Create a new debugger scope.
  6674. debuggerScope = AddScopeObject(scopeType, start, scopeLocation);
  6675. }
  6676. else
  6677. {
  6678. debuggerScope->UpdateDueToByteCodeRegeneration(scopeType, start, scopeLocation);
  6679. }
  6680. if(index)
  6681. {
  6682. *index = currentDebuggerScopeIndex;
  6683. }
  6684. return debuggerScope;
  6685. }
  6686. void FunctionBody::RecordEndScopeObject(DebuggerScope* currentScope, int end)
  6687. {
  6688. AssertMsg(currentScope, "No current debugger scope passed in.");
  6689. currentScope->SetEnd(end);
  6690. }
  6691. DebuggerScope * FunctionBody::AddScopeObject(DiagExtraScopesType scopeType, int start, RegSlot scopeLocation)
  6692. {
  6693. Assert(GetScopeObjectChain());
  6694. DebuggerScope *scopeObject = RecyclerNew(m_scriptContext->GetRecycler(), DebuggerScope, m_scriptContext->GetRecycler(), scopeType, scopeLocation, start);
  6695. GetScopeObjectChain()->pScopeChain->Add(scopeObject);
  6696. return scopeObject;
  6697. }
  6698. // Tries to retrieve the debugger scope at the specified index. If the index is out of range, nullptr
  6699. // is returned.
  6700. bool FunctionBody::TryGetDebuggerScopeAt(int index, DebuggerScope*& debuggerScope)
  6701. {
  6702. AssertMsg(this->GetScopeObjectChain(), "TryGetDebuggerScopeAt should only be called with a valid scope chain in place.");
  6703. Assert(index >= 0);
  6704. const Js::ScopeObjectChain::ScopeObjectChainList* scopeChain = this->GetScopeObjectChain()->pScopeChain;
  6705. if (index < scopeChain->Count())
  6706. {
  6707. debuggerScope = scopeChain->Item(index);
  6708. return true;
  6709. }
  6710. return false;
  6711. }
  6712. #if DYNAMIC_INTERPRETER_THUNK
  6713. DWORD FunctionBody::GetDynamicInterpreterThunkSize() const
  6714. {
  6715. return InterpreterThunkEmitter::ThunkSize;
  6716. }
  6717. #endif
  6718. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  6719. void
  6720. FunctionBody::DumpFullFunctionName()
  6721. {
  6722. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  6723. Output::Print(_u("Function %s (%s)"), this->GetDisplayName(), this->GetDebugNumberSet(debugStringBuffer));
  6724. }
  6725. void FunctionBody::DumpFunctionId(bool pad)
  6726. {
  6727. uint sourceContextId = this->GetSourceContextInfo()->sourceContextId;
  6728. if (sourceContextId == Js::Constants::NoSourceContext)
  6729. {
  6730. if (this->IsDynamicScript())
  6731. {
  6732. Output::Print(pad? _u("Dy.%-3d") : _u("Dyn#%d"), this->GetLocalFunctionId());
  6733. }
  6734. else
  6735. {
  6736. // Function from LoadFile
  6737. Output::Print(pad? _u("%-5d") : _u("#%d"), this->GetLocalFunctionId());
  6738. }
  6739. }
  6740. else
  6741. {
  6742. Output::Print(pad? _u("%2d.%-3d") : _u("#%d.%d"), sourceContextId, this->GetLocalFunctionId());
  6743. }
  6744. }
  6745. #endif
  6746. void FunctionBody::EnsureAuxStatementData()
  6747. {
  6748. if (m_sourceInfo.m_auxStatementData == nullptr)
  6749. {
  6750. Recycler* recycler = m_scriptContext->GetRecycler();
  6751. // Note: allocating must be consistent with clean up in CleanupToReparse.
  6752. m_sourceInfo.m_auxStatementData = RecyclerNew(recycler, AuxStatementData);
  6753. }
  6754. }
  6755. /*static*/
  6756. void FunctionBody::GetShortNameFromUrl(__in LPCWSTR pchUrl, _Out_writes_z_(cchBuffer) LPWSTR pchShortName, __in size_t cchBuffer)
  6757. {
  6758. LPCWSTR pchFile = wcsrchr(pchUrl, _u('/'));
  6759. if (pchFile == nullptr)
  6760. {
  6761. pchFile = wcsrchr(pchUrl, _u('\\'));
  6762. }
  6763. LPCWSTR pchToCopy = pchUrl;
  6764. if (pchFile != nullptr)
  6765. {
  6766. pchToCopy = pchFile + 1;
  6767. }
  6768. wcscpy_s(pchShortName, cchBuffer, pchToCopy);
  6769. }
  6770. FunctionBody::StatementAdjustmentRecordList* FunctionBody::GetStatementAdjustmentRecords()
  6771. {
  6772. if (m_sourceInfo.m_auxStatementData)
  6773. {
  6774. return m_sourceInfo.m_auxStatementData->m_statementAdjustmentRecords;
  6775. }
  6776. return nullptr;
  6777. }
  6778. FunctionBody::CrossFrameEntryExitRecordList* FunctionBody::GetCrossFrameEntryExitRecords()
  6779. {
  6780. if (m_sourceInfo.m_auxStatementData)
  6781. {
  6782. return m_sourceInfo.m_auxStatementData->m_crossFrameBlockEntryExisRecords;
  6783. }
  6784. return nullptr;
  6785. }
  6786. void FunctionBody::RecordCrossFrameEntryExitRecord(uint byteCodeOffset, bool isEnterBlock)
  6787. {
  6788. this->EnsureAuxStatementData();
  6789. Recycler* recycler = this->m_scriptContext->GetRecycler();
  6790. if (this->GetCrossFrameEntryExitRecords() == nullptr)
  6791. {
  6792. m_sourceInfo.m_auxStatementData->m_crossFrameBlockEntryExisRecords = RecyclerNew(recycler, CrossFrameEntryExitRecordList, recycler);
  6793. }
  6794. Assert(this->GetCrossFrameEntryExitRecords());
  6795. CrossFrameEntryExitRecord record(byteCodeOffset, isEnterBlock);
  6796. this->GetCrossFrameEntryExitRecords()->Add(record); // Will copy stack value and put the copy into the container.
  6797. }
  6798. FunctionBody::AuxStatementData::AuxStatementData() : m_statementAdjustmentRecords(nullptr), m_crossFrameBlockEntryExisRecords(nullptr)
  6799. {
  6800. }
  6801. FunctionBody::StatementAdjustmentRecord::StatementAdjustmentRecord() :
  6802. m_byteCodeOffset((uint)Constants::InvalidOffset), m_adjustmentType(SAT_None)
  6803. {
  6804. }
  6805. FunctionBody::StatementAdjustmentRecord::StatementAdjustmentRecord(StatementAdjustmentType type, int byteCodeOffset) :
  6806. m_adjustmentType(type), m_byteCodeOffset(byteCodeOffset)
  6807. {
  6808. Assert(SAT_None <= type && type <= SAT_All);
  6809. }
  6810. FunctionBody::StatementAdjustmentRecord::StatementAdjustmentRecord(const StatementAdjustmentRecord& other) :
  6811. m_byteCodeOffset(other.m_byteCodeOffset), m_adjustmentType(other.m_adjustmentType)
  6812. {
  6813. }
  6814. uint FunctionBody::StatementAdjustmentRecord::GetByteCodeOffset()
  6815. {
  6816. Assert(m_byteCodeOffset != Constants::InvalidOffset);
  6817. return m_byteCodeOffset;
  6818. }
  6819. FunctionBody::StatementAdjustmentType FunctionBody::StatementAdjustmentRecord::GetAdjustmentType()
  6820. {
  6821. Assert(this->m_adjustmentType != SAT_None);
  6822. return m_adjustmentType;
  6823. }
  6824. FunctionBody::CrossFrameEntryExitRecord::CrossFrameEntryExitRecord() :
  6825. m_byteCodeOffset((uint)Constants::InvalidOffset), m_isEnterBlock(false)
  6826. {
  6827. }
  6828. FunctionBody::CrossFrameEntryExitRecord::CrossFrameEntryExitRecord(uint byteCodeOffset, bool isEnterBlock) :
  6829. m_byteCodeOffset(byteCodeOffset), m_isEnterBlock(isEnterBlock)
  6830. {
  6831. }
  6832. FunctionBody::CrossFrameEntryExitRecord::CrossFrameEntryExitRecord(const CrossFrameEntryExitRecord& other) :
  6833. m_byteCodeOffset(other.m_byteCodeOffset), m_isEnterBlock(other.m_isEnterBlock)
  6834. {
  6835. }
  6836. uint FunctionBody::CrossFrameEntryExitRecord::GetByteCodeOffset() const
  6837. {
  6838. Assert(m_byteCodeOffset != Constants::InvalidOffset);
  6839. return m_byteCodeOffset;
  6840. }
  6841. bool FunctionBody::CrossFrameEntryExitRecord::GetIsEnterBlock()
  6842. {
  6843. return m_isEnterBlock;
  6844. }
  6845. EntryPointPolymorphicInlineCacheInfo::EntryPointPolymorphicInlineCacheInfo(FunctionBody * functionBody) :
  6846. selfInfo(functionBody),
  6847. inlineeInfo(functionBody->GetRecycler())
  6848. {
  6849. }
  6850. PolymorphicInlineCacheInfo * EntryPointPolymorphicInlineCacheInfo::GetInlineeInfo(FunctionBody * inlineeFunctionBody)
  6851. {
  6852. SListCounted<PolymorphicInlineCacheInfo*, Recycler>::Iterator iter(&inlineeInfo);
  6853. while (iter.Next())
  6854. {
  6855. PolymorphicInlineCacheInfo * info = iter.Data();
  6856. if (info->GetFunctionBody() == inlineeFunctionBody)
  6857. {
  6858. return info;
  6859. }
  6860. }
  6861. return nullptr;
  6862. }
  6863. PolymorphicInlineCacheInfo * EntryPointPolymorphicInlineCacheInfo::EnsureInlineeInfo(Recycler * recycler, FunctionBody * inlineeFunctionBody)
  6864. {
  6865. PolymorphicInlineCacheInfo * info = GetInlineeInfo(inlineeFunctionBody);
  6866. if (!info)
  6867. {
  6868. info = RecyclerNew(recycler, PolymorphicInlineCacheInfo, inlineeFunctionBody);
  6869. inlineeInfo.Prepend(info);
  6870. }
  6871. return info;
  6872. }
  6873. void EntryPointPolymorphicInlineCacheInfo::SetPolymorphicInlineCache(FunctionBody * functionBody, uint index, PolymorphicInlineCache * polymorphicInlineCache, bool isInlinee, byte polyCacheUtil)
  6874. {
  6875. if (!isInlinee)
  6876. {
  6877. SetPolymorphicInlineCache(&selfInfo, functionBody, index, polymorphicInlineCache, polyCacheUtil);
  6878. Assert(functionBody == selfInfo.GetFunctionBody());
  6879. }
  6880. else
  6881. {
  6882. SetPolymorphicInlineCache(EnsureInlineeInfo(functionBody->GetScriptContext()->GetRecycler(), functionBody), functionBody, index, polymorphicInlineCache, polyCacheUtil);
  6883. Assert(functionBody == GetInlineeInfo(functionBody)->GetFunctionBody());
  6884. }
  6885. }
  6886. void EntryPointPolymorphicInlineCacheInfo::SetPolymorphicInlineCache(PolymorphicInlineCacheInfo * polymorphicInlineCacheInfo, FunctionBody * functionBody, uint index, PolymorphicInlineCache * polymorphicInlineCache, byte polyCacheUtil)
  6887. {
  6888. polymorphicInlineCacheInfo->GetPolymorphicInlineCaches()->SetInlineCache(functionBody->GetScriptContext()->GetRecycler(), functionBody, index, polymorphicInlineCache);
  6889. polymorphicInlineCacheInfo->GetUtilArray()->SetUtil(functionBody, index, polyCacheUtil);
  6890. }
  6891. void PolymorphicCacheUtilizationArray::SetUtil(Js::FunctionBody* functionBody, uint index, byte util)
  6892. {
  6893. Assert(functionBody);
  6894. Assert(index < functionBody->GetInlineCacheCount());
  6895. EnsureUtilArray(functionBody->GetScriptContext()->GetRecycler(), functionBody);
  6896. this->utilArray[index] = util;
  6897. }
  6898. byte PolymorphicCacheUtilizationArray::GetUtil(Js::FunctionBody* functionBody, uint index)
  6899. {
  6900. Assert(index < functionBody->GetInlineCacheCount());
  6901. return this->utilArray[index];
  6902. }
  6903. void PolymorphicCacheUtilizationArray::EnsureUtilArray(Recycler * const recycler, Js::FunctionBody * functionBody)
  6904. {
  6905. Assert(recycler);
  6906. Assert(functionBody);
  6907. Assert(functionBody->GetInlineCacheCount() != 0);
  6908. if(this->utilArray)
  6909. {
  6910. return;
  6911. }
  6912. this->utilArray = RecyclerNewArrayLeafZ(recycler, byte, functionBody->GetInlineCacheCount());
  6913. }
  6914. #if ENABLE_NATIVE_CODEGEN
  6915. DWORD_PTR EntryPointInfo::GetNativeAddress() const
  6916. {
  6917. // need the assert to skip for asmjsFunction as nativeAddress can be interpreter too for asmjs
  6918. Assert(this->GetState() == CodeGenRecorded || this->GetState() == CodeGenDone || this->isAsmJsFunction);
  6919. // !! this is illegal, however (by design) `IsInNativeAddressRange` needs it
  6920. return reinterpret_cast<DWORD_PTR>(this->GetNativeEntryPointData()->GetNativeAddress());
  6921. }
  6922. Js::JavascriptMethod EntryPointInfo::GetThunkAddress() const
  6923. {
  6924. Assert(this->GetState() == CodeGenRecorded || this->GetState() == CodeGenDone);
  6925. return this->GetNativeEntryPointData()->GetThunkAddress();
  6926. }
  6927. Js::JavascriptMethod EntryPointInfo::GetNativeEntrypoint() const
  6928. {
  6929. Assert(this->GetState() == CodeGenRecorded || this->GetState() == CodeGenDone || this->isAsmJsFunction);
  6930. Js::JavascriptMethod thunkAddress = this->GetNativeEntryPointData()->GetThunkAddress();
  6931. return thunkAddress ? thunkAddress : this->GetNativeEntryPointData()->GetNativeAddress();
  6932. }
  6933. ptrdiff_t EntryPointInfo::GetCodeSize() const
  6934. {
  6935. Assert(this->GetState() == CodeGenRecorded || this->GetState() == CodeGenDone);
  6936. return this->GetNativeEntryPointData()->GetCodeSize();
  6937. }
  6938. JitTransferData * EntryPointInfo::GetJitTransferData()
  6939. {
  6940. return this->GetNativeEntryPointData()->GetJitTransferData();
  6941. }
  6942. SmallSpanSequence* EntryPointInfo::GetNativeThrowSpanSequence() const
  6943. {
  6944. Assert(this->GetState() != NotScheduled);
  6945. Assert(this->GetState() != CleanedUp);
  6946. return this->GetNativeEntryPointData()->GetNativeThrowSpanSequence();
  6947. }
  6948. void EntryPointInfo::SetNativeThrowSpanSequence(SmallSpanSequence* seq)
  6949. {
  6950. Assert(this->GetState() == CodeGenQueued);
  6951. Assert(this->GetNativeEntryPointData()->GetNativeThrowSpanSequence() == nullptr);
  6952. this->GetNativeEntryPointData()->SetNativeThrowSpanSequence(seq);
  6953. }
  6954. uint EntryPointInfo::GetFrameHeight()
  6955. {
  6956. return this->GetNativeEntryPointData()->GetFrameHeight();
  6957. }
  6958. bool EntryPointInfo::HasInlinees()
  6959. {
  6960. return this->GetFrameHeight() > 0;
  6961. }
  6962. NativeEntryPointData * EntryPointInfo::EnsureNativeEntryPointData()
  6963. {
  6964. NativeEntryPointData * data = this->nativeEntryPointData;
  6965. if (data == nullptr)
  6966. {
  6967. #if ENABLE_OOP_NATIVE_CODEGEN
  6968. if (JITManager::GetJITManager()->IsOOPJITEnabled())
  6969. {
  6970. data = RecyclerNew(this->GetScriptContext()->GetRecycler(), OOPNativeEntryPointData);
  6971. }
  6972. else
  6973. #endif
  6974. {
  6975. data = RecyclerNew(this->GetScriptContext()->GetRecycler(), InProcNativeEntryPointData);
  6976. }
  6977. this->nativeEntryPointData = data;
  6978. }
  6979. return data;
  6980. }
  6981. bool EntryPointInfo::HasNativeEntryPointData() const
  6982. {
  6983. return this->nativeEntryPointData != nullptr;
  6984. }
  6985. NativeEntryPointData * EntryPointInfo::GetNativeEntryPointData() const
  6986. {
  6987. Assert(this->HasNativeEntryPointData());
  6988. return this->nativeEntryPointData;
  6989. }
  6990. InProcNativeEntryPointData * EntryPointInfo::GetInProcNativeEntryPointData()
  6991. {
  6992. return static_cast<InProcNativeEntryPointData *>(this->GetNativeEntryPointData());
  6993. }
  6994. #if ENABLE_OOP_NATIVE_CODEGEN
  6995. OOPNativeEntryPointData * EntryPointInfo::GetOOPNativeEntryPointData()
  6996. {
  6997. return static_cast<OOPNativeEntryPointData *>(this->GetNativeEntryPointData());
  6998. }
  6999. #endif
  7000. void EntryPointInfo::EnsureIsReadyToCall()
  7001. {
  7002. ProcessJitTransferData();
  7003. #if ENABLE_OOP_NATIVE_CODEGEN
  7004. #if !FLOATVAR
  7005. if (JITManager::GetJITManager()->IsOOPJITEnabled())
  7006. {
  7007. this->GetOOPNativeEntryPointData()->ProcessNumberPageSegments(GetScriptContext());
  7008. }
  7009. #endif
  7010. #endif
  7011. }
  7012. void EntryPointInfo::SetCodeGenRecorded(Js::JavascriptMethod thunkAddress, Js::JavascriptMethod nativeAddress, ptrdiff_t codeSize, void * validationCookie)
  7013. {
  7014. Assert(this->GetState() == CodeGenQueued);
  7015. Assert(codeSize > 0);
  7016. this->GetNativeEntryPointData()->RecordNativeCode(thunkAddress, nativeAddress, codeSize, validationCookie);
  7017. this->state = CodeGenRecorded;
  7018. #ifdef PERF_COUNTERS
  7019. this->OnRecorded();
  7020. #endif
  7021. }
  7022. void EntryPointInfo::SetCodeGenDone()
  7023. {
  7024. Assert(this->GetState() == CodeGenRecorded);
  7025. this->state = CodeGenDone;
  7026. this->workItem = nullptr;
  7027. if (this->IsLoopBody())
  7028. {
  7029. this->GetFunctionBody()->SetHasDoneLoopBodyCodeGen(true);
  7030. }
  7031. }
  7032. void EntryPointInfo::ProcessJitTransferData()
  7033. {
  7034. Assert(!IsCleanedUp());
  7035. auto jitTransferData = GetJitTransferData();
  7036. if (jitTransferData == nullptr)
  7037. {
  7038. return;
  7039. }
  7040. class AutoCleanup
  7041. {
  7042. EntryPointInfo *entryPointInfo;
  7043. public:
  7044. AutoCleanup(EntryPointInfo *entryPointInfo) : entryPointInfo(entryPointInfo)
  7045. {
  7046. }
  7047. void Done()
  7048. {
  7049. entryPointInfo = nullptr;
  7050. }
  7051. ~AutoCleanup()
  7052. {
  7053. if (entryPointInfo)
  7054. {
  7055. entryPointInfo->OnNativeCodeInstallFailure();
  7056. }
  7057. }
  7058. } autoCleanup(this);
  7059. ScriptContext* scriptContext = GetScriptContext();
  7060. if (jitTransferData->GetIsReady())
  7061. {
  7062. PinTypeRefs(scriptContext);
  7063. InstallGuards(scriptContext);
  7064. }
  7065. FreeJitTransferData();
  7066. autoCleanup.Done();
  7067. }
  7068. void EntryPointInfo::OnNativeCodeInstallFailure()
  7069. {
  7070. // If more data is transferred from the background thread to the main thread in ProcessJitTransferData,
  7071. // corresponding fields on the entryPointInfo should be rolled back here.
  7072. this->nativeEntryPointData->ClearTypeRefsAndGuards(GetScriptContext());
  7073. this->ResetOnNativeCodeInstallFailure();
  7074. }
  7075. #ifdef FIELD_ACCESS_STATS
  7076. FieldAccessStats* EntryPointInfo::EnsureFieldAccessStats(Recycler* recycler)
  7077. {
  7078. if (this->fieldAccessStats == nullptr)
  7079. {
  7080. this->fieldAccessStats = RecyclerNew(recycler, FieldAccessStats);
  7081. }
  7082. return this->fieldAccessStats;
  7083. }
  7084. #endif
  7085. void EntryPointInfo::PinTypeRefs(ScriptContext* scriptContext)
  7086. {
  7087. NativeEntryPointData * nativeEntryPointData = this->GetNativeEntryPointData();
  7088. JitTransferData * jitTransferData = nativeEntryPointData->GetJitTransferData();
  7089. Assert(jitTransferData != nullptr && jitTransferData->GetIsReady());
  7090. Recycler* recycler = scriptContext->GetRecycler();
  7091. if (jitTransferData->GetRuntimeTypeRefs() != nullptr)
  7092. {
  7093. // Copy pinned types from a heap allocated array created on the background thread
  7094. // to a recycler allocated array which will live as long as this EntryPointInfo.
  7095. // The original heap allocated array will be freed at the end of NativeCodeGenerator::CheckCodeGenDone
  7096. void** jitPinnedTypeRefs = jitTransferData->GetRuntimeTypeRefs();
  7097. size_t jitPinnedTypeRefCount = jitTransferData->GetRuntimeTypeRefCount();
  7098. nativeEntryPointData->PinTypeRefs(recycler, jitPinnedTypeRefCount, jitPinnedTypeRefs);
  7099. }
  7100. }
  7101. void EntryPointInfo::InstallGuards(ScriptContext* scriptContext)
  7102. {
  7103. NativeEntryPointData * nativeEntryPointData = this->GetNativeEntryPointData();
  7104. JitTransferData * jitTransferData = this->GetNativeEntryPointData()->GetJitTransferData();
  7105. Assert(jitTransferData != nullptr && jitTransferData->GetIsReady());
  7106. for (int i = 0; i < jitTransferData->lazyBailoutPropertyCount; i++)
  7107. {
  7108. Assert(jitTransferData->lazyBailoutProperties != nullptr);
  7109. Js::PropertyId propertyId = jitTransferData->lazyBailoutProperties[i];
  7110. Js::PropertyGuard* sharedPropertyGuard = nullptr;
  7111. bool hasSharedPropertyGuard = nativeEntryPointData->TryGetSharedPropertyGuard(propertyId, sharedPropertyGuard);
  7112. Assert(hasSharedPropertyGuard);
  7113. bool isValid = hasSharedPropertyGuard ? sharedPropertyGuard->IsValid() : false;
  7114. if (isValid)
  7115. {
  7116. scriptContext->GetThreadContext()->RegisterLazyBailout(propertyId, this);
  7117. }
  7118. else
  7119. {
  7120. OUTPUT_TRACE2(Js::LazyBailoutPhase, this->GetFunctionBody(), _u("Lazy bailout - Invalidation due to property: %s \n"), scriptContext->GetPropertyName(propertyId)->GetBuffer());
  7121. this->Invalidate(true);
  7122. return;
  7123. }
  7124. }
  7125. // in-proc JIT
  7126. if (jitTransferData->equivalentTypeGuardCount > 0)
  7127. {
  7128. Assert(jitTransferData->equivalentTypeGuardOffsets == nullptr);
  7129. Assert(jitTransferData->equivalentTypeGuards != nullptr);
  7130. int guardCount = jitTransferData->equivalentTypeGuardCount;
  7131. JitEquivalentTypeGuard** guards = jitTransferData->equivalentTypeGuards;
  7132. EquivalentTypeCache * cache = nativeEntryPointData->EnsureEquivalentTypeCache(guardCount, scriptContext, this);
  7133. for (JitEquivalentTypeGuard** guard = guards; guard < guards + guardCount; guard++)
  7134. {
  7135. EquivalentTypeCache* oldCache = (*guard)->GetCache();
  7136. // Copy the contents of the heap-allocated cache to the recycler-allocated version to make sure the types are
  7137. // kept alive. Allow the properties pointer to refer to the heap-allocated arrays. It will stay alive as long
  7138. // as the entry point is alive, and property entries contain no pointers to other recycler allocated objects.
  7139. (*cache) = (*oldCache);
  7140. // Set the recycler-allocated cache on the (heap-allocated) guard.
  7141. (*guard)->SetCache(cache);
  7142. for (uint i = 0; i < EQUIVALENT_TYPE_CACHE_SIZE; i++)
  7143. {
  7144. if((*cache).types[i] != nullptr)
  7145. {
  7146. (*cache).types[i]->SetHasBeenCached();
  7147. }
  7148. else
  7149. {
  7150. #ifdef DEBUG
  7151. for (uint __i = i; __i < EQUIVALENT_TYPE_CACHE_SIZE; __i++)
  7152. { Assert((*cache).types[__i] == nullptr); }
  7153. #endif
  7154. break; // type array must be shrinked.
  7155. }
  7156. }
  7157. cache++;
  7158. }
  7159. }
  7160. #if ENABLE_OOP_NATIVE_CODEGEN
  7161. if (jitTransferData->equivalentTypeGuardOffsets)
  7162. {
  7163. // InstallGuards
  7164. int guardCount = jitTransferData->equivalentTypeGuardOffsets->count;
  7165. EquivalentTypeCache* cache = this->nativeEntryPointData->EnsureEquivalentTypeCache(guardCount, scriptContext, this);
  7166. char * nativeDataBuffer = this->GetOOPNativeEntryPointData()->GetNativeDataBuffer();
  7167. for (int i = 0; i < guardCount; i++)
  7168. {
  7169. auto& cacheIDL = jitTransferData->equivalentTypeGuardOffsets->guards[i].cache;
  7170. auto guardOffset = jitTransferData->equivalentTypeGuardOffsets->guards[i].offset;
  7171. JitEquivalentTypeGuard* guard = (JitEquivalentTypeGuard*)(nativeDataBuffer + guardOffset);
  7172. cache[i].guard = guard;
  7173. cache[i].hasFixedValue = cacheIDL.hasFixedValue != 0;
  7174. cache[i].isLoadedFromProto = cacheIDL.isLoadedFromProto != 0;
  7175. cache[i].nextEvictionVictim = cacheIDL.nextEvictionVictim;
  7176. cache[i].record.propertyCount = cacheIDL.record.propertyCount;
  7177. cache[i].record.properties = (EquivalentPropertyEntry*)(nativeDataBuffer + cacheIDL.record.propertyOffset);
  7178. for (int j = 0; j < EQUIVALENT_TYPE_CACHE_SIZE; j++)
  7179. {
  7180. cache[i].types[j] = (Js::Type*)cacheIDL.types[j];
  7181. }
  7182. guard->SetCache(&cache[i]);
  7183. }
  7184. }
  7185. // OOP JIT
  7186. if (jitTransferData->typeGuardTransferData.entries != nullptr)
  7187. {
  7188. int propertyGuardCount = jitTransferData->typeGuardTransferData.propertyGuardCount;
  7189. Field(FakePropertyGuardWeakReference*) * propertyGuardWeakRefs = this->nativeEntryPointData->EnsurePropertyGuardWeakRefs(propertyGuardCount, scriptContext->GetRecycler());
  7190. ThreadContext* threadContext = scriptContext->GetThreadContext();
  7191. auto next = &jitTransferData->typeGuardTransferData.entries;
  7192. while (*next)
  7193. {
  7194. Js::PropertyId propertyId = (*next)->propId;
  7195. Js::PropertyGuard* sharedPropertyGuard = nullptr;
  7196. // We use the shared guard created during work item creation to ensure that the condition we assumed didn't change while
  7197. // we were JIT-ing. If we don't have a shared property guard for this property then we must not need to protect it,
  7198. // because it exists on the instance. Unfortunately, this means that if we have a bug and fail to create a shared
  7199. // guard for some property during work item creation, we won't find out about it here.
  7200. bool isNeeded = nativeEntryPointData->TryGetSharedPropertyGuard(propertyId, sharedPropertyGuard);
  7201. bool isValid = isNeeded ? sharedPropertyGuard->IsValid() : false;
  7202. if (isNeeded)
  7203. {
  7204. char * nativeDataBuffer = this->GetOOPNativeEntryPointData()->GetNativeDataBuffer();
  7205. for (unsigned int i = 0; i < (*next)->guardsCount; i++)
  7206. {
  7207. Js::JitIndexedPropertyGuard* guard = (Js::JitIndexedPropertyGuard*)(nativeDataBuffer + (*next)->guardOffsets[i]);
  7208. int guardIndex = guard->GetIndex();
  7209. Assert(guardIndex >= 0 && guardIndex < propertyGuardCount);
  7210. // We use the shared guard here to make sure the conditions we assumed didn't change while we were JIT-ing.
  7211. // If they did, we proactively invalidate the guard here, so that we bail out if we try to call this code.
  7212. if (isValid)
  7213. {
  7214. auto propertyGuardWeakRef = propertyGuardWeakRefs[guardIndex];
  7215. if (propertyGuardWeakRef == nullptr)
  7216. {
  7217. propertyGuardWeakRef = Js::FakePropertyGuardWeakReference::New(scriptContext->GetRecycler(), guard);
  7218. propertyGuardWeakRefs[guardIndex] = propertyGuardWeakRef;
  7219. }
  7220. Assert(propertyGuardWeakRef->Get() == guard);
  7221. threadContext->RegisterUniquePropertyGuard(propertyId, propertyGuardWeakRef);
  7222. }
  7223. else
  7224. {
  7225. guard->Invalidate();
  7226. }
  7227. }
  7228. }
  7229. *next = (*next)->next;
  7230. }
  7231. }
  7232. #endif
  7233. // in-proc JIT
  7234. // The propertyGuardsByPropertyId structure is temporary and serves only to register the type guards for the correct
  7235. // properties. If we've done code gen for this EntryPointInfo, typePropertyGuardsByPropertyId will have been used and nulled out.
  7236. if (jitTransferData->propertyGuardsByPropertyId != nullptr)
  7237. {
  7238. int propertyGuardCount = jitTransferData->propertyGuardCount;
  7239. Field(FakePropertyGuardWeakReference*) * propertyGuardWeakRefs = nativeEntryPointData->EnsurePropertyGuardWeakRefs(propertyGuardCount, scriptContext->GetRecycler());
  7240. ThreadContext* threadContext = scriptContext->GetThreadContext();
  7241. Js::TypeGuardTransferEntry* entry = jitTransferData->propertyGuardsByPropertyId;
  7242. while (entry->propertyId != Js::Constants::NoProperty)
  7243. {
  7244. Js::PropertyId propertyId = entry->propertyId;
  7245. Js::PropertyGuard* sharedPropertyGuard = nullptr;
  7246. // We use the shared guard created during work item creation to ensure that the condition we assumed didn't change while
  7247. // we were JIT-ing. If we don't have a shared property guard for this property then we must not need to protect it,
  7248. // because it exists on the instance. Unfortunately, this means that if we have a bug and fail to create a shared
  7249. // guard for some property during work item creation, we won't find out about it here.
  7250. bool isNeeded = nativeEntryPointData->TryGetSharedPropertyGuard(propertyId, sharedPropertyGuard);
  7251. bool isValid = isNeeded ? sharedPropertyGuard->IsValid() : false;
  7252. int entryGuardIndex = 0;
  7253. while (entry->guards[entryGuardIndex] != nullptr)
  7254. {
  7255. if (isNeeded)
  7256. {
  7257. Js::JitIndexedPropertyGuard* guard = entry->guards[entryGuardIndex];
  7258. int guardIndex = guard->GetIndex();
  7259. Assert(guardIndex >= 0 && guardIndex < propertyGuardCount);
  7260. // We use the shared guard here to make sure the conditions we assumed didn't change while we were JIT-ing.
  7261. // If they did, we proactively invalidate the guard here, so that we bail out if we try to call this code.
  7262. if (isValid)
  7263. {
  7264. auto propertyGuardWeakRef = propertyGuardWeakRefs[guardIndex];
  7265. if (propertyGuardWeakRef == nullptr)
  7266. {
  7267. propertyGuardWeakRef = Js::FakePropertyGuardWeakReference::New(scriptContext->GetRecycler(), guard);
  7268. propertyGuardWeakRefs[guardIndex] = propertyGuardWeakRef;
  7269. }
  7270. Assert(propertyGuardWeakRef->Get() == guard);
  7271. threadContext->RegisterUniquePropertyGuard(propertyId, propertyGuardWeakRef);
  7272. }
  7273. else
  7274. {
  7275. guard->Invalidate();
  7276. }
  7277. }
  7278. entryGuardIndex++;
  7279. }
  7280. entry = reinterpret_cast<Js::TypeGuardTransferEntry*>(&entry->guards[++entryGuardIndex]);
  7281. }
  7282. }
  7283. // The ctorCacheGuardsByPropertyId structure is temporary and serves only to register the constructor cache guards for the correct
  7284. // properties. If we've done code gen for this EntryPointInfo, ctorCacheGuardsByPropertyId will have been used and nulled out.
  7285. // Unlike type property guards, constructor cache guards use the live constructor caches associated with function objects. These are
  7286. // recycler allocated and are kept alive by the constructorCaches field, where they were inserted during work item creation.
  7287. // OOP JIT
  7288. if (jitTransferData->ctorCacheTransferData.entries != nullptr)
  7289. {
  7290. ThreadContext* threadContext = scriptContext->GetThreadContext();
  7291. CtorCacheTransferEntryIDL ** entries = jitTransferData->ctorCacheTransferData.entries;
  7292. for (uint i = 0; i < jitTransferData->ctorCacheTransferData.ctorCachesCount; ++i)
  7293. {
  7294. Js::PropertyId propertyId = entries[i]->propId;
  7295. Js::PropertyGuard* sharedPropertyGuard = nullptr;
  7296. // We use the shared guard created during work item creation to ensure that the condition we assumed didn't change while
  7297. // we were JIT-ing. If we don't have a shared property guard for this property then we must not need to protect it,
  7298. // because it exists on the instance. Unfortunately, this means that if we have a bug and fail to create a shared
  7299. // guard for some property during work item creation, we won't find out about it here.
  7300. bool isNeeded = nativeEntryPointData->TryGetSharedPropertyGuard(propertyId, sharedPropertyGuard);
  7301. bool isValid = isNeeded ? sharedPropertyGuard->IsValid() : false;
  7302. if (isNeeded)
  7303. {
  7304. for (uint j = 0; j < entries[i]->cacheCount; ++j)
  7305. {
  7306. Js::ConstructorCache* cache = (Js::ConstructorCache*)(entries[i]->caches[j]);
  7307. // We use the shared cache here to make sure the conditions we assumed didn't change while we were JIT-ing.
  7308. // If they did, we proactively invalidate the cache here, so that we bail out if we try to call this code.
  7309. if (isValid)
  7310. {
  7311. threadContext->RegisterConstructorCache(propertyId, cache);
  7312. }
  7313. else
  7314. {
  7315. cache->InvalidateAsGuard();
  7316. }
  7317. }
  7318. }
  7319. }
  7320. }
  7321. if (jitTransferData->ctorCacheGuardsByPropertyId != nullptr)
  7322. {
  7323. ThreadContext* threadContext = scriptContext->GetThreadContext();
  7324. Js::CtorCacheGuardTransferEntry* entry = jitTransferData->ctorCacheGuardsByPropertyId;
  7325. while (entry->propertyId != Js::Constants::NoProperty)
  7326. {
  7327. Js::PropertyId propertyId = entry->propertyId;
  7328. Js::PropertyGuard* sharedPropertyGuard = nullptr;
  7329. // We use the shared guard created during work item creation to ensure that the condition we assumed didn't change while
  7330. // we were JIT-ing. If we don't have a shared property guard for this property then we must not need to protect it,
  7331. // because it exists on the instance. Unfortunately, this means that if we have a bug and fail to create a shared
  7332. // guard for some property during work item creation, we won't find out about it here.
  7333. bool isNeeded = nativeEntryPointData->TryGetSharedPropertyGuard(propertyId, sharedPropertyGuard);
  7334. bool isValid = isNeeded ? sharedPropertyGuard->IsValid() : false;
  7335. int entryCacheIndex = 0;
  7336. while (entry->caches[entryCacheIndex] != 0)
  7337. {
  7338. if (isNeeded)
  7339. {
  7340. Js::ConstructorCache* cache = (Js::ConstructorCache*)(entry->caches[entryCacheIndex]);
  7341. // We use the shared cache here to make sure the conditions we assumed didn't change while we were JIT-ing.
  7342. // If they did, we proactively invalidate the cache here, so that we bail out if we try to call this code.
  7343. if (isValid)
  7344. {
  7345. threadContext->RegisterConstructorCache(propertyId, cache);
  7346. }
  7347. else
  7348. {
  7349. cache->InvalidateAsGuard();
  7350. }
  7351. }
  7352. entryCacheIndex++;
  7353. }
  7354. entry = reinterpret_cast<Js::CtorCacheGuardTransferEntry*>(&entry->caches[++entryCacheIndex]);
  7355. }
  7356. }
  7357. if (PHASE_ON(Js::FailNativeCodeInstallPhase, this->GetFunctionBody()))
  7358. {
  7359. Js::Throw::OutOfMemory();
  7360. }
  7361. }
  7362. InlineeFrameRecord* EntryPointInfo::FindInlineeFrame(void* returnAddress)
  7363. {
  7364. #if ENABLE_OOP_NATIVE_CODEGEN
  7365. if (JITManager::GetJITManager()->IsOOPJITEnabled()) // OOP JIT
  7366. {
  7367. OOPNativeEntryPointData * oopNativeEntryPointData = this->GetOOPNativeEntryPointData();
  7368. char * nativeDataBuffer = oopNativeEntryPointData->GetNativeDataBuffer();
  7369. NativeOffsetInlineeFrameRecordOffset* offsets = (NativeOffsetInlineeFrameRecordOffset*)(nativeDataBuffer + oopNativeEntryPointData->GetInlineeFrameOffsetArrayOffset());
  7370. size_t offset = (size_t)((BYTE*)returnAddress - (BYTE*)this->GetNativeAddress());
  7371. uint inlineeFrameOffsetArrayCount = oopNativeEntryPointData->GetInlineeFrameOffsetArrayCount();
  7372. if (inlineeFrameOffsetArrayCount == 0)
  7373. {
  7374. return nullptr;
  7375. }
  7376. uint fromIndex = 0;
  7377. uint toIndex = inlineeFrameOffsetArrayCount - 1;
  7378. while (fromIndex <= toIndex)
  7379. {
  7380. uint midIndex = fromIndex + (toIndex - fromIndex) / 2;
  7381. auto item = offsets[midIndex];
  7382. if (item.offset >= offset)
  7383. {
  7384. if (midIndex == 0 || (midIndex > 0 && offsets[midIndex - 1].offset < offset))
  7385. {
  7386. if (offsets[midIndex].recordOffset == NativeOffsetInlineeFrameRecordOffset::InvalidRecordOffset)
  7387. {
  7388. return nullptr;
  7389. }
  7390. else
  7391. {
  7392. return (InlineeFrameRecord*)(nativeDataBuffer + offsets[midIndex].recordOffset);
  7393. }
  7394. }
  7395. else
  7396. {
  7397. toIndex = midIndex - 1;
  7398. }
  7399. }
  7400. else
  7401. {
  7402. fromIndex = midIndex + 1;
  7403. }
  7404. }
  7405. return nullptr;
  7406. }
  7407. else
  7408. #endif
  7409. // in-proc JIT
  7410. {
  7411. InlineeFrameMap * inlineeFrameMap = this->GetInProcNativeEntryPointData()->GetInlineeFrameMap();
  7412. if (inlineeFrameMap == nullptr)
  7413. {
  7414. return nullptr;
  7415. }
  7416. size_t offset = (size_t)((BYTE*)returnAddress - (BYTE*)this->GetNativeAddress());
  7417. int index = inlineeFrameMap->BinarySearch([=](const NativeOffsetInlineeFramePair& pair, int index) {
  7418. if (pair.offset >= offset)
  7419. {
  7420. if (index == 0 || (index > 0 && inlineeFrameMap->Item(index - 1).offset < offset))
  7421. {
  7422. return 0;
  7423. }
  7424. else
  7425. {
  7426. return 1;
  7427. }
  7428. }
  7429. return -1;
  7430. });
  7431. if (index == -1)
  7432. {
  7433. return nullptr;
  7434. }
  7435. return inlineeFrameMap->Item(index).record;
  7436. }
  7437. }
  7438. void EntryPointInfo::DoLazyBailout(BYTE** addressOfInstructionPointer, Js::FunctionBody* functionBody, const PropertyRecord* propertyRecord)
  7439. {
  7440. BYTE* instructionPointer = *addressOfInstructionPointer;
  7441. NativeEntryPointData * nativeEntryPointData = this->GetNativeEntryPointData();
  7442. Js::JavascriptMethod nativeAddress = nativeEntryPointData->GetNativeAddress();
  7443. ptrdiff_t codeSize = nativeEntryPointData->GetCodeSize();
  7444. Assert(instructionPointer > (BYTE*)nativeAddress && instructionPointer < ((BYTE*)nativeAddress + codeSize));
  7445. size_t offset = instructionPointer - (BYTE*)nativeAddress;
  7446. BailOutRecordMap * bailoutRecordMap = this->GetInProcNativeEntryPointData()->GetBailOutRecordMap();
  7447. int found = bailoutRecordMap->BinarySearch([=](const LazyBailOutRecord& record, int index)
  7448. {
  7449. // find the closest entry which is greater than the current offset.
  7450. if (record.offset >= offset)
  7451. {
  7452. if (index == 0 || (index > 0 && bailoutRecordMap->Item(index - 1).offset < offset))
  7453. {
  7454. return 0;
  7455. }
  7456. else
  7457. {
  7458. return 1;
  7459. }
  7460. }
  7461. return -1;
  7462. });
  7463. if (found != -1)
  7464. {
  7465. LazyBailOutRecord& record = bailoutRecordMap->Item(found);
  7466. *addressOfInstructionPointer = record.instructionPointer;
  7467. record.SetBailOutKind();
  7468. if (PHASE_TRACE1(Js::LazyBailoutPhase))
  7469. {
  7470. Output::Print(_u("On stack lazy bailout. Property: %s Old IP: 0x%x New IP: 0x%x "), propertyRecord->GetBuffer(), instructionPointer, record.instructionPointer);
  7471. #if DBG
  7472. record.Dump(functionBody);
  7473. #endif
  7474. Output::Print(_u("\n"));
  7475. }
  7476. }
  7477. else
  7478. {
  7479. AssertMsg(false, "Lazy Bailout address mapping missing");
  7480. }
  7481. }
  7482. void EntryPointInfo::FreeJitTransferData()
  7483. {
  7484. if (this->HasNativeEntryPointData())
  7485. {
  7486. this->GetNativeEntryPointData()->FreeJitTransferData();;
  7487. }
  7488. }
  7489. bool EntryPointInfo::ClearEquivalentTypeCaches()
  7490. {
  7491. return this->GetNativeEntryPointData()->ClearEquivalentTypeCaches(GetScriptContext()->GetRecycler());
  7492. }
  7493. bool EquivalentTypeCache::ClearUnusedTypes(Recycler *recycler)
  7494. {
  7495. bool isAnyTypeLive = false;
  7496. Assert(this->guard);
  7497. if (this->guard->IsValid())
  7498. {
  7499. if (this->guard->IsPoly())
  7500. {
  7501. JitPolyEquivalentTypeGuard * polyGuard = this->guard->AsPolyTypeCheckGuard();
  7502. for (uint8 i = 0; i < polyGuard->GetSize(); i++)
  7503. {
  7504. intptr_t value = polyGuard->GetPolyValue(i);
  7505. if (value != PropertyGuard::GuardValue::Uninitialized && value != PropertyGuard::GuardValue::Invalidated_DuringSweep)
  7506. {
  7507. Type *type = reinterpret_cast<Type*>(value);
  7508. if (!recycler->IsObjectMarked(type))
  7509. {
  7510. polyGuard->InvalidateDuringSweep(i);
  7511. }
  7512. else
  7513. {
  7514. isAnyTypeLive = true;
  7515. }
  7516. }
  7517. }
  7518. }
  7519. else
  7520. {
  7521. Type *type = reinterpret_cast<Type*>(this->guard->GetValue());
  7522. if (!recycler->IsObjectMarked(type))
  7523. {
  7524. this->guard->InvalidateDuringSweep();
  7525. }
  7526. else
  7527. {
  7528. isAnyTypeLive = true;
  7529. }
  7530. }
  7531. }
  7532. uint16 nonNullIndex = 0;
  7533. #if DBG
  7534. bool isGuardValuePresent = false;
  7535. #endif
  7536. for (int i = 0; i < EQUIVALENT_TYPE_CACHE_SIZE; i++)
  7537. {
  7538. Type *type = this->types[i];
  7539. if (type != nullptr)
  7540. {
  7541. this->types[i] = nullptr;
  7542. if (recycler->IsObjectMarked(type))
  7543. {
  7544. // compact the types array by moving non-null types
  7545. // to the beginning.
  7546. this->types[nonNullIndex++] = type;
  7547. #if DBG
  7548. if (guard->IsPoly())
  7549. {
  7550. isGuardValuePresent = true;
  7551. }
  7552. else if (this->guard->GetValue() == reinterpret_cast<intptr_t>(type))
  7553. {
  7554. isGuardValuePresent = true;
  7555. }
  7556. #endif
  7557. }
  7558. }
  7559. else
  7560. {
  7561. #ifdef DEBUG
  7562. for (int __i = i; __i < EQUIVALENT_TYPE_CACHE_SIZE; __i++)
  7563. { Assert(this->types[__i] == nullptr); }
  7564. #endif
  7565. break; // array must be shrinked already
  7566. }
  7567. }
  7568. if (nonNullIndex > 0)
  7569. {
  7570. isAnyTypeLive = true;
  7571. }
  7572. else if (guard->IsPoly())
  7573. {
  7574. if (!isAnyTypeLive)
  7575. {
  7576. guard->Invalidate();
  7577. }
  7578. }
  7579. else if (guard->IsInvalidatedDuringSweep())
  7580. {
  7581. // just mark this as actual invalidated since there are no types
  7582. // present
  7583. guard->Invalidate();
  7584. }
  7585. // verify if guard value is valid, it is present in one of the types
  7586. AssertMsg(!this->guard->IsValid() || isGuardValuePresent || nonNullIndex == 0,
  7587. "After ClearUnusedTypes, valid guard value should be one of the cached equivalent types.");
  7588. return isAnyTypeLive;
  7589. }
  7590. #endif
  7591. #if ENABLE_ENTRYPOINT_CLEANUP_TRACE
  7592. #if ENABLE_DEBUG_STACK_BACK_TRACE
  7593. void EntryPointInfo::CaptureCleanupStackTrace()
  7594. {
  7595. if (this->cleanupStack != nullptr)
  7596. {
  7597. this->cleanupStack->Delete(&NoCheckHeapAllocator::Instance);
  7598. this->cleanupStack = nullptr;
  7599. }
  7600. this->cleanupStack = StackBackTrace::Capture(&NoCheckHeapAllocator::Instance);
  7601. }
  7602. #endif
  7603. #endif
  7604. void EntryPointInfo::Finalize(bool isShutdown)
  7605. {
  7606. __super::Finalize(isShutdown);
  7607. if (!isShutdown)
  7608. {
  7609. ReleasePendingWorkItem();
  7610. }
  7611. #if ENABLE_ENTRYPOINT_CLEANUP_TRACE
  7612. this->SetCleanupReason(CleanupReason::CleanUpForFinalize);
  7613. #endif
  7614. this->Cleanup(isShutdown, false);
  7615. #if ENABLE_ENTRYPOINT_CLEANUP_TRACE
  7616. #if ENABLE_DEBUG_STACK_BACK_TRACE
  7617. if (this->cleanupStack != nullptr)
  7618. {
  7619. this->cleanupStack->Delete(&NoCheckHeapAllocator::Instance);
  7620. this->cleanupStack = nullptr;
  7621. }
  7622. #endif
  7623. #endif
  7624. this->library = nullptr;
  7625. }
  7626. void EntryPointInfo::Cleanup(bool isShutdown, bool captureCleanupStack)
  7627. {
  7628. if (this->GetState() != CleanedUp)
  7629. {
  7630. #if ENABLE_NATIVE_CODEGEN
  7631. this->OnCleanup(isShutdown);
  7632. if (this->nativeEntryPointData)
  7633. {
  7634. this->nativeEntryPointData->Cleanup(GetScriptContext(), isShutdown, false);
  7635. this->nativeEntryPointData = nullptr;
  7636. }
  7637. #endif // ENABLE_NATIVE_CODEGEN
  7638. // This is how we set the CleanedUp state
  7639. this->workItem = nullptr;
  7640. this->library = nullptr;
  7641. this->state = CleanedUp;
  7642. #if ENABLE_ENTRYPOINT_CLEANUP_TRACE
  7643. #if ENABLE_DEBUG_CONFIG_OPTIONS
  7644. #if !DBG
  7645. captureCleanupStack = captureCleanupStack && Js::Configuration::Global.flags.FreTestDiagMode;
  7646. #endif
  7647. #if ENABLE_DEBUG_STACK_BACK_TRACE
  7648. if (captureCleanupStack)
  7649. {
  7650. this->CaptureCleanupStackTrace();
  7651. }
  7652. #endif
  7653. #endif
  7654. #endif
  7655. #if DEBUG
  7656. const unsigned char* rpcData = serializedRpcData;
  7657. HeapDeleteArray(serializedRpcDataSize, rpcData);
  7658. serializedRpcDataSize = 0;
  7659. serializedRpcData = nullptr;
  7660. #endif
  7661. }
  7662. }
  7663. void EntryPointInfo::Reset(bool resetStateToNotScheduled)
  7664. {
  7665. Assert(this->GetState() != CleanedUp);
  7666. this->workItem = nullptr;
  7667. #if ENABLE_NATIVE_CODEGEN
  7668. if (this->nativeEntryPointData)
  7669. {
  7670. this->nativeEntryPointData->Cleanup(GetScriptContext(), false, true);
  7671. this->nativeEntryPointData = nullptr;
  7672. }
  7673. #endif
  7674. // Set the state to NotScheduled only if the call to Reset is not because of JIT cap being reached
  7675. if (resetStateToNotScheduled)
  7676. {
  7677. this->state = NotScheduled;
  7678. }
  7679. }
  7680. #if ENABLE_NATIVE_CODEGEN
  7681. // This function needs review when we enable lazy bailouts-
  7682. // Is calling Reset enough? Does Reset sufficiently resets the state of the entryPointInfo?
  7683. void EntryPointInfo::ResetOnLazyBailoutFailure()
  7684. {
  7685. Assert(PHASE_ON1(Js::LazyBailoutPhase));
  7686. // Reset the entry point upon a lazy bailout.
  7687. this->Reset(true);
  7688. this->jsMethod = nullptr;
  7689. }
  7690. #endif
  7691. #ifdef ASMJS_PLAT
  7692. void EntryPointInfo::SetIsTJMode(bool value)
  7693. {
  7694. Assert(this->GetIsAsmJSFunction());
  7695. mIsTemplatizedJitMode = value;
  7696. }
  7697. bool EntryPointInfo::GetIsTJMode()const
  7698. {
  7699. return mIsTemplatizedJitMode;
  7700. };
  7701. // set code size, used by TJ to set the code size
  7702. void EntryPointInfo::SetTJCodeSize(ptrdiff_t size)
  7703. {
  7704. Assert(isAsmJsFunction);
  7705. // TODO: We don't need the whole NativeEntryPointData to just hold just the code and size for TJ mode
  7706. this->EnsureNativeEntryPointData()->SetTJCodeSize(size);
  7707. }
  7708. void EntryPointInfo::SetTJNativeAddress(Js::JavascriptMethod address, void * validationCookie)
  7709. {
  7710. Assert(isAsmJsFunction);
  7711. // TODO: We don't need the whole NativeEntryPointData to just hold just the code and size for TJ mode
  7712. this->EnsureNativeEntryPointData()->SetTJNativeAddress(address, validationCookie);
  7713. }
  7714. #endif
  7715. //End AsmJS Support
  7716. #ifdef PERF_COUNTERS
  7717. void FunctionEntryPointInfo::OnRecorded()
  7718. {
  7719. PERF_COUNTER_ADD(Code, TotalNativeCodeSize, GetCodeSize());
  7720. PERF_COUNTER_ADD(Code, FunctionNativeCodeSize, GetCodeSize());
  7721. PERF_COUNTER_ADD(Code, DynamicNativeCodeSize, GetCodeSize());
  7722. }
  7723. #endif
  7724. FunctionEntryPointInfo::FunctionEntryPointInfo(FunctionProxy * functionProxy, Js::JavascriptMethod method, ThreadContext* context) :
  7725. EntryPointInfo(method, functionProxy->GetScriptContext()->GetLibrary(), context),
  7726. localVarSlotsOffset(Js::Constants::InvalidOffset),
  7727. localVarChangedOffset(Js::Constants::InvalidOffset),
  7728. callsCount(0),
  7729. jitMode(ExecutionMode::Interpreter),
  7730. functionProxy(functionProxy),
  7731. nextEntryPoint(nullptr)
  7732. {
  7733. }
  7734. #if ENABLE_NATIVE_CODEGEN
  7735. ExecutionMode FunctionEntryPointInfo::GetJitMode() const
  7736. {
  7737. return jitMode;
  7738. }
  7739. void FunctionEntryPointInfo::SetJitMode(const ExecutionMode jitMode)
  7740. {
  7741. Assert(jitMode == ExecutionMode::SimpleJit || jitMode == ExecutionMode::FullJit);
  7742. this->jitMode = jitMode;
  7743. }
  7744. #endif
  7745. bool FunctionEntryPointInfo::ExecutedSinceCallCountCollection() const
  7746. {
  7747. return this->callsCount != this->lastCallsCount;
  7748. }
  7749. void FunctionEntryPointInfo::CollectCallCounts()
  7750. {
  7751. this->lastCallsCount = this->callsCount;
  7752. }
  7753. void FunctionEntryPointInfo::ReleasePendingWorkItem()
  7754. {
  7755. // Do this outside of Cleanup since cleanup can be called from the background thread
  7756. // We remove any work items corresponding to the function body being reclaimed
  7757. // so that the background thread doesn't try to use them. ScriptContext != null => this
  7758. // is a function entry point
  7759. // In general this is not needed for loop bodies since loop bodies aren't in the low priority
  7760. // queue, they should be jitted before the entry point is finalized
  7761. if (!this->IsNotScheduled() && !this->IsCleanedUp())
  7762. {
  7763. #if defined(_M_ARM32_OR_ARM64)
  7764. // On ARM machines, order of writes is not guaranteed while reading data from another processor
  7765. // So we need to have a memory barrier here in order to make sure that the work item is consistent
  7766. MemoryBarrier();
  7767. #endif
  7768. CodeGenWorkItem* workItem = this->GetWorkItem();
  7769. if (workItem != nullptr)
  7770. {
  7771. Assert(this->library != nullptr);
  7772. #if ENABLE_NATIVE_CODEGEN
  7773. TryReleaseNonHiPriWorkItem(this->library->GetScriptContext(), workItem);
  7774. #endif
  7775. }
  7776. }
  7777. }
  7778. FunctionBody *FunctionEntryPointInfo::GetFunctionBody() const
  7779. {
  7780. return functionProxy->GetFunctionBody();
  7781. }
  7782. #if ENABLE_NATIVE_CODEGEN
  7783. void EntryPointInfo::CleanupNativeCode(ScriptContext * scriptContext)
  7784. {
  7785. if (this->jsMethod == this->GetNativeEntrypoint())
  7786. {
  7787. #if DBG
  7788. // tag the jsMethod in case the native address is reused in recycler and create a false positive
  7789. // not checking validationCookie because this can happen while debugger attaching, native address
  7790. // are batch freed through deleting NativeCodeGenerator
  7791. this->jsMethod = (Js::JavascriptMethod)((intptr_t)this->jsMethod | 1);
  7792. #else
  7793. this->jsMethod = nullptr;
  7794. #endif
  7795. }
  7796. }
  7797. #endif
  7798. void FunctionEntryPointInfo::OnCleanup(bool isShutdown)
  7799. {
  7800. if (this->IsCodeGenDone())
  7801. {
  7802. Assert(this->functionProxy->GetFunctionInfo()->HasBody());
  7803. #if ENABLE_NATIVE_CODEGEN
  7804. if (this->IsNativeEntryPointProcessed())
  7805. {
  7806. JS_ETW(EtwTrace::LogMethodNativeUnloadEvent(this->functionProxy->GetFunctionBody(), this));
  7807. }
  7808. #endif
  7809. FunctionBody* functionBody = this->functionProxy->GetFunctionBody();
  7810. #ifdef ASMJS_PLAT
  7811. if (this->GetIsTJMode())
  7812. {
  7813. // release LoopHeaders here if the entrypointInfo is TJ
  7814. this->GetFunctionBody()->ReleaseLoopHeaders();
  7815. }
  7816. #endif
  7817. if(functionBody->GetSimpleJitEntryPointInfo() == this)
  7818. {
  7819. functionBody->SetSimpleJitEntryPointInfo(nullptr);
  7820. }
  7821. #if ENABLE_NATIVE_CODEGEN
  7822. CleanupNativeCode(this->functionProxy->GetScriptContext());
  7823. #endif
  7824. }
  7825. this->functionProxy = nullptr;
  7826. }
  7827. #if ENABLE_NATIVE_CODEGEN
  7828. void FunctionEntryPointInfo::ResetOnNativeCodeInstallFailure()
  7829. {
  7830. this->functionProxy->MapFunctionObjectTypes([&](ScriptFunctionType* functionType)
  7831. {
  7832. Assert(functionType->GetTypeId() == TypeIds_Function);
  7833. if (functionType->GetEntryPointInfo() == this)
  7834. {
  7835. if (!this->GetIsAsmJSFunction())
  7836. {
  7837. functionType->SetEntryPoint(GetCheckCodeGenThunk());
  7838. }
  7839. #ifdef ASMJS_PLAT
  7840. else
  7841. {
  7842. functionType->SetEntryPoint(GetCheckAsmJsCodeGenThunk());
  7843. }
  7844. #endif
  7845. }
  7846. });
  7847. }
  7848. void FunctionEntryPointInfo::EnterExpirableCollectMode()
  7849. {
  7850. this->lastCallsCount = this->callsCount;
  7851. // For code that is not jitted yet we don't want to expire since there is nothing to free here
  7852. if (this->IsCodeGenPending())
  7853. {
  7854. this->SetIsObjectUsed();
  7855. }
  7856. }
  7857. void FunctionEntryPointInfo::Invalidate(bool prolongEntryPoint)
  7858. {
  7859. Assert(!this->functionProxy->IsDeferred());
  7860. FunctionBody* functionBody = this->functionProxy->GetFunctionBody();
  7861. Assert(this != functionBody->GetSimpleJitEntryPointInfo());
  7862. // We may have got here following OOM in ProcessJitTransferData. Free any data we have
  7863. // to reduce the chance of another OOM below.
  7864. this->FreeJitTransferData();
  7865. FunctionEntryPointInfo* entryPoint = functionBody->GetDefaultFunctionEntryPointInfo();
  7866. if (entryPoint->IsCodeGenPending())
  7867. {
  7868. OUTPUT_TRACE(Js::LazyBailoutPhase, _u("Skipping creating new entrypoint as one is already pending\n"));
  7869. }
  7870. else
  7871. {
  7872. class AutoCleanup
  7873. {
  7874. EntryPointInfo *entryPointInfo;
  7875. public:
  7876. AutoCleanup(EntryPointInfo *entryPointInfo) : entryPointInfo(entryPointInfo)
  7877. {
  7878. }
  7879. void Done()
  7880. {
  7881. entryPointInfo = nullptr;
  7882. }
  7883. ~AutoCleanup()
  7884. {
  7885. if (entryPointInfo)
  7886. {
  7887. entryPointInfo->ResetOnLazyBailoutFailure();
  7888. }
  7889. }
  7890. } autoCleanup(this);
  7891. entryPoint = functionBody->CreateNewDefaultEntryPoint();
  7892. GenerateFunction(functionBody->GetScriptContext()->GetNativeCodeGenerator(), functionBody, /*function*/ nullptr);
  7893. autoCleanup.Done();
  7894. }
  7895. this->functionProxy->MapFunctionObjectTypes([&](ScriptFunctionType* functionType)
  7896. {
  7897. Assert(functionType->GetTypeId() == TypeIds_Function);
  7898. if (functionType->GetEntryPointInfo() == this)
  7899. {
  7900. functionType->SetEntryPointInfo(entryPoint);
  7901. functionType->SetEntryPoint(this->functionProxy->GetDirectEntryPoint(entryPoint));
  7902. }
  7903. });
  7904. if (!prolongEntryPoint)
  7905. {
  7906. ThreadContext* threadContext = this->functionProxy->GetScriptContext()->GetThreadContext();
  7907. threadContext->QueueFreeOldEntryPointInfoIfInScript(this);
  7908. }
  7909. }
  7910. void FunctionEntryPointInfo::Expire()
  7911. {
  7912. if (this->lastCallsCount != this->callsCount || !this->IsNativeEntryPointProcessed() || this->IsCleanedUp())
  7913. {
  7914. return;
  7915. }
  7916. ThreadContext* threadContext = this->functionProxy->GetScriptContext()->GetThreadContext();
  7917. Assert(!this->functionProxy->IsDeferred());
  7918. FunctionBody* functionBody = this->functionProxy->GetFunctionBody();
  7919. FunctionEntryPointInfo *simpleJitEntryPointInfo = functionBody->GetSimpleJitEntryPointInfo();
  7920. const bool expiringSimpleJitEntryPointInfo = simpleJitEntryPointInfo == this;
  7921. if(expiringSimpleJitEntryPointInfo)
  7922. {
  7923. if(functionBody->GetExecutionMode() != ExecutionMode::FullJit)
  7924. {
  7925. // Don't expire simple JIT code until the transition to full JIT
  7926. return;
  7927. }
  7928. simpleJitEntryPointInfo = nullptr;
  7929. functionBody->SetSimpleJitEntryPointInfo(nullptr);
  7930. }
  7931. try
  7932. {
  7933. AUTO_NESTED_HANDLED_EXCEPTION_TYPE(ExceptionType_OutOfMemory);
  7934. FunctionEntryPointInfo* newEntryPoint = nullptr;
  7935. FunctionEntryPointInfo *const defaultEntryPointInfo = functionBody->GetDefaultFunctionEntryPointInfo();
  7936. if(this == defaultEntryPointInfo)
  7937. {
  7938. if(simpleJitEntryPointInfo)
  7939. {
  7940. newEntryPoint = simpleJitEntryPointInfo;
  7941. functionBody->SetDefaultFunctionEntryPointInfo(simpleJitEntryPointInfo, newEntryPoint->GetNativeEntrypoint());
  7942. functionBody->ResetSimpleJitLimitAndCallCount();
  7943. }
  7944. #ifdef ASMJS_PLAT
  7945. else if (functionBody->GetIsAsmJsFunction())
  7946. {
  7947. // the new entrypoint will be set to interpreter
  7948. newEntryPoint = functionBody->CreateNewDefaultEntryPoint();
  7949. newEntryPoint->SetIsAsmJSFunction(true);
  7950. newEntryPoint->jsMethod = AsmJsDefaultEntryThunk;
  7951. functionBody->SetIsAsmJsFullJitScheduled(false);
  7952. functionBody->SetDefaultInterpreterExecutionMode();
  7953. this->functionProxy->SetOriginalEntryPoint(AsmJsDefaultEntryThunk);
  7954. }
  7955. #endif
  7956. else
  7957. {
  7958. newEntryPoint = functionBody->CreateNewDefaultEntryPoint();
  7959. functionBody->ReinitializeExecutionModeAndLimits();
  7960. #if ENABLE_NATIVE_CODEGEN
  7961. // In order for the function to ever get JIT again, we need to call GenerateFunction now
  7962. if (!PHASE_OFF(Js::BackEndPhase, functionBody) && !functionBody->GetScriptContext()->GetConfig()->IsNoNative())
  7963. {
  7964. GenerateFunction(functionBody->GetScriptContext()->GetNativeCodeGenerator(), functionBody);
  7965. }
  7966. #endif
  7967. }
  7968. functionBody->TraceExecutionMode("JitCodeExpired");
  7969. }
  7970. else
  7971. {
  7972. newEntryPoint = defaultEntryPointInfo;
  7973. }
  7974. OUTPUT_TRACE(Js::ExpirableCollectPhase, _u("Expiring 0x%p\n"), this);
  7975. this->functionProxy->MapFunctionObjectTypes([&] (ScriptFunctionType* functionType)
  7976. {
  7977. Assert(functionType->GetTypeId() == TypeIds_Function);
  7978. if (functionType->GetEntryPointInfo() == this)
  7979. {
  7980. OUTPUT_TRACE(Js::ExpirableCollectPhase, _u("Type 0x%p uses this entry point- switching to default entry point\n"), this);
  7981. functionType->SetEntryPointInfo(newEntryPoint);
  7982. // we are allowed to replace the entry point on the type only if it's
  7983. // directly using the jitted code or a type is referencing this entry point
  7984. // but the entry point hasn't been called since the codegen thunk was installed on it
  7985. if (functionType->GetEntryPoint() == functionProxy->GetDirectEntryPoint(this) || IsIntermediateCodeGenThunk(functionType->GetEntryPoint()))
  7986. {
  7987. functionType->SetEntryPoint(this->functionProxy->GetDirectEntryPoint(newEntryPoint));
  7988. }
  7989. }
  7990. else
  7991. {
  7992. Assert(!functionType->GetEntryPointInfo()->IsFunctionEntryPointInfo() ||
  7993. ((FunctionEntryPointInfo*)functionType->GetEntryPointInfo())->IsCleanedUp()
  7994. || functionType->GetEntryPoint() != this->GetNativeEntrypoint());
  7995. }
  7996. });
  7997. if(expiringSimpleJitEntryPointInfo)
  7998. {
  7999. // We could have just created a new entry point info that is using the simple JIT code. An allocation may have
  8000. // triggered shortly after, resulting in expiring the simple JIT entry point info. Update any entry point infos
  8001. // that are using the simple JIT code, and update the original entry point as necessary as well.
  8002. const JavascriptMethod newOriginalEntryPoint =
  8003. functionBody->GetDynamicInterpreterEntryPoint()
  8004. ? reinterpret_cast<JavascriptMethod>(
  8005. InterpreterThunkEmitter::ConvertToEntryPoint(functionBody->GetDynamicInterpreterEntryPoint()))
  8006. : DefaultEntryThunk;
  8007. const JavascriptMethod currentThunk = functionBody->GetScriptContext()->CurrentThunk;
  8008. const JavascriptMethod newDirectEntryPoint =
  8009. currentThunk == DefaultEntryThunk ? newOriginalEntryPoint : currentThunk;
  8010. const JavascriptMethod simpleJitNativeAddress = GetNativeEntrypoint();
  8011. functionBody->MapEntryPoints([&](const int entryPointIndex, FunctionEntryPointInfo *const entryPointInfo)
  8012. {
  8013. if(entryPointInfo != this && entryPointInfo->jsMethod == simpleJitNativeAddress)
  8014. {
  8015. entryPointInfo->jsMethod = newDirectEntryPoint;
  8016. }
  8017. });
  8018. if(functionBody->GetOriginalEntryPoint_Unchecked() == simpleJitNativeAddress)
  8019. {
  8020. functionBody->SetOriginalEntryPoint(newOriginalEntryPoint);
  8021. functionBody->VerifyOriginalEntryPoint();
  8022. }
  8023. }
  8024. threadContext->QueueFreeOldEntryPointInfoIfInScript(this);
  8025. }
  8026. catch (Js::OutOfMemoryException)
  8027. {
  8028. // If we can't allocate a new entry point, skip expiring this object
  8029. if(expiringSimpleJitEntryPointInfo)
  8030. {
  8031. simpleJitEntryPointInfo = this;
  8032. functionBody->SetSimpleJitEntryPointInfo(this);
  8033. }
  8034. }
  8035. }
  8036. #endif
  8037. #ifdef PERF_COUNTERS
  8038. void LoopEntryPointInfo::OnRecorded()
  8039. {
  8040. PERF_COUNTER_ADD(Code, TotalNativeCodeSize, GetCodeSize());
  8041. PERF_COUNTER_ADD(Code, LoopNativeCodeSize, GetCodeSize());
  8042. PERF_COUNTER_ADD(Code, DynamicNativeCodeSize, GetCodeSize());
  8043. }
  8044. #endif
  8045. FunctionBody *LoopEntryPointInfo::GetFunctionBody() const
  8046. {
  8047. return loopHeader->functionBody;
  8048. }
  8049. //End AsmJs Support
  8050. void LoopEntryPointInfo::OnCleanup(bool isShutdown)
  8051. {
  8052. #ifdef ASMJS_PLAT
  8053. if (this->IsCodeGenDone() && !this->GetIsTJMode())
  8054. #else
  8055. if (this->IsCodeGenDone())
  8056. #endif
  8057. {
  8058. JS_ETW(EtwTrace::LogLoopBodyUnloadEvent(this->loopHeader->functionBody, this,
  8059. this->loopHeader->functionBody->GetLoopNumber(this->loopHeader)));
  8060. #if ENABLE_NATIVE_CODEGEN
  8061. this->CleanupNativeCode(this->loopHeader->functionBody->GetScriptContext());
  8062. #endif
  8063. }
  8064. }
  8065. #if ENABLE_NATIVE_CODEGEN
  8066. void LoopEntryPointInfo::ResetOnNativeCodeInstallFailure()
  8067. {
  8068. // Since we call the address on the entryPointInfo for loop bodies, all we need to do is to roll back
  8069. // the fields on the entryPointInfo related to transferring data from jit thread to main thread (already
  8070. // being done in EntryPointInfo::OnNativeCodeInstallFailure). On the next loop iteration, the interpreter
  8071. // will call EntryPointInfo::EnsureIsReadyToCall and we'll try to process jit transfer data again.
  8072. }
  8073. #endif
  8074. void LoopHeader::Init( FunctionBody * functionBody )
  8075. {
  8076. // DisableJIT-TODO: Should this entire class be ifdefed out?
  8077. #if ENABLE_NATIVE_CODEGEN
  8078. this->functionBody = functionBody;
  8079. Recycler* recycler = functionBody->GetScriptContext()->GetRecycler();
  8080. // Sync entryPoints changes to etw rundown lock
  8081. auto syncObj = functionBody->GetScriptContext()->GetThreadContext()->GetFunctionBodyLock();
  8082. this->entryPoints = RecyclerNew(recycler, LoopEntryPointList, recycler, syncObj);
  8083. this->CreateEntryPoint();
  8084. #endif
  8085. }
  8086. #if ENABLE_NATIVE_CODEGEN
  8087. int LoopHeader::CreateEntryPoint()
  8088. {
  8089. ScriptContext* scriptContext = this->functionBody->GetScriptContext();
  8090. Recycler* recycler = scriptContext->GetRecycler();
  8091. LoopEntryPointInfo* entryPoint = RecyclerNew(recycler, LoopEntryPointInfo, this, scriptContext->GetLibrary());
  8092. return this->entryPoints->Add(entryPoint);
  8093. }
  8094. void LoopHeader::ReleaseEntryPoints()
  8095. {
  8096. for (int iEntryPoint = 0; iEntryPoint < this->entryPoints->Count(); iEntryPoint++)
  8097. {
  8098. LoopEntryPointInfo * entryPoint = this->entryPoints->Item(iEntryPoint);
  8099. if (entryPoint != nullptr && entryPoint->IsCodeGenDone())
  8100. {
  8101. // ReleaseEntryPoints is not called during recycler shutdown scenarios
  8102. // We also don't capture the cleanup stack since we've not seen cleanup bugs affect
  8103. // loop entry points so far. We can pass true here if this is no longer the case.
  8104. entryPoint->Cleanup(false /* isShutdown */, false /* capture cleanup stack */);
  8105. this->entryPoints->Item(iEntryPoint, nullptr);
  8106. }
  8107. }
  8108. }
  8109. #endif
  8110. #if ENABLE_DEBUG_CONFIG_OPTIONS
  8111. void FunctionBody::DumpRegStats(FunctionBody *funcBody)
  8112. {
  8113. if (funcBody->callCountStats == 0)
  8114. {
  8115. return;
  8116. }
  8117. uint loads = funcBody->regAllocLoadCount;
  8118. uint stores = funcBody->regAllocStoreCount;
  8119. if (Js::Configuration::Global.flags.NormalizeStats)
  8120. {
  8121. loads /= this->callCountStats;
  8122. stores /= this->callCountStats;
  8123. }
  8124. funcBody->DumpFullFunctionName();
  8125. Output::SkipToColumn(55);
  8126. Output::Print(_u("Calls:%6d Loads:%9d Stores:%9d Total refs:%9d\n"), this->callCountStats,
  8127. loads, stores, loads + stores);
  8128. }
  8129. #endif
  8130. Js::RegSlot FunctionBody::GetRestParamRegSlot()
  8131. {
  8132. Js::RegSlot dstRegSlot = GetConstantCount();
  8133. if (GetHasImplicitArgIns())
  8134. {
  8135. dstRegSlot += GetInParamsCount() - 1;
  8136. }
  8137. return dstRegSlot;
  8138. }
  8139. uint FunctionBody::GetNumberOfRecursiveCallSites()
  8140. {
  8141. uint recursiveInlineSpan = 0;
  8142. uint recursiveCallSiteInlineInfo = 0;
  8143. #if ENABLE_PROFILE_INFO
  8144. if (this->HasDynamicProfileInfo())
  8145. {
  8146. recursiveCallSiteInlineInfo = this->dynamicProfileInfo->GetRecursiveInlineInfo();
  8147. }
  8148. #endif
  8149. while (recursiveCallSiteInlineInfo)
  8150. {
  8151. recursiveInlineSpan += (recursiveCallSiteInlineInfo & 1);
  8152. recursiveCallSiteInlineInfo >>= 1;
  8153. }
  8154. return recursiveInlineSpan;
  8155. }
  8156. bool FunctionBody::CanInlineRecursively(uint depth, bool tryAggressive)
  8157. {
  8158. uint recursiveInlineSpan = this->GetNumberOfRecursiveCallSites();
  8159. uint minRecursiveInlineDepth = (uint)CONFIG_FLAG(RecursiveInlineDepthMin);
  8160. if (recursiveInlineSpan != this->GetProfiledCallSiteCount() || tryAggressive == false)
  8161. {
  8162. return depth < minRecursiveInlineDepth;
  8163. }
  8164. uint maxRecursiveInlineDepth = (uint)CONFIG_FLAG(RecursiveInlineDepthMax);
  8165. uint maxRecursiveBytecodeBudget = (uint)CONFIG_FLAG(RecursiveInlineThreshold);
  8166. uint numberOfAllowedFuncs = maxRecursiveBytecodeBudget / this->GetByteCodeWithoutLDACount();
  8167. uint maxDepth;
  8168. if (recursiveInlineSpan == 1)
  8169. {
  8170. maxDepth = numberOfAllowedFuncs;
  8171. }
  8172. else
  8173. {
  8174. maxDepth = (uint)ceil(log((double)((double)numberOfAllowedFuncs) / log((double)recursiveInlineSpan)));
  8175. }
  8176. maxDepth = maxDepth < minRecursiveInlineDepth ? minRecursiveInlineDepth : maxDepth;
  8177. maxDepth = maxDepth < maxRecursiveInlineDepth ? maxDepth : maxRecursiveInlineDepth;
  8178. return depth < maxDepth;
  8179. }
  8180. static const char16 LoopWStr[] = _u("Loop");
  8181. size_t FunctionBody::GetLoopBodyName(uint loopNumber, _Out_writes_opt_z_(sizeInChars) WCHAR* displayName, _In_ size_t sizeInChars)
  8182. {
  8183. const char16* functionName = this->GetExternalDisplayName();
  8184. size_t length = wcslen(functionName) + /*length of largest int32*/ 10 + _countof(LoopWStr) + /*null*/ 1;
  8185. if (sizeInChars < length || displayName == nullptr)
  8186. {
  8187. return length;
  8188. }
  8189. int charsWritten = swprintf_s(displayName, length, _u("%s%s%u"), functionName, LoopWStr, loopNumber + 1);
  8190. Assert(charsWritten != -1);
  8191. return charsWritten + /*nullptr*/ 1;
  8192. }
  8193. void FunctionBody::MapAndSetEnvRegister(RegSlot reg)
  8194. {
  8195. Assert(!m_hasEnvRegister);
  8196. SetEnvRegister(this->MapRegSlot(reg));
  8197. }
  8198. void FunctionBody::SetEnvRegister(RegSlot reg)
  8199. {
  8200. if (reg == Constants::NoRegister)
  8201. {
  8202. m_hasEnvRegister = false;
  8203. }
  8204. else
  8205. {
  8206. m_hasEnvRegister = true;
  8207. SetCountField(CounterFields::EnvRegister, reg);
  8208. }
  8209. }
  8210. RegSlot FunctionBody::GetEnvRegister() const
  8211. {
  8212. return m_hasEnvRegister ? GetCountField(CounterFields::EnvRegister) : Constants::NoRegister;
  8213. }
  8214. void FunctionBody::MapAndSetThisRegisterForEventHandler(RegSlot reg)
  8215. {
  8216. Assert(!m_hasThisRegisterForEventHandler);
  8217. SetThisRegisterForEventHandler(this->MapRegSlot(reg));
  8218. }
  8219. void FunctionBody::SetThisRegisterForEventHandler(RegSlot reg)
  8220. {
  8221. if (reg == Constants::NoRegister)
  8222. {
  8223. m_hasThisRegisterForEventHandler = false;
  8224. }
  8225. else
  8226. {
  8227. m_hasThisRegisterForEventHandler = true;
  8228. SetCountField(CounterFields::ThisRegisterForEventHandler, reg);
  8229. }
  8230. }
  8231. RegSlot FunctionBody::GetThisRegisterForEventHandler() const
  8232. {
  8233. return m_hasThisRegisterForEventHandler ? GetCountField(CounterFields::ThisRegisterForEventHandler) : Constants::NoRegister;
  8234. }
  8235. void FunctionBody::SetLocalClosureRegister(RegSlot reg)
  8236. {
  8237. if (reg == Constants::NoRegister)
  8238. {
  8239. m_hasLocalClosureRegister = false;
  8240. }
  8241. else
  8242. {
  8243. m_hasLocalClosureRegister = true;
  8244. SetCountField(CounterFields::LocalClosureRegister, reg);
  8245. }
  8246. }
  8247. void FunctionBody::MapAndSetLocalClosureRegister(RegSlot reg)
  8248. {
  8249. Assert(!m_hasLocalClosureRegister);
  8250. SetLocalClosureRegister(this->MapRegSlot(reg));
  8251. }
  8252. RegSlot FunctionBody::GetLocalClosureRegister() const
  8253. {
  8254. return m_hasLocalClosureRegister ? GetCountField(CounterFields::LocalClosureRegister) : Constants::NoRegister;
  8255. }
  8256. void FunctionBody::SetParamClosureRegister(RegSlot reg)
  8257. {
  8258. if (reg == Constants::NoRegister)
  8259. {
  8260. m_hasParamClosureRegister = false;
  8261. }
  8262. else
  8263. {
  8264. m_hasParamClosureRegister = true;
  8265. SetCountField(CounterFields::ParamClosureRegister, reg);
  8266. }
  8267. }
  8268. void FunctionBody::MapAndSetParamClosureRegister(RegSlot reg)
  8269. {
  8270. Assert(!m_hasParamClosureRegister);
  8271. SetParamClosureRegister(this->MapRegSlot(reg));
  8272. }
  8273. RegSlot FunctionBody::GetParamClosureRegister() const
  8274. {
  8275. return m_hasParamClosureRegister ? GetCountField(CounterFields::ParamClosureRegister) : Constants::NoRegister;
  8276. }
  8277. void FunctionBody::MapAndSetLocalFrameDisplayRegister(RegSlot reg)
  8278. {
  8279. Assert(!m_hasLocalFrameDisplayRegister);
  8280. SetLocalFrameDisplayRegister(this->MapRegSlot(reg));
  8281. }
  8282. void FunctionBody::SetLocalFrameDisplayRegister(RegSlot reg)
  8283. {
  8284. if (reg == Constants::NoRegister)
  8285. {
  8286. m_hasLocalFrameDisplayRegister = false;
  8287. }
  8288. else
  8289. {
  8290. m_hasLocalFrameDisplayRegister = true;
  8291. SetCountField(CounterFields::LocalFrameDisplayRegister, reg);
  8292. }
  8293. }
  8294. RegSlot FunctionBody::GetLocalFrameDisplayRegister() const
  8295. {
  8296. return m_hasLocalFrameDisplayRegister ? GetCountField(CounterFields::LocalFrameDisplayRegister) : Constants::NoRegister;
  8297. }
  8298. void FunctionBody::MapAndSetFirstInnerScopeRegister(RegSlot reg)
  8299. {
  8300. Assert(!m_hasFirstInnerScopeRegister);
  8301. SetFirstInnerScopeRegister(this->MapRegSlot(reg));
  8302. }
  8303. void FunctionBody::SetFirstInnerScopeRegister(RegSlot reg)
  8304. {
  8305. if (reg == Constants::NoRegister)
  8306. {
  8307. m_hasFirstInnerScopeRegister = false;
  8308. }
  8309. else
  8310. {
  8311. m_hasFirstInnerScopeRegister = true;
  8312. SetCountField(CounterFields::FirstInnerScopeRegister, reg);
  8313. }
  8314. }
  8315. RegSlot FunctionBody::GetFirstInnerScopeRegister() const
  8316. {
  8317. return m_hasFirstInnerScopeRegister ? GetCountField(CounterFields::FirstInnerScopeRegister) : Constants::NoRegister;
  8318. }
  8319. void FunctionBody::MapAndSetFuncExprScopeRegister(RegSlot reg)
  8320. {
  8321. Assert(!m_hasFuncExprScopeRegister);
  8322. SetFuncExprScopeRegister(this->MapRegSlot(reg));
  8323. }
  8324. void FunctionBody::SetFuncExprScopeRegister(RegSlot reg)
  8325. {
  8326. if (reg == Constants::NoRegister)
  8327. {
  8328. m_hasFuncExprScopeRegister = false;
  8329. }
  8330. else
  8331. {
  8332. m_hasFuncExprScopeRegister = true;
  8333. SetCountField(CounterFields::FuncExprScopeRegister, reg);
  8334. }
  8335. }
  8336. RegSlot FunctionBody::GetFuncExprScopeRegister() const
  8337. {
  8338. return m_hasFuncExprScopeRegister ? GetCountField(CounterFields::FuncExprScopeRegister) : Constants::NoRegister;
  8339. }
  8340. void FunctionBody::SetFirstTmpRegister(RegSlot reg)
  8341. {
  8342. if (reg == Constants::NoRegister)
  8343. {
  8344. m_hasFirstTmpRegister = false;
  8345. }
  8346. else
  8347. {
  8348. m_hasFirstTmpRegister = true;
  8349. SetCountField(CounterFields::FirstTmpRegister, reg);
  8350. }
  8351. }
  8352. RegSlot FunctionBody::GetFirstTmpRegister() const
  8353. {
  8354. return m_hasFirstTmpRegister ? this->GetCountField(CounterFields::FirstTmpRegister) : Constants::NoRegister;
  8355. }
  8356. }
  8357. #if !DBG
  8358. // Don't grow these data structure unless absolutely necessary
  8359. CompileAssert(sizeof(Js::EntryPointInfo) <= 56);
  8360. CompileAssert(sizeof(Js::FunctionEntryPointInfo) <= 96);
  8361. #endif