FunctionBody.cpp 367 KB

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