FunctionBody.cpp 389 KB

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