FunctionBody.cpp 364 KB

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