FunctionBody.cpp 363 KB

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