NativeCodeGenerator.cpp 154 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844
  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 "Backend.h"
  6. #include "Base/ScriptContextProfiler.h"
  7. #include "NativeEntryPointData.h"
  8. #include "JitTransferData.h"
  9. #if DBG
  10. Js::JavascriptMethod checkCodeGenThunk;
  11. #endif
  12. #ifdef ENABLE_PREJIT
  13. #define IS_PREJIT_ON() (Js::Configuration::Global.flags.Prejit)
  14. #else
  15. #define IS_PREJIT_ON() (DEFAULT_CONFIG_Prejit)
  16. #endif
  17. #define ASSERT_THREAD() AssertMsg(mainThreadId == GetCurrentThreadContextId(), \
  18. "Cannot use this member of native code generator from thread other than the creating context's current thread")
  19. NativeCodeGenerator::NativeCodeGenerator(Js::ScriptContext * scriptContext)
  20. : JsUtil::WaitableJobManager(scriptContext->GetThreadContext()->GetJobProcessor()),
  21. scriptContext(scriptContext),
  22. pendingCodeGenWorkItems(0),
  23. queuedFullJitWorkItemCount(0),
  24. foregroundAllocators(nullptr),
  25. backgroundAllocators(nullptr),
  26. byteCodeSizeGenerated(0),
  27. isClosed(false),
  28. isOptimizedForManyInstances(scriptContext->GetThreadContext()->IsOptimizedForManyInstances()),
  29. SetNativeEntryPoint(Js::FunctionBody::DefaultSetNativeEntryPoint),
  30. freeLoopBodyManager(scriptContext->GetThreadContext()->GetJobProcessor()),
  31. hasUpdatedQForDebugMode(false)
  32. #ifdef PROFILE_EXEC
  33. , foregroundCodeGenProfiler(nullptr)
  34. , backgroundCodeGenProfiler(nullptr)
  35. #endif
  36. {
  37. freeLoopBodyManager.SetNativeCodeGen(this);
  38. #if DBG_DUMP
  39. if (Js::Configuration::Global.flags.IsEnabled(Js::AsmDumpModeFlag)
  40. && (Js::Configuration::Global.flags.AsmDumpMode != nullptr))
  41. {
  42. bool fileOpened = false;
  43. fileOpened = (0 == _wfopen_s(&this->asmFile, Js::Configuration::Global.flags.AsmDumpMode, _u("wt")));
  44. if (!fileOpened)
  45. {
  46. size_t len = wcslen(Js::Configuration::Global.flags.AsmDumpMode);
  47. if (len < _MAX_PATH - 5)
  48. {
  49. char16 filename[_MAX_PATH];
  50. wcscpy_s(filename, _MAX_PATH, Js::Configuration::Global.flags.AsmDumpMode);
  51. char16 * number = filename + len;
  52. for (int i = 0; i < 1000; i++)
  53. {
  54. _itow_s(i, number, 5, 10);
  55. fileOpened = (0 == _wfopen_s(&this->asmFile, filename, _u("wt")));
  56. if (fileOpened)
  57. {
  58. break;
  59. }
  60. }
  61. }
  62. if (!fileOpened)
  63. {
  64. this->asmFile = nullptr;
  65. AssertMsg(0, "Could not open file for AsmDump. The output will goto standard console");
  66. }
  67. }
  68. }
  69. else
  70. {
  71. this->asmFile = nullptr;
  72. }
  73. #endif
  74. #if DBG
  75. this->mainThreadId = GetCurrentThreadContextId();
  76. #endif
  77. Processor()->AddManager(this);
  78. this->freeLoopBodyManager.SetAutoClose(false);
  79. }
  80. NativeCodeGenerator::~NativeCodeGenerator()
  81. {
  82. Assert(this->IsClosed());
  83. #if PDATA_ENABLED && defined(_WIN32)
  84. DelayDeletingFunctionTable::Clear();
  85. #endif
  86. #ifdef PROFILE_EXEC
  87. if (this->foregroundCodeGenProfiler != nullptr)
  88. {
  89. this->foregroundCodeGenProfiler->Release();
  90. }
  91. #endif
  92. if (scriptContext->GetJitFuncRangeCache() != nullptr)
  93. {
  94. scriptContext->GetJitFuncRangeCache()->ClearCache();
  95. }
  96. if(this->foregroundAllocators != nullptr)
  97. {
  98. HeapDelete(this->foregroundAllocators);
  99. }
  100. if (this->backgroundAllocators)
  101. {
  102. #if DBG
  103. // PageAllocator is thread agile. This destructor can be called from background GC thread.
  104. // We have already removed this manager from the job queue and hence its fine to set the threadId to -1.
  105. // We can't DissociatePageAllocator here as its allocated ui thread.
  106. //this->Processor()->DissociatePageAllocator(allocator->GetPageAllocator());
  107. this->backgroundAllocators->ClearConcurrentThreadId();
  108. #endif
  109. // The native code generator may be deleted after Close was called on the job processor. In that case, the
  110. // background thread is no longer running, so clean things up in the foreground.
  111. HeapDelete(this->backgroundAllocators);
  112. }
  113. #ifdef PROFILE_EXEC
  114. if (Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag))
  115. {
  116. while (this->backgroundCodeGenProfiler)
  117. {
  118. Js::ScriptContextProfiler *codegenProfiler = this->backgroundCodeGenProfiler;
  119. this->backgroundCodeGenProfiler = this->backgroundCodeGenProfiler->next;
  120. // background codegen profiler is allocated in background thread,
  121. // clear the thead Id before release
  122. #ifdef DBG
  123. if (codegenProfiler->pageAllocator != nullptr)
  124. {
  125. codegenProfiler->pageAllocator->SetDisableThreadAccessCheck();
  126. }
  127. #endif
  128. codegenProfiler->Release();
  129. }
  130. }
  131. else
  132. {
  133. Assert(this->backgroundCodeGenProfiler == nullptr);
  134. }
  135. #endif
  136. }
  137. void NativeCodeGenerator::Close()
  138. {
  139. Assert(!this->IsClosed());
  140. // Close FreeLoopBodyJobManager first, as it depends on NativeCodeGenerator to be open before it's removed
  141. this->freeLoopBodyManager.Close();
  142. Processor()->RemoveManager(this);
  143. this->isClosed = true;
  144. Assert(!queuedFullJitWorkItems.Head());
  145. Assert(queuedFullJitWorkItemCount == 0);
  146. for(JsUtil::Job *job = workItems.Head(); job;)
  147. {
  148. JsUtil::Job *const next = job->Next();
  149. JobProcessed(job, /*succeeded*/ false);
  150. job = next;
  151. }
  152. workItems.Clear();
  153. // Only decommit here instead of releasing the memory, so we retain control over these addresses
  154. // Mitigate against the case the entry point is called after the script site is closed
  155. if (this->backgroundAllocators)
  156. {
  157. this->backgroundAllocators->emitBufferManager.Decommit();
  158. }
  159. if (this->foregroundAllocators)
  160. {
  161. this->foregroundAllocators->emitBufferManager.Decommit();
  162. }
  163. #if DBG_DUMP
  164. if (this->asmFile != nullptr)
  165. {
  166. if(0 != fclose(this->asmFile))
  167. {
  168. AssertMsg(0, "Could not close file for AsmDump. You may ignore this warning.");
  169. }
  170. }
  171. #endif
  172. }
  173. #if DBG_DUMP
  174. extern Func *CurrentFunc;
  175. #endif
  176. JsFunctionCodeGen *
  177. NativeCodeGenerator::NewFunctionCodeGen(Js::FunctionBody *functionBody, Js::EntryPointInfo* info)
  178. {
  179. return HeapNewNoThrow(JsFunctionCodeGen, this, functionBody, info, functionBody->IsInDebugMode());
  180. }
  181. JsLoopBodyCodeGen *
  182. NativeCodeGenerator::NewLoopBodyCodeGen(Js::FunctionBody *functionBody, Js::EntryPointInfo* info, Js::LoopHeader * loopHeader)
  183. {
  184. return HeapNewNoThrow(JsLoopBodyCodeGen, this, functionBody, info, functionBody->IsInDebugMode(), loopHeader);
  185. }
  186. #ifdef ENABLE_PREJIT
  187. bool
  188. NativeCodeGenerator::DoBackEnd(Js::FunctionBody *fn)
  189. {
  190. return (
  191. !PHASE_OFF(Js::BackEndPhase, fn)
  192. && !fn->IsGeneratorAndJitIsDisabled()
  193. #ifdef ASMJS_PLAT
  194. && !fn->IsAsmJSModule()
  195. #endif
  196. );
  197. }
  198. void
  199. NativeCodeGenerator::GenerateAllFunctions(Js::FunctionBody * fn)
  200. {
  201. Assert(IS_PREJIT_ON());
  202. Assert(fn->GetDefaultFunctionEntryPointInfo()->entryPointIndex == 0);
  203. // Make sure this isn't a deferred function
  204. Assert(fn->GetFunctionBody() == fn);
  205. Assert(!fn->IsDeferred());
  206. if (DoBackEnd(fn))
  207. {
  208. if (fn->GetLoopCount() != 0 && fn->ForceJITLoopBody() && !fn->IsInDebugMode())
  209. {
  210. // Only jit the loop body with /force:JITLoopBody
  211. for (uint i = 0; i < fn->GetLoopCount(); i++)
  212. {
  213. Js::LoopHeader * loopHeader = fn->GetLoopHeader(i);
  214. Js::EntryPointInfo * entryPointInfo = loopHeader->GetCurrentEntryPointInfo();
  215. this->GenerateLoopBody(fn, loopHeader, entryPointInfo);
  216. }
  217. }
  218. else
  219. {
  220. // A JIT attempt should have already been made through GenerateFunction
  221. Assert(!fn->GetDefaultFunctionEntryPointInfo()->IsNotScheduled());
  222. }
  223. }
  224. for (uint i = 0; i < fn->GetNestedCount(); i++)
  225. {
  226. Js::FunctionBody* functionToJIT = fn->GetNestedFunctionForExecution(i)->GetFunctionBody();
  227. GenerateAllFunctions(functionToJIT);
  228. }
  229. }
  230. #endif
  231. #if _M_ARM
  232. USHORT ArmExtractThumbImmediate16(PUSHORT address)
  233. {
  234. return ((address[0] << 12) & 0xf000) | // bits[15:12] in OP0[3:0]
  235. ((address[0] << 1) & 0x0800) | // bits[11] in OP0[10]
  236. ((address[1] >> 4) & 0x0700) | // bits[10:8] in OP1[14:12]
  237. ((address[1] >> 0) & 0x00ff); // bits[7:0] in OP1[7:0]
  238. }
  239. void ArmInsertThumbImmediate16(PUSHORT address, USHORT immediate)
  240. {
  241. USHORT opcode0;
  242. USHORT opcode1;
  243. opcode0 = address[0];
  244. opcode1 = address[1];
  245. opcode0 &= ~((0xf000 >> 12) | (0x0800 >> 1));
  246. opcode1 &= ~((0x0700 << 4) | (0x00ff << 0));
  247. opcode0 |= (immediate & 0xf000) >> 12; // bits[15:12] in OP0[3:0]
  248. opcode0 |= (immediate & 0x0800) >> 1; // bits[11] in OP0[10]
  249. opcode1 |= (immediate & 0x0700) << 4; // bits[10:8] in OP1[14:12]
  250. opcode1 |= (immediate & 0x00ff) << 0; // bits[7:0] in OP1[7:0]
  251. address[0] = opcode0;
  252. address[1] = opcode1;
  253. }
  254. #endif
  255. void DoFunctionRelocations(BYTE *function, DWORD functionOffset, DWORD functionSize, BYTE *module, size_t imageBase, IMAGE_SECTION_HEADER *textHeader, IMAGE_SECTION_HEADER *relocHeader)
  256. {
  257. PIMAGE_BASE_RELOCATION relocationBlock = (PIMAGE_BASE_RELOCATION)(module + relocHeader->PointerToRawData);
  258. for (; relocationBlock->VirtualAddress > 0 && ((BYTE *)relocationBlock < (module + relocHeader->PointerToRawData + relocHeader->SizeOfRawData)); )
  259. {
  260. DWORD blockOffset = relocationBlock->VirtualAddress - textHeader->VirtualAddress;
  261. // Skip relocation blocks that are before the function
  262. if ((blockOffset + 0x1000) > functionOffset)
  263. {
  264. unsigned short *relocation = (unsigned short *)((unsigned char *)relocationBlock + sizeof(IMAGE_BASE_RELOCATION));
  265. for (uint index = 0; index < ((relocationBlock->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / 2); index++, relocation++)
  266. {
  267. int type = *relocation >> 12;
  268. int offset = *relocation & 0xfff;
  269. // If we are past the end of the function, we can stop.
  270. if ((blockOffset + offset) >= (functionOffset + functionSize))
  271. {
  272. break;
  273. }
  274. if ((blockOffset + offset) < functionOffset)
  275. {
  276. continue;
  277. }
  278. switch (type)
  279. {
  280. case IMAGE_REL_BASED_ABSOLUTE:
  281. break;
  282. #if _M_IX86
  283. case IMAGE_REL_BASED_HIGHLOW:
  284. {
  285. DWORD *patchAddrHL = (DWORD *) (function + blockOffset + offset - functionOffset);
  286. DWORD patchAddrHLOffset = *patchAddrHL - imageBase - textHeader->VirtualAddress;
  287. Assert((patchAddrHLOffset > functionOffset) && (patchAddrHLOffset < (functionOffset + functionSize)));
  288. *patchAddrHL = patchAddrHLOffset - functionOffset + (DWORD)function;
  289. }
  290. break;
  291. #elif defined(TARGET_64)
  292. case IMAGE_REL_BASED_DIR64:
  293. {
  294. ULONGLONG *patchAddr64 = (ULONGLONG *) (function + blockOffset + offset - functionOffset);
  295. ULONGLONG patchAddr64Offset = *patchAddr64 - imageBase - textHeader->VirtualAddress;
  296. Assert((patchAddr64Offset > functionOffset) && (patchAddr64Offset < (functionOffset + functionSize)));
  297. *patchAddr64 = patchAddr64Offset - functionOffset + (ULONGLONG)function;
  298. }
  299. break;
  300. #else
  301. case IMAGE_REL_BASED_THUMB_MOV32:
  302. {
  303. USHORT *patchAddr = (USHORT *) (function + blockOffset + offset - functionOffset);
  304. DWORD address = ArmExtractThumbImmediate16(patchAddr) | (ArmExtractThumbImmediate16(patchAddr + 2) << 16);
  305. address = address - imageBase - textHeader->VirtualAddress - functionOffset + (DWORD)function;
  306. ArmInsertThumbImmediate16(patchAddr, (USHORT)(address & 0xFFFF));
  307. ArmInsertThumbImmediate16(patchAddr + 2, (USHORT)(address >> 16));
  308. }
  309. break;
  310. #endif
  311. default:
  312. Assert(false);
  313. break;
  314. }
  315. }
  316. }
  317. relocationBlock = (PIMAGE_BASE_RELOCATION) (((BYTE *) relocationBlock) + relocationBlock->SizeOfBlock);
  318. }
  319. }
  320. class AutoRestoreDefaultEntryPoint
  321. {
  322. public:
  323. AutoRestoreDefaultEntryPoint(Js::FunctionBody* functionBody):
  324. functionBody(functionBody)
  325. {
  326. this->oldDefaultEntryPoint = functionBody->GetDefaultFunctionEntryPointInfo();
  327. this->oldOriginalEntryPoint = functionBody->GetOriginalEntryPoint();
  328. this->newEntryPoint = functionBody->CreateNewDefaultEntryPoint();
  329. }
  330. ~AutoRestoreDefaultEntryPoint()
  331. {
  332. if (newEntryPoint && !newEntryPoint->IsCodeGenDone())
  333. {
  334. functionBody->RestoreOldDefaultEntryPoint(oldDefaultEntryPoint, oldOriginalEntryPoint, newEntryPoint);
  335. }
  336. }
  337. private:
  338. Js::FunctionBody* functionBody;
  339. Js::FunctionEntryPointInfo* oldDefaultEntryPoint;
  340. Js::JavascriptMethod oldOriginalEntryPoint;
  341. Js::FunctionEntryPointInfo* newEntryPoint;
  342. };
  343. //static
  344. void NativeCodeGenerator::Jit_TransitionFromSimpleJit(void *const framePointer)
  345. {
  346. JIT_HELPER_NOT_REENTRANT_NOLOCK_HEADER(TransitionFromSimpleJit);
  347. TransitionFromSimpleJit(
  348. Js::VarTo<Js::ScriptFunction>(Js::JavascriptCallStackLayout::FromFramePointer(framePointer)->functionObject));
  349. JIT_HELPER_END(TransitionFromSimpleJit);
  350. }
  351. //static
  352. void NativeCodeGenerator::TransitionFromSimpleJit(Js::ScriptFunction *const function)
  353. {
  354. Assert(function);
  355. Js::FunctionBody *const functionBody = function->GetFunctionBody();
  356. Js::FunctionEntryPointInfo *const defaultEntryPointInfo = functionBody->GetDefaultFunctionEntryPointInfo();
  357. if(defaultEntryPointInfo == functionBody->GetSimpleJitEntryPointInfo())
  358. {
  359. Assert(functionBody->GetExecutionMode() == ExecutionMode::SimpleJit);
  360. Assert(function->GetFunctionEntryPointInfo() == defaultEntryPointInfo);
  361. // The latest entry point is the simple JIT, transition to the next execution mode and schedule a full JIT
  362. bool functionEntryPointUpdated = functionBody->GetScriptContext()->GetNativeCodeGenerator()->GenerateFunction(functionBody, function);
  363. if (functionEntryPointUpdated)
  364. {
  365. // Transition to the next execution mode after scheduling a full JIT, in case of OOM before the entry point is changed
  366. const bool transitioned = functionBody->TryTransitionToNextExecutionMode();
  367. Assert(transitioned);
  368. if (PHASE_TRACE(Js::SimpleJitPhase, functionBody))
  369. {
  370. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  371. Output::Print(
  372. _u("SimpleJit (TransitionFromSimpleJit): function: %s (%s)"),
  373. functionBody->GetDisplayName(),
  374. functionBody->GetDebugNumberSet(debugStringBuffer));
  375. Output::Flush();
  376. }
  377. }
  378. return;
  379. }
  380. if(function->GetFunctionEntryPointInfo() != defaultEntryPointInfo)
  381. {
  382. // A full JIT may have already been scheduled, or some entry point info got expired before the simple JIT entry point
  383. // was ready. In any case, the function's entry point info is not the latest, so update it.
  384. function->UpdateThunkEntryPoint(defaultEntryPointInfo, functionBody->GetDirectEntryPoint(defaultEntryPointInfo));
  385. }
  386. }
  387. #ifdef IR_VIEWER
  388. Js::Var
  389. NativeCodeGenerator::RejitIRViewerFunction(Js::FunctionBody *fn, Js::ScriptContext *requestContext)
  390. {
  391. /* Note: adapted from NativeCodeGenerator::GenerateFunction (NativeCodeGenerator.cpp) */
  392. Js::ScriptContext *scriptContext = fn->GetScriptContext();
  393. PageAllocator *pageAllocator = scriptContext->GetThreadContext()->GetPageAllocator();
  394. NativeCodeGenerator *nativeCodeGenerator = scriptContext->GetNativeCodeGenerator();
  395. AutoRestoreDefaultEntryPoint autoRestore(fn);
  396. Js::FunctionEntryPointInfo * entryPoint = fn->GetDefaultFunctionEntryPointInfo();
  397. JsFunctionCodeGen workitem(this, fn, entryPoint, fn->IsInDebugMode());
  398. workitem.isRejitIRViewerFunction = true;
  399. workitem.irViewerRequestContext = scriptContext;
  400. workitem.SetJitMode(ExecutionMode::FullJit);
  401. entryPoint->SetCodeGenPendingWithStackAllocatedWorkItem();
  402. entryPoint->SetCodeGenQueued();
  403. const auto recyclableData = GatherCodeGenData(fn, fn, entryPoint, &workitem);
  404. workitem.SetRecyclableData(recyclableData);
  405. nativeCodeGenerator->CodeGen(pageAllocator, &workitem, true);
  406. return Js::CrossSite::MarshalVar(requestContext, workitem.GetIRViewerOutput(scriptContext));
  407. }
  408. #endif /* IR_VIEWER */
  409. #ifdef ALLOW_JIT_REPRO
  410. HRESULT NativeCodeGenerator::JitFromEncodedWorkItem(_In_reads_(bufferSize) const byte* buffer, _In_ uint bufferSize)
  411. {
  412. CodeGenWorkItemIDL* workItemData = nullptr;
  413. HRESULT hr = JITManager::DeserializeRPCData(buffer, bufferSize, &workItemData);
  414. if (FAILED(hr))
  415. {
  416. return hr;
  417. }
  418. AssertOrFailFast(workItemData);
  419. JITOutputIDL jitOutput = { 0 };
  420. CodeGen(scriptContext->GetThreadContext()->GetPageAllocator(), workItemData, jitOutput, true);
  421. return S_OK;
  422. }
  423. #endif
  424. ///----------------------------------------------------------------------------
  425. ///
  426. /// NativeCodeGenerator::GenerateFunction
  427. ///
  428. /// This is the main entry point for the runtime to call the native code
  429. /// generator.
  430. ///
  431. ///----------------------------------------------------------------------------
  432. bool
  433. NativeCodeGenerator::GenerateFunction(Js::FunctionBody *fn, Js::ScriptFunction * function)
  434. {
  435. ASSERT_THREAD();
  436. Assert(!fn->GetIsFromNativeCodeModule());
  437. Assert(fn->GetScriptContext()->GetNativeCodeGenerator() == this);
  438. Assert(fn->GetFunctionBody() == fn);
  439. Assert(!fn->IsDeferred());
  440. if (fn->IsGeneratorAndJitIsDisabled())
  441. {
  442. // JITing generator functions is not complete nor stable yet so it is off by default.
  443. // Also try/catch JIT support in generator functions is not a goal for threshold
  444. // release so JITing generators containing try blocks is disabled for now.
  445. return false;
  446. }
  447. if (fn->IsInDebugMode() && fn->GetHasTry())
  448. {
  449. // Under debug mode disable JIT for functions that:
  450. // - have try
  451. return false;
  452. }
  453. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  454. if (Js::Configuration::Global.flags.Interpret &&
  455. fn->GetDisplayName() &&
  456. ::wcsstr(Js::Configuration::Global.flags.Interpret, fn->GetDisplayName()))
  457. {
  458. return false;
  459. }
  460. #endif
  461. if (fn->GetLoopCount() != 0 && fn->ForceJITLoopBody() && !fn->IsInDebugMode())
  462. {
  463. // Don't code gen the function if the function has loop, ForceJITLoopBody is on,
  464. // unless we are in debug mode in which case JIT loop body is disabled, even if it's forced.
  465. return false;
  466. }
  467. // Create a work item with null entry point- we'll set it once its allocated
  468. AutoPtr<JsFunctionCodeGen> workItemAutoPtr(this->NewFunctionCodeGen(fn, nullptr));
  469. if ((JsFunctionCodeGen*) workItemAutoPtr == nullptr)
  470. {
  471. // OOM, just skip this work item and return.
  472. return false;
  473. }
  474. Js::FunctionEntryPointInfo* entryPointInfo = nullptr;
  475. if (function != nullptr)
  476. {
  477. entryPointInfo = fn->CreateNewDefaultEntryPoint();
  478. }
  479. else
  480. {
  481. entryPointInfo = fn->GetDefaultFunctionEntryPointInfo();
  482. Assert(fn->IsInterpreterThunk() || fn->IsSimpleJitOriginalEntryPoint());
  483. }
  484. bool doPreJit = IS_PREJIT_ON();
  485. #ifdef ASMJS_PLAT
  486. if (fn->GetIsAsmjsMode())
  487. {
  488. AnalysisAssert(function != nullptr);
  489. Js::FunctionEntryPointInfo* oldFuncObjEntryPointInfo = (Js::FunctionEntryPointInfo*)function->GetEntryPointInfo();
  490. Assert(oldFuncObjEntryPointInfo->GetIsAsmJSFunction()); // should be asmjs entrypoint info
  491. // Set asmjs to be true in entrypoint
  492. entryPointInfo->SetIsAsmJSFunction(true);
  493. Assert(PHASE_ON1(Js::AsmJsJITTemplatePhase) || (!oldFuncObjEntryPointInfo->GetIsTJMode() && !entryPointInfo->GetIsTJMode()));
  494. // this changes the address in the entrypointinfo to be the AsmJsCodgenThunk
  495. function->UpdateThunkEntryPoint(entryPointInfo, NativeCodeGenerator::CheckAsmJsCodeGenThunk);
  496. if (PHASE_TRACE1(Js::AsmjsEntryPointInfoPhase))
  497. Output::Print(_u("New Entrypoint is CheckAsmJsCodeGenThunk for function: %s\n"), fn->GetDisplayName());
  498. doPreJit |= CONFIG_FLAG(MaxAsmJsInterpreterRunCount) == 0 || CONFIG_ISENABLED(Js::ForceNativeFlag);
  499. }
  500. else
  501. #endif
  502. {
  503. fn->SetCheckCodeGenEntryPoint(entryPointInfo, NativeCodeGenerator::CheckCodeGenThunk);
  504. if (function != nullptr)
  505. {
  506. function->UpdateThunkEntryPoint(entryPointInfo, NativeCodeGenerator::CheckCodeGenThunk);
  507. }
  508. }
  509. JsFunctionCodeGen * workitem = workItemAutoPtr.Detach();
  510. workitem->SetEntryPointInfo(entryPointInfo);
  511. entryPointInfo->SetCodeGenPending(workitem);
  512. InterlockedIncrement(&pendingCodeGenWorkItems);
  513. if(!doPreJit)
  514. {
  515. workItems.LinkToEnd(workitem);
  516. return true;
  517. }
  518. const ExecutionMode prejitJitMode = PrejitJitMode(fn);
  519. workitem->SetJitMode(prejitJitMode);
  520. try
  521. {
  522. AddToJitQueue(workitem, /*prioritize*/ true, /*lock*/ true, function);
  523. }
  524. catch (...)
  525. {
  526. // Add the item back to the list if AddToJitQueue throws. The position in the list is not important.
  527. workitem->ResetJitMode();
  528. workItems.LinkToEnd(workitem);
  529. throw;
  530. }
  531. fn->TraceExecutionMode("Prejit (before)");
  532. if(prejitJitMode == ExecutionMode::SimpleJit)
  533. {
  534. fn->TransitionToSimpleJitExecutionMode();
  535. }
  536. else
  537. {
  538. Assert(prejitJitMode == ExecutionMode::FullJit);
  539. fn->TransitionToFullJitExecutionMode();
  540. }
  541. fn->TraceExecutionMode("Prejit");
  542. Processor()->PrioritizeJobAndWait(this, entryPointInfo, function);
  543. CheckCodeGenDone(fn, entryPointInfo, function);
  544. return true;
  545. }
  546. void NativeCodeGenerator::GenerateLoopBody(Js::FunctionBody * fn, Js::LoopHeader * loopHeader, Js::EntryPointInfo* entryPoint, uint localCount, Js::Var localSlots[])
  547. {
  548. ASSERT_THREAD();
  549. Assert(fn->GetScriptContext()->GetNativeCodeGenerator() == this);
  550. Assert(entryPoint->jsMethod == nullptr);
  551. #if DBG_DUMP
  552. if (PHASE_TRACE1(Js::JITLoopBodyPhase))
  553. {
  554. fn->DumpFunctionId(true);
  555. Output::Print(_u(": %-20s LoopBody Start Loop: %2d ByteCode: %4d (%4d,%4d)\n"), fn->GetDisplayName(), fn->GetLoopNumber(loopHeader),
  556. loopHeader->endOffset - loopHeader->startOffset, loopHeader->startOffset, loopHeader->endOffset);
  557. Output::Flush();
  558. }
  559. #endif
  560. // If the parent function is JITted, no need to JIT this loop
  561. // CanReleaseLoopHeaders is a quick and dirty way of checking if the
  562. // function is currently being interpreted. If it is being interpreted,
  563. // We'd still like to jit the loop body.
  564. // We reset the interpretCount to 0 in case we switch back to the interpreter
  565. if (fn->GetNativeEntryPointUsed() && fn->GetCanReleaseLoopHeaders()
  566. #ifdef ASMJS_PLAT
  567. && (!fn->GetIsAsmJsFunction() || !(loopHeader->GetCurrentEntryPointInfo()->GetIsTJMode()))
  568. #endif
  569. )
  570. {
  571. loopHeader->ResetInterpreterCount();
  572. return;
  573. }
  574. #ifdef ASMJS_PLAT
  575. if (fn->GetIsAsmJsFunction())
  576. {
  577. Js::LoopEntryPointInfo* loopEntryPointInfo = (Js::LoopEntryPointInfo*)entryPoint;
  578. loopEntryPointInfo->SetIsAsmJSFunction(true);
  579. }
  580. #endif
  581. JsLoopBodyCodeGen * workitem = this->NewLoopBodyCodeGen(fn, entryPoint, loopHeader);
  582. if (!workitem)
  583. {
  584. // OOM, just skip this work item and return.
  585. return;
  586. }
  587. entryPoint->SetCodeGenPending(workitem);
  588. try
  589. {
  590. if (!fn->GetIsAsmJsFunction()) // not needed for asmjs as we don't profile in asm mode
  591. {
  592. const uint profiledRegBegin = fn->GetConstantCount();
  593. const uint profiledRegEnd = localCount;
  594. if (profiledRegBegin < profiledRegEnd)
  595. {
  596. workitem->GetJITData()->symIdToValueTypeMapCount = profiledRegEnd - profiledRegBegin;
  597. workitem->GetJITData()->symIdToValueTypeMap = (uint16*)HeapNewArrayZ(ValueType, workitem->GetJITData()->symIdToValueTypeMapCount);
  598. Recycler *recycler = fn->GetScriptContext()->GetRecycler();
  599. for (uint i = profiledRegBegin; i < profiledRegEnd; i++)
  600. {
  601. if (localSlots[i] && IsValidVar(localSlots[i], recycler))
  602. {
  603. workitem->GetJITData()->symIdToValueTypeMap[i - profiledRegBegin] = ValueType::Uninitialized.Merge(localSlots[i]).GetRawData();
  604. }
  605. }
  606. }
  607. }
  608. workitem->SetJitMode(ExecutionMode::FullJit);
  609. AddToJitQueue(workitem, /*prioritize*/ true, /*lock*/ true);
  610. }
  611. catch (...)
  612. {
  613. // If adding to the JIT queue fails we need to revert the state of the entry point
  614. // and delete the work item
  615. entryPoint->RevertToNotScheduled();
  616. workitem->Delete();
  617. throw;
  618. }
  619. if (!Processor()->ProcessesInBackground() || fn->ForceJITLoopBody())
  620. {
  621. Processor()->PrioritizeJobAndWait(this, entryPoint);
  622. }
  623. }
  624. bool
  625. NativeCodeGenerator::IsValidVar(const Js::Var var, Recycler *const recycler)
  626. {
  627. using namespace Js;
  628. Assert(var);
  629. Assert(recycler);
  630. // We may be handling uninitialized memory here, need to ensure that each recycler-allocated object is valid before it is
  631. // read. Virtual functions shouldn't be called because the type ID may match by coincidence but the vtable can still be
  632. // invalid, even if it is deemed to be a "valid" object, since that only validates that the memory is still owned by the
  633. // recycler. This function validates the memory that ValueType::Merge(Var) reads.
  634. if(TaggedInt::Is(var))
  635. {
  636. return true;
  637. }
  638. #if FLOATVAR
  639. if(JavascriptNumber::Is_NoTaggedIntCheck(var))
  640. {
  641. return true;
  642. }
  643. #endif
  644. RecyclableObject *const recyclableObject = UnsafeVarTo<RecyclableObject>(var);
  645. if(!recycler->IsValidObject(recyclableObject, sizeof(*recyclableObject)))
  646. {
  647. return false;
  648. }
  649. INT_PTR vtable = VirtualTableInfoBase::GetVirtualTable(var);
  650. if (vtable <= USHRT_MAX || (vtable & 1))
  651. {
  652. // Don't have a vtable, is it not a var, may be a frame display?
  653. return false;
  654. }
  655. Type *const type = recyclableObject->GetType();
  656. if(!recycler->IsValidObject(type, sizeof(*type)))
  657. {
  658. return false;
  659. }
  660. #if !FLOATVAR
  661. if(JavascriptNumber::Is_NoTaggedIntCheck(var))
  662. {
  663. return true;
  664. }
  665. #endif
  666. const TypeId typeId = type->GetTypeId();
  667. if(typeId < static_cast<TypeId>(0))
  668. {
  669. return false;
  670. }
  671. if(!DynamicType::Is(typeId))
  672. {
  673. return true;
  674. }
  675. DynamicType *const dynamicType = static_cast<DynamicType *>(type);
  676. if(!recycler->IsValidObject(dynamicType, sizeof(*dynamicType)))
  677. {
  678. return false;
  679. }
  680. DynamicTypeHandler *const typeHandler = dynamicType->GetTypeHandler();
  681. if(!recycler->IsValidObject(typeHandler, sizeof(*typeHandler)))
  682. {
  683. return false;
  684. }
  685. // Not using VarTo<DynamicObject> since there's a virtual call in there
  686. DynamicObject *const object = static_cast<DynamicObject *>(recyclableObject);
  687. if(!recycler->IsValidObject(object, sizeof(*object)))
  688. {
  689. return false;
  690. }
  691. if(typeId != TypeIds_Array)
  692. {
  693. ArrayObject* const objectArray = object->GetObjectArrayUnchecked();
  694. return objectArray == nullptr || recycler->IsValidObject(objectArray, sizeof(*objectArray));
  695. }
  696. // Not using JavascriptArray::FromVar since there's a virtual call in there
  697. JavascriptArray *const array = static_cast<JavascriptArray *>(object);
  698. if(!recycler->IsValidObject(array, sizeof(*array)))
  699. {
  700. return false;
  701. }
  702. return true;
  703. }
  704. #if ENABLE_DEBUG_CONFIG_OPTIONS
  705. volatile UINT_PTR NativeCodeGenerator::CodegenFailureSeed = 0;
  706. #endif
  707. void NativeCodeGenerator::CodeGen(PageAllocator* pageAllocator, CodeGenWorkItemIDL* workItemData, _Out_ JITOutputIDL& jitWriteData, const bool foreground, Js::EntryPointInfo* epInfo /*= nullptr*/)
  708. {
  709. if (JITManager::GetJITManager()->IsOOPJITEnabled())
  710. {
  711. PSCRIPTCONTEXT_HANDLE remoteScriptContext = this->scriptContext->GetRemoteScriptAddr();
  712. if (!JITManager::GetJITManager()->IsConnected())
  713. {
  714. throw Js::OperationAbortedException();
  715. }
  716. HRESULT hr = JITManager::GetJITManager()->RemoteCodeGenCall(
  717. workItemData,
  718. remoteScriptContext,
  719. &jitWriteData);
  720. if (hr == E_ACCESSDENIED && scriptContext->IsClosed())
  721. {
  722. // script context may close after codegen call starts, consider this as aborted codegen
  723. hr = E_ABORT;
  724. }
  725. JITManager::HandleServerCallResult(hr, RemoteCallType::CodeGen);
  726. if (!PreReservedVirtualAllocWrapper::IsInRange((void*)this->scriptContext->GetThreadContext()->GetPreReservedRegionAddr(), (void*)jitWriteData.codeAddress))
  727. {
  728. this->scriptContext->GetJitFuncRangeCache()->AddFuncRange((void*)jitWriteData.codeAddress, jitWriteData.codeSize);
  729. }
  730. Assert(jitWriteData.codeAddress);
  731. Assert(jitWriteData.codeSize);
  732. }
  733. else
  734. {
  735. #if DBG
  736. size_t serializedRpcDataSize = 0;
  737. const unsigned char* serializedRpcData = nullptr;
  738. JITManager::SerializeRPCData(workItemData, &serializedRpcDataSize, &serializedRpcData);
  739. struct AutoFreeArray
  740. {
  741. const byte* arr = nullptr;
  742. size_t bufferSize = 0;
  743. ~AutoFreeArray() { HeapDeleteArray(bufferSize, arr); }
  744. } autoFreeArray;
  745. if (CONFIG_FLAG(EntryPointInfoRpcData) && epInfo != nullptr)
  746. {
  747. epInfo->SetSerializedRpcData(serializedRpcData, serializedRpcDataSize);
  748. }
  749. else
  750. {
  751. autoFreeArray.arr = serializedRpcData;
  752. autoFreeArray.bufferSize = serializedRpcDataSize;
  753. }
  754. #endif
  755. InProcCodeGenAllocators *const allocators =
  756. foreground ? EnsureForegroundAllocators(pageAllocator) : GetBackgroundAllocator(pageAllocator); // okay to do outside lock since the respective function is called only from one thread
  757. NoRecoverMemoryJitArenaAllocator jitArena(_u("JITArena"), pageAllocator, Js::Throw::OutOfMemory);
  758. #if DBG
  759. jitArena.SetNeedsDelayFreeList();
  760. #endif
  761. JITTimeWorkItem * jitWorkItem = Anew(&jitArena, JITTimeWorkItem, workItemData);
  762. #if !FLOATVAR
  763. CodeGenNumberAllocator* pNumberAllocator = nullptr;
  764. // the number allocator needs to be on the stack so that if we are doing foreground JIT
  765. // the chunk allocated from the recycler will be stacked pinned
  766. CodeGenNumberAllocator numberAllocator(
  767. foreground ? nullptr : scriptContext->GetThreadContext()->GetCodeGenNumberThreadAllocator(),
  768. scriptContext->GetRecycler());
  769. pNumberAllocator = &numberAllocator;
  770. #endif
  771. Js::ScriptContextProfiler *const codeGenProfiler =
  772. #ifdef PROFILE_EXEC
  773. foreground ? EnsureForegroundCodeGenProfiler() : GetBackgroundCodeGenProfiler(pageAllocator); // okay to do outside lock since the respective function is called only from one thread
  774. #else
  775. nullptr;
  776. #endif
  777. Func::Codegen(&jitArena, jitWorkItem, scriptContext->GetThreadContext(),
  778. scriptContext, &jitWriteData, epInfo, nullptr, jitWorkItem->GetPolymorphicInlineCacheInfo(), allocators,
  779. #if !FLOATVAR
  780. pNumberAllocator,
  781. #endif
  782. codeGenProfiler, !foreground);
  783. if (!this->scriptContext->GetThreadContext()->GetPreReservedVirtualAllocator()->IsInRange((void*)jitWriteData.codeAddress))
  784. {
  785. this->scriptContext->GetJitFuncRangeCache()->AddFuncRange((void*)jitWriteData.codeAddress, jitWriteData.codeSize);
  786. }
  787. }
  788. }
  789. void
  790. NativeCodeGenerator::CodeGen(PageAllocator * pageAllocator, CodeGenWorkItem* workItem, const bool foreground)
  791. {
  792. if(foreground)
  793. {
  794. // Func::Codegen has a lot of things on the stack, so probe the stack here instead
  795. PROBE_STACK_NO_DISPOSE(scriptContext, Js::Constants::MinStackJITCompile);
  796. }
  797. #if ENABLE_DEBUG_CONFIG_OPTIONS
  798. if (!foreground && Js::Configuration::Global.flags.IsEnabled(Js::InduceCodeGenFailureFlag))
  799. {
  800. if (NativeCodeGenerator::CodegenFailureSeed == 0)
  801. {
  802. // Initialize the seed
  803. NativeCodeGenerator::CodegenFailureSeed = Js::Configuration::Global.flags.InduceCodeGenFailureSeed;
  804. if (NativeCodeGenerator::CodegenFailureSeed == 0)
  805. {
  806. LARGE_INTEGER ctr;
  807. ::QueryPerformanceCounter(&ctr);
  808. NativeCodeGenerator::CodegenFailureSeed = ctr.HighPart ^ ctr.LowPart;
  809. srand((uint)NativeCodeGenerator::CodegenFailureSeed);
  810. }
  811. }
  812. int v = Math::Rand() % 100;
  813. if (v < Js::Configuration::Global.flags.InduceCodeGenFailure)
  814. {
  815. switch (v % 3)
  816. {
  817. case 0: Js::Throw::OutOfMemory(); break;
  818. case 1: throw Js::StackOverflowException(); break;
  819. case 2: throw Js::OperationAbortedException(); break;
  820. default:
  821. Assert(false);
  822. }
  823. }
  824. }
  825. #endif
  826. bool irviewerInstance = false;
  827. #ifdef IR_VIEWER
  828. irviewerInstance = true;
  829. #endif
  830. Assert(
  831. workItem->Type() != JsFunctionType ||
  832. irviewerInstance ||
  833. IsThunk(workItem->GetFunctionBody()->GetDirectEntryPoint(workItem->GetEntryPoint())) ||
  834. IsAsmJsCodeGenThunk(workItem->GetFunctionBody()->GetDirectEntryPoint(workItem->GetEntryPoint())));
  835. InterlockedExchangeAdd(&this->byteCodeSizeGenerated, workItem->GetByteCodeCount()); // must be interlocked because this data may be modified in the foreground and background thread concurrently
  836. Js::FunctionBody* body = workItem->GetFunctionBody();
  837. int nRegs = body->GetLocalsCount();
  838. AssertMsg((nRegs + 1) == (int)(SymID)(nRegs + 1), "SymID too small...");
  839. if (body->GetScriptContext()->IsClosed())
  840. {
  841. // Should not be jitting something in the foreground when the script context is actually closed
  842. Assert(IsBackgroundJIT() || !body->GetScriptContext()->IsActuallyClosed());
  843. throw Js::OperationAbortedException();
  844. }
  845. #if ENABLE_OOP_NATIVE_CODEGEN
  846. if (JITManager::GetJITManager()->IsOOPJITEnabled())
  847. {
  848. workItem->GetJITData()->nativeDataAddr = (__int3264)workItem->GetEntryPoint()->GetOOPNativeEntryPointData()->GetNativeDataBufferRef();
  849. }
  850. #endif
  851. // TODO: oop jit can we be more efficient here?
  852. ArenaAllocator alloc(_u("JitData"), pageAllocator, Js::Throw::OutOfMemory);
  853. auto& jitData = workItem->GetJITData()->jitData;
  854. jitData = AnewStructZ(&alloc, FunctionJITTimeDataIDL);
  855. auto codeGenData = workItem->RecyclableData()->JitTimeData();
  856. FunctionJITTimeInfo::BuildJITTimeData(&alloc, codeGenData, nullptr, workItem->GetJITData()->jitData, false, foreground);
  857. workItem->GetJITData()->profiledIterations = codeGenData->GetProfiledIterations();
  858. Js::EntryPointInfo * epInfo = workItem->GetEntryPoint();
  859. if (workItem->Type() == JsFunctionType)
  860. {
  861. auto funcEPInfo = (Js::FunctionEntryPointInfo*)epInfo;
  862. jitData->callsCountAddress = (uintptr_t)&funcEPInfo->callsCount;
  863. }
  864. else
  865. {
  866. workItem->GetJITData()->jittedLoopIterationsSinceLastBailoutAddr = (intptr_t)Js::FunctionBody::GetJittedLoopIterationsSinceLastBailoutAddress(epInfo);
  867. }
  868. jitData->sharedPropertyGuards = codeGenData->sharedPropertyGuards;
  869. jitData->sharedPropGuardCount = codeGenData->sharedPropertyGuardCount;
  870. JITOutputIDL jitWriteData = {0};
  871. #if !FLOATVAR
  872. workItem->GetJITData()->xProcNumberPageSegment = scriptContext->GetThreadContext()->GetXProcNumberPageSegmentManager()->GetFreeSegment(&alloc);
  873. #endif
  874. workItem->GetJITData()->globalThisAddr = (intptr_t)workItem->RecyclableData()->JitTimeData()->GetGlobalThisObject();
  875. LARGE_INTEGER start_time = { 0 };
  876. NativeCodeGenerator::LogCodeGenStart(workItem, &start_time);
  877. workItem->GetJITData()->startTime = (int64)start_time.QuadPart;
  878. CodeGen(pageAllocator, workItem->GetJITData(), jitWriteData, foreground, epInfo);
  879. if (JITManager::GetJITManager()->IsOOPJITEnabled() && PHASE_VERBOSE_TRACE(Js::BackEndPhase, workItem->GetFunctionBody()))
  880. {
  881. LARGE_INTEGER freq;
  882. LARGE_INTEGER end_time;
  883. QueryPerformanceCounter(&end_time);
  884. QueryPerformanceFrequency(&freq);
  885. Output::Print(
  886. _u("BackendMarshalOut - function: %s time:%8.6f mSec\r\n"),
  887. workItem->GetFunctionBody()->GetDisplayName(),
  888. (((double)((end_time.QuadPart - jitWriteData.startTime)* (double)1000.0 / (double)freq.QuadPart))) / (1));
  889. Output::Flush();
  890. }
  891. epInfo->GetNativeEntryPointData()->SetFrameHeight(jitWriteData.frameHeight);
  892. if (workItem->Type() == JsFunctionType)
  893. {
  894. Js::FunctionEntryPointInfo * funcEP = (Js::FunctionEntryPointInfo*)workItem->GetEntryPoint();
  895. funcEP->localVarSlotsOffset = jitWriteData.localVarSlotsOffset;
  896. funcEP->localVarChangedOffset = jitWriteData.localVarChangedOffset;
  897. }
  898. if (jitWriteData.hasJittedStackClosure != FALSE)
  899. {
  900. workItem->GetEntryPoint()->SetHasJittedStackClosure();
  901. }
  902. #if ENABLE_OOP_NATIVE_CODEGEN
  903. #if !FLOATVAR
  904. if (jitWriteData.numberPageSegments)
  905. {
  906. if (jitWriteData.numberPageSegments->pageAddress == 0)
  907. {
  908. midl_user_free(jitWriteData.numberPageSegments);
  909. jitWriteData.numberPageSegments = nullptr;
  910. }
  911. else
  912. {
  913. // TODO: when codegen fail, need to return the segment as well
  914. epInfo->GetOOPNativeEntryPointData()->SetNumberPageSegment(jitWriteData.numberPageSegments);
  915. }
  916. }
  917. #endif
  918. #endif
  919. #if ENABLE_OOP_NATIVE_CODEGEN
  920. if (JITManager::GetJITManager()->IsOOPJITEnabled())
  921. {
  922. if (jitWriteData.nativeDataFixupTable)
  923. {
  924. for (unsigned int i = 0; i < jitWriteData.nativeDataFixupTable->count; i++)
  925. {
  926. auto& record = jitWriteData.nativeDataFixupTable->fixupRecords[i];
  927. auto updateList = record.updateList;
  928. if (PHASE_TRACE1(Js::NativeCodeDataPhase))
  929. {
  930. Output::Print(_u("NativeCodeData Fixup: allocIndex:%d, len:%x, totalOffset:%x, startAddress:%p\n"),
  931. record.index, record.length, record.startOffset, jitWriteData.buffer->data + record.startOffset);
  932. }
  933. while (updateList)
  934. {
  935. void* addrToFixup = jitWriteData.buffer->data + record.startOffset + updateList->addrOffset;
  936. void* targetAddr = jitWriteData.buffer->data + updateList->targetTotalOffset;
  937. if (PHASE_TRACE1(Js::NativeCodeDataPhase))
  938. {
  939. Output::Print(_u("\tEntry: +%x %p(%p) ==> %p\n"), updateList->addrOffset, addrToFixup, *(void**)(addrToFixup), targetAddr);
  940. }
  941. *(void**)(addrToFixup) = targetAddr;
  942. auto current = updateList;
  943. updateList = updateList->next;
  944. midl_user_free(current);
  945. }
  946. }
  947. midl_user_free(jitWriteData.nativeDataFixupTable);
  948. jitWriteData.nativeDataFixupTable = nullptr;
  949. // change the address with the fixup information
  950. epInfo->GetOOPNativeEntryPointData()->SetNativeDataBuffer((char*)jitWriteData.buffer->data);
  951. #if DBG
  952. if (PHASE_TRACE1(Js::NativeCodeDataPhase))
  953. {
  954. Output::Print(_u("NativeCodeData Client Buffer: %p, len: %x\n"), jitWriteData.buffer->data, jitWriteData.buffer->len);
  955. }
  956. #endif
  957. }
  958. if (jitWriteData.throwMapCount > 0)
  959. {
  960. Js::ThrowMapEntry * throwMap = (Js::ThrowMapEntry *)(jitWriteData.buffer->data + jitWriteData.throwMapOffset);
  961. Js::SmallSpanSequenceIter iter;
  962. for (uint i = 0; i < jitWriteData.throwMapCount; ++i)
  963. {
  964. workItem->RecordNativeThrowMap(iter, throwMap[i].nativeBufferOffset, throwMap[i].statementIndex);
  965. }
  966. }
  967. epInfo->GetOOPNativeEntryPointData()->RecordInlineeFrameOffsetsInfo(jitWriteData.inlineeFrameOffsetArrayOffset, jitWriteData.inlineeFrameOffsetArrayCount);
  968. }
  969. #endif
  970. if (workItem->GetJitMode() != ExecutionMode::SimpleJit)
  971. {
  972. epInfo->GetJitTransferData()->SetRuntimeTypeRefs(jitWriteData.pinnedTypeRefs);
  973. epInfo->GetJitTransferData()->SetEquivalentTypeGuardOffsets(jitWriteData.equivalentTypeGuardOffsets);
  974. epInfo->GetJitTransferData()->SetTypeGuardTransferData(&jitWriteData);
  975. Assert(jitWriteData.ctorCacheEntries == nullptr || epInfo->GetNativeEntryPointData()->GetConstructorCacheCount() > 0);
  976. epInfo->GetJitTransferData()->SetCtorCacheTransferData(&jitWriteData);
  977. workItem->GetEntryPoint()->GetJitTransferData()->SetIsReady();
  978. }
  979. else
  980. {
  981. Assert(jitWriteData.pinnedTypeRefs == nullptr);
  982. }
  983. #if defined(TARGET_64)
  984. XDataAllocation * xdataInfo = HeapNewZ(XDataAllocation);
  985. xdataInfo->address = (byte*)jitWriteData.xdataAddr;
  986. XDataAllocator::Register(xdataInfo, jitWriteData.codeAddress, jitWriteData.codeSize);
  987. epInfo->GetNativeEntryPointData()->SetXDataInfo(xdataInfo);
  988. #endif
  989. #if defined(_M_ARM)
  990. // for in-proc jit we do registration in encoder
  991. if (JITManager::GetJITManager()->IsOOPJITEnabled())
  992. {
  993. XDataAllocation * xdataInfo = HeapNewZ(XDataAllocation);
  994. xdataInfo->pdataCount = jitWriteData.pdataCount;
  995. xdataInfo->xdataSize = jitWriteData.xdataSize;
  996. if (jitWriteData.buffer)
  997. {
  998. xdataInfo->address = jitWriteData.buffer->data + jitWriteData.xdataOffset;
  999. for (ushort i = 0; i < xdataInfo->pdataCount; ++i)
  1000. {
  1001. RUNTIME_FUNCTION *function = xdataInfo->GetPdataArray() + i;
  1002. // if flag is 0, then we have separate .xdata, for which we need to fixup the address
  1003. if (function->Flag == 0)
  1004. {
  1005. // UnwindData was set on server as the offset from the beginning of xdata buffer
  1006. function->UnwindData = (DWORD)(xdataInfo->address + function->UnwindData);
  1007. Assert(((DWORD)function->UnwindData & 0x3) == 0); // 4 byte aligned
  1008. }
  1009. }
  1010. }
  1011. else
  1012. {
  1013. xdataInfo->address = nullptr;
  1014. }
  1015. // unmask thumb mode from code address
  1016. XDataAllocator::Register(xdataInfo, jitWriteData.codeAddress & ~0x1, jitWriteData.codeSize);
  1017. epInfo->GetNativeEntryPointData()->SetXDataInfo(xdataInfo);
  1018. }
  1019. #endif
  1020. if (!CONFIG_FLAG(OOPCFGRegistration))
  1021. {
  1022. if (jitWriteData.thunkAddress)
  1023. {
  1024. scriptContext->GetThreadContext()->SetValidCallTargetForCFG((PVOID)jitWriteData.thunkAddress);
  1025. }
  1026. else
  1027. {
  1028. scriptContext->GetThreadContext()->SetValidCallTargetForCFG((PVOID)jitWriteData.codeAddress);
  1029. }
  1030. }
  1031. if (workItem->Type() == JsLoopBodyWorkItemType)
  1032. {
  1033. Assert(jitWriteData.thunkAddress == NULL);
  1034. ((JsLoopBodyCodeGen*)workItem)->SetCodeAddress(jitWriteData.codeAddress);
  1035. }
  1036. workItem->GetEntryPoint()->SetCodeGenRecorded((Js::JavascriptMethod)jitWriteData.thunkAddress, (Js::JavascriptMethod)jitWriteData.codeAddress, jitWriteData.codeSize, (void *)this);
  1037. #if DBG_DUMP
  1038. if (PHASE_DUMP(Js::EncoderPhase, workItem->GetFunctionBody()) && Js::Configuration::Global.flags.Verbose && !JITManager::GetJITManager()->IsOOPJITEnabled())
  1039. {
  1040. workItem->GetEntryPoint()->DumpNativeOffsetMaps();
  1041. workItem->GetEntryPoint()->DumpNativeThrowSpanSequence();
  1042. Output::Flush();
  1043. }
  1044. #endif
  1045. if (jitWriteData.hasBailoutInstr != FALSE)
  1046. {
  1047. body->SetHasBailoutInstrInJittedCode(true);
  1048. }
  1049. if (!jitWriteData.isInPrereservedRegion)
  1050. {
  1051. scriptContext->GetThreadContext()->ResetIsAllJITCodeInPreReservedRegion();
  1052. }
  1053. body->m_argUsedForBranch |= jitWriteData.argUsedForBranch;
  1054. if (body->HasDynamicProfileInfo())
  1055. {
  1056. if (jitWriteData.disableArrayCheckHoist)
  1057. {
  1058. body->GetAnyDynamicProfileInfo()->DisableArrayCheckHoist(workItem->Type() == JsLoopBodyWorkItemType);
  1059. }
  1060. if (jitWriteData.disableAggressiveIntTypeSpec)
  1061. {
  1062. body->GetAnyDynamicProfileInfo()->DisableAggressiveIntTypeSpec(workItem->Type() == JsLoopBodyWorkItemType);
  1063. }
  1064. if (jitWriteData.disableStackArgOpt)
  1065. {
  1066. body->GetAnyDynamicProfileInfo()->DisableStackArgOpt();
  1067. }
  1068. if (jitWriteData.disableSwitchOpt)
  1069. {
  1070. body->GetAnyDynamicProfileInfo()->DisableSwitchOpt();
  1071. }
  1072. if (jitWriteData.disableTrackCompoundedIntOverflow)
  1073. {
  1074. body->GetAnyDynamicProfileInfo()->DisableTrackCompoundedIntOverflow();
  1075. }
  1076. if (jitWriteData.disableMemOp)
  1077. {
  1078. body->GetAnyDynamicProfileInfo()->DisableMemOp();
  1079. }
  1080. }
  1081. if (jitWriteData.disableInlineApply)
  1082. {
  1083. body->SetDisableInlineApply(true);
  1084. }
  1085. if (jitWriteData.disableInlineSpread)
  1086. {
  1087. body->SetDisableInlineSpread(true);
  1088. }
  1089. #ifdef PROFILE_BAILOUT_RECORD_MEMORY
  1090. if (Js::Configuration::Global.flags.ProfileBailOutRecordMemory)
  1091. {
  1092. scriptContext->codeSize += workItem->GetEntryPoint()->GetCodeSize();
  1093. }
  1094. #endif
  1095. NativeCodeGenerator::LogCodeGenDone(workItem, &start_time);
  1096. #ifdef BGJIT_STATS
  1097. // Must be interlocked because the following data may be modified from the background and foreground threads concurrently
  1098. Js::ScriptContext *scriptContext = workItem->GetScriptContext();
  1099. if (workItem->Type() == JsFunctionType)
  1100. {
  1101. InterlockedExchangeAdd(&scriptContext->bytecodeJITCount, workItem->GetByteCodeCount());
  1102. InterlockedIncrement(&scriptContext->funcJITCount);
  1103. }
  1104. else if(workItem->Type() == JsLoopBodyWorkItemType)
  1105. {
  1106. InterlockedIncrement(&scriptContext->loopJITCount);
  1107. }
  1108. #endif
  1109. }
  1110. /* static */
  1111. void NativeCodeGenerator::LogCodeGenStart(CodeGenWorkItem * workItem, LARGE_INTEGER * start_time)
  1112. {
  1113. Js::FunctionBody * body = workItem->GetFunctionBody();
  1114. {
  1115. if (IS_JS_ETW(EventEnabledJSCRIPT_FUNCTION_JIT_START()))
  1116. {
  1117. WCHAR displayNameBuffer[256];
  1118. WCHAR* displayName = displayNameBuffer;
  1119. size_t sizeInChars = workItem->GetDisplayName(displayName, 256);
  1120. if (sizeInChars > 256)
  1121. {
  1122. displayName = HeapNewArray(WCHAR, sizeInChars);
  1123. workItem->GetDisplayName(displayName, 256);
  1124. }
  1125. JS_ETW(EventWriteJSCRIPT_FUNCTION_JIT_START(
  1126. body->GetFunctionNumber(),
  1127. displayName,
  1128. body->GetScriptContext(),
  1129. workItem->GetInterpretedCount(),
  1130. (const unsigned int)body->LengthInBytes(),
  1131. body->GetByteCodeCount(),
  1132. body->GetByteCodeInLoopCount(),
  1133. (int)workItem->GetJitMode()));
  1134. if (displayName != displayNameBuffer)
  1135. {
  1136. HeapDeleteArray(sizeInChars, displayName);
  1137. }
  1138. }
  1139. }
  1140. #if DBG_DUMP
  1141. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::BackEndPhase))
  1142. {
  1143. if (workItem->GetEntryPoint()->IsLoopBody())
  1144. {
  1145. Output::Print(_u("---BeginBackEnd: function: %s, loop:%d---\r\n"), body->GetDisplayName(), ((JsLoopBodyCodeGen*)workItem)->GetLoopNumber());
  1146. }
  1147. else
  1148. {
  1149. Output::Print(_u("---BeginBackEnd: function: %s---\r\n"), body->GetDisplayName());
  1150. }
  1151. Output::Flush();
  1152. }
  1153. #endif
  1154. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  1155. if (PHASE_TRACE(Js::BackEndPhase, body))
  1156. {
  1157. QueryPerformanceCounter(start_time);
  1158. if (workItem->GetEntryPoint()->IsLoopBody())
  1159. {
  1160. Output::Print(
  1161. _u("BeginBackEnd - function: %s (%s, line %u), loop: %u, mode: %S"),
  1162. body->GetDisplayName(),
  1163. body->GetDebugNumberSet(debugStringBuffer),
  1164. body->GetLineNumber(),
  1165. ((JsLoopBodyCodeGen*)workItem)->GetLoopNumber(),
  1166. ExecutionModeName(workItem->GetJitMode()));
  1167. if (body->GetIsAsmjsMode())
  1168. {
  1169. Output::Print(_u(" (Asmjs)\n"));
  1170. }
  1171. else
  1172. {
  1173. Output::Print(_u("\n"));
  1174. }
  1175. }
  1176. else
  1177. {
  1178. Output::Print(
  1179. _u("BeginBackEnd - function: %s (%s, line %u), mode: %S"),
  1180. body->GetDisplayName(),
  1181. body->GetDebugNumberSet(debugStringBuffer),
  1182. body->GetLineNumber(),
  1183. ExecutionModeName(workItem->GetJitMode()));
  1184. if (body->GetIsAsmjsMode())
  1185. {
  1186. Output::Print(_u(" (Asmjs)\n"));
  1187. }
  1188. else
  1189. {
  1190. Output::Print(_u("\n"));
  1191. }
  1192. }
  1193. Output::Flush();
  1194. }
  1195. #ifdef FIELD_ACCESS_STATS
  1196. if (PHASE_TRACE(Js::ObjTypeSpecPhase, body) || PHASE_TRACE(Js::EquivObjTypeSpecPhase, body))
  1197. {
  1198. if (workItem->RecyclableData()->JitTimeData()->inlineCacheStats)
  1199. {
  1200. auto stats = workItem->RecyclableData()->JitTimeData()->inlineCacheStats;
  1201. Output::Print(_u("ObjTypeSpec: jitting function %s (#%s): inline cache stats:\n"), body->GetDisplayName(), body->GetDebugNumberSet(debugStringBuffer));
  1202. Output::Print(_u(" overall: total %u, no profile info %u\n"), stats->totalInlineCacheCount, stats->noInfoInlineCacheCount);
  1203. Output::Print(_u(" mono: total %u, empty %u, cloned %u\n"),
  1204. stats->monoInlineCacheCount, stats->emptyMonoInlineCacheCount, stats->clonedMonoInlineCacheCount);
  1205. Output::Print(_u(" poly: total %u (high %u, low %u), null %u, empty %u, ignored %u, disabled %u, equivalent %u, non-equivalent %u, cloned %u\n"),
  1206. stats->polyInlineCacheCount, stats->highUtilPolyInlineCacheCount, stats->lowUtilPolyInlineCacheCount,
  1207. stats->nullPolyInlineCacheCount, stats->emptyPolyInlineCacheCount, stats->ignoredPolyInlineCacheCount, stats->disabledPolyInlineCacheCount,
  1208. stats->equivPolyInlineCacheCount, stats->nonEquivPolyInlineCacheCount, stats->clonedPolyInlineCacheCount);
  1209. }
  1210. else
  1211. {
  1212. Output::Print(_u("EquivObjTypeSpec: function %s (%s): inline cache stats unavailable\n"), body->GetDisplayName(), body->GetDebugNumberSet(debugStringBuffer));
  1213. }
  1214. Output::Flush();
  1215. }
  1216. #endif
  1217. }
  1218. /* static */
  1219. void NativeCodeGenerator::LogCodeGenDone(CodeGenWorkItem * workItem, LARGE_INTEGER * start_time)
  1220. {
  1221. Js::FunctionBody * body = workItem->GetFunctionBody();
  1222. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  1223. {
  1224. if (IS_JS_ETW(EventEnabledJSCRIPT_FUNCTION_JIT_STOP()))
  1225. {
  1226. WCHAR displayNameBuffer[256];
  1227. WCHAR* displayName = displayNameBuffer;
  1228. size_t sizeInChars = workItem->GetDisplayName(displayName, 256);
  1229. if (sizeInChars > 256)
  1230. {
  1231. displayName = HeapNewArray(WCHAR, sizeInChars);
  1232. workItem->GetDisplayName(displayName, 256);
  1233. }
  1234. void* entryPoint;
  1235. ptrdiff_t codeSize;
  1236. workItem->GetEntryPointAddress(&entryPoint, &codeSize);
  1237. JS_ETW(EventWriteJSCRIPT_FUNCTION_JIT_STOP(
  1238. body->GetFunctionNumber(),
  1239. displayName,
  1240. body->GetScriptContext(),
  1241. workItem->GetInterpretedCount(),
  1242. entryPoint,
  1243. codeSize));
  1244. if (displayName != displayNameBuffer)
  1245. {
  1246. HeapDeleteArray(sizeInChars, displayName);
  1247. }
  1248. }
  1249. }
  1250. #if DBG_DUMP
  1251. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::BackEndPhase))
  1252. {
  1253. Output::Print(_u("---EndBackEnd---\r\n"));
  1254. Output::Flush();
  1255. }
  1256. #endif
  1257. if (PHASE_TRACE(Js::BackEndPhase, body))
  1258. {
  1259. LARGE_INTEGER freq;
  1260. LARGE_INTEGER end_time;
  1261. QueryPerformanceCounter(&end_time);
  1262. QueryPerformanceFrequency(&freq);
  1263. if (workItem->GetEntryPoint()->IsLoopBody())
  1264. {
  1265. Output::Print(
  1266. _u("EndBackEnd - function: %s (%s, line %u), loop: %u, mode: %S, time:%8.6f mSec"),
  1267. body->GetDisplayName(),
  1268. body->GetDebugNumberSet(debugStringBuffer),
  1269. body->GetLineNumber(),
  1270. ((JsLoopBodyCodeGen*)workItem)->GetLoopNumber(),
  1271. ExecutionModeName(workItem->GetJitMode()),
  1272. (((double)((end_time.QuadPart - start_time->QuadPart)* (double)1000.0 / (double)freq.QuadPart))) / (1));
  1273. if (body->GetIsAsmjsMode())
  1274. {
  1275. Output::Print(_u(" (Asmjs)\n"));
  1276. }
  1277. else
  1278. {
  1279. Output::Print(_u("\n"));
  1280. }
  1281. }
  1282. else
  1283. {
  1284. Output::Print(
  1285. _u("EndBackEnd - function: %s (%s, line %u), mode: %S time:%8.6f mSec"),
  1286. body->GetDisplayName(),
  1287. body->GetDebugNumberSet(debugStringBuffer),
  1288. body->GetLineNumber(),
  1289. ExecutionModeName(workItem->GetJitMode()),
  1290. (((double)((end_time.QuadPart - start_time->QuadPart)* (double)1000.0 / (double)freq.QuadPart))) / (1));
  1291. if (body->GetIsAsmjsMode())
  1292. {
  1293. Output::Print(_u(" (Asmjs)\n"));
  1294. }
  1295. else
  1296. {
  1297. Output::Print(_u("\n"));
  1298. }
  1299. }
  1300. Output::Flush();
  1301. }
  1302. }
  1303. void NativeCodeGenerator::SetProfileMode(BOOL fSet)
  1304. {
  1305. this->SetNativeEntryPoint = fSet? Js::FunctionBody::ProfileSetNativeEntryPoint : Js::FunctionBody::DefaultSetNativeEntryPoint;
  1306. }
  1307. #if _M_IX86
  1308. __declspec(naked)
  1309. Js::Var
  1310. NativeCodeGenerator::CheckAsmJsCodeGenThunk(Js::RecyclableObject* function, Js::CallInfo callInfo, ...)
  1311. {
  1312. __asm
  1313. {
  1314. push ebp
  1315. mov ebp, esp
  1316. push function
  1317. call NativeCodeGenerator::CheckAsmJsCodeGen
  1318. #ifdef _CONTROL_FLOW_GUARD
  1319. // verify that the call target is valid
  1320. mov ecx, eax
  1321. call[__guard_check_icall_fptr]
  1322. mov eax, ecx
  1323. #endif
  1324. pop ebp
  1325. jmp eax
  1326. }
  1327. }
  1328. #elif _M_X64 || _M_ARM || _M_ARM64
  1329. // Do nothing: the implementation of NativeCodeGenerator::CheckCodeGenThunk is declared (appropriately decorated) in
  1330. // Backend\amd64\Thunks.asm and Backend\arm\Thunks.asm and Backend\arm64\Thunks.asm respectively.
  1331. #else
  1332. #error Not implemented.
  1333. #endif
  1334. #if _M_IX86
  1335. __declspec(naked)
  1336. Js::Var
  1337. NativeCodeGenerator::CheckCodeGenThunk(Js::RecyclableObject* function, Js::CallInfo callInfo, ...)
  1338. {
  1339. __asm
  1340. {
  1341. push ebp
  1342. mov ebp, esp
  1343. push [esp+8]
  1344. call NativeCodeGenerator::CheckCodeGen
  1345. #ifdef _CONTROL_FLOW_GUARD
  1346. // verify that the call target is valid
  1347. mov ecx, eax
  1348. call[__guard_check_icall_fptr]
  1349. mov eax, ecx
  1350. #endif
  1351. pop ebp
  1352. jmp eax
  1353. }
  1354. }
  1355. #elif _M_X64 || _M_ARM || _M_ARM64
  1356. // Do nothing: the implementation of NativeCodeGenerator::CheckCodeGenThunk is declared (appropriately decorated) in
  1357. // Backend\amd64\Thunks.asm and Backend\arm\Thunks.asm and Backend\arm64\Thunks.asm respectively.
  1358. #else
  1359. #error Not implemented.
  1360. #endif
  1361. bool
  1362. NativeCodeGenerator::IsThunk(Js::JavascriptMethod codeAddress)
  1363. {
  1364. return codeAddress == NativeCodeGenerator::CheckCodeGenThunk;
  1365. }
  1366. bool
  1367. NativeCodeGenerator::IsAsmJsCodeGenThunk(Js::JavascriptMethod codeAddress)
  1368. {
  1369. #ifdef ASMJS_PLAT
  1370. return codeAddress == NativeCodeGenerator::CheckAsmJsCodeGenThunk;
  1371. #else
  1372. return false;
  1373. #endif
  1374. }
  1375. CheckCodeGenFunction
  1376. NativeCodeGenerator::GetCheckCodeGenFunction(Js::JavascriptMethod codeAddress)
  1377. {
  1378. if (codeAddress == NativeCodeGenerator::CheckCodeGenThunk)
  1379. {
  1380. return NativeCodeGenerator::CheckCodeGen;
  1381. }
  1382. return nullptr;
  1383. }
  1384. Js::JavascriptMethod
  1385. NativeCodeGenerator::CheckAsmJsCodeGen(Js::ScriptFunction * function)
  1386. {
  1387. Assert(function);
  1388. Js::FunctionBody *functionBody = function->GetFunctionBody();
  1389. Js::ScriptContext *scriptContext = functionBody->GetScriptContext();
  1390. NativeCodeGenerator *nativeCodeGen = scriptContext->GetNativeCodeGenerator();
  1391. Assert(scriptContext->GetThreadContext()->IsScriptActive());
  1392. Assert(scriptContext->GetThreadContext()->IsInScript());
  1393. AssertOrFailFastMsg(!functionBody->IsWasmFunction() || functionBody->GetByteCodeCount() > 0, "Wasm function should be parsed by now");
  1394. // Load the entry point here to validate it got changed afterwards
  1395. Js::FunctionEntryPointInfo* entryPoint = function->GetFunctionEntryPointInfo();
  1396. #if ENABLE_DEBUG_CONFIG_OPTIONS
  1397. if ((PHASE_ON1(Js::AsmJsJITTemplatePhase) && CONFIG_FLAG(MaxTemplatizedJitRunCount) >= 0) || (!PHASE_ON1(Js::AsmJsJITTemplatePhase) && CONFIG_FLAG(MaxAsmJsInterpreterRunCount) >= 0))
  1398. {
  1399. nativeCodeGen->Processor()->PrioritizeJobAndWait(nativeCodeGen, entryPoint, function);
  1400. } else
  1401. #endif
  1402. if (!nativeCodeGen->Processor()->PrioritizeJob(nativeCodeGen, entryPoint, function))
  1403. {
  1404. if (PHASE_TRACE1(Js::AsmjsEntryPointInfoPhase))
  1405. {
  1406. Output::Print(_u("Codegen not done yet for function: %s, Entrypoint is CheckAsmJsCodeGenThunk\n"), function->GetFunctionBody()->GetDisplayName());
  1407. }
  1408. return functionBody->GetOriginalEntryPoint();
  1409. }
  1410. if (PHASE_TRACE1(Js::AsmjsEntryPointInfoPhase))
  1411. {
  1412. Output::Print(_u("CodeGen Done for function: %s, Changing Entrypoint to Full JIT\n"), function->GetFunctionBody()->GetDisplayName());
  1413. }
  1414. // we will need to set the functionbody external and asmjs entrypoint to the fulljit entrypoint
  1415. return CheckCodeGenDone(functionBody, entryPoint, function);
  1416. }
  1417. Js::JavascriptMethod
  1418. NativeCodeGenerator::CheckCodeGen(Js::ScriptFunction * function)
  1419. {
  1420. Assert(function);
  1421. Assert(function->GetEntryPoint() == NativeCodeGenerator::CheckCodeGenThunk
  1422. || Js::CrossSite::IsThunk(function->GetEntryPoint()));
  1423. // We are not expecting non-deserialized functions here; Error if it hasn't been deserialized by this point
  1424. Js::FunctionBody *functionBody = function->GetFunctionBody();
  1425. Js::ScriptContext *scriptContext = functionBody->GetScriptContext();
  1426. NativeCodeGenerator *nativeCodeGen = scriptContext->GetNativeCodeGenerator();
  1427. Assert(scriptContext->GetThreadContext()->IsScriptActive());
  1428. Assert(scriptContext->GetThreadContext()->IsInScript());
  1429. // Load the entry point here to validate it got changed afterwards
  1430. Js::JavascriptMethod originalEntryPoint = functionBody->GetOriginalEntryPoint();
  1431. Js::FunctionEntryPointInfo* entryPoint = function->GetFunctionEntryPointInfo();
  1432. Js::FunctionEntryPointInfo *const defaultEntryPointInfo = functionBody->GetDefaultFunctionEntryPointInfo();
  1433. if(entryPoint != defaultEntryPointInfo)
  1434. {
  1435. // Switch to the latest entry point info
  1436. function->UpdateThunkEntryPoint(defaultEntryPointInfo, functionBody->GetDirectEntryPoint(defaultEntryPointInfo));
  1437. const Js::JavascriptMethod defaultDirectEntryPoint = functionBody->GetDirectEntryPoint(defaultEntryPointInfo);
  1438. if(!IsThunk(defaultDirectEntryPoint))
  1439. {
  1440. return defaultDirectEntryPoint;
  1441. }
  1442. entryPoint = defaultEntryPointInfo;
  1443. }
  1444. // If a transition to JIT needs to be forced, JIT right away
  1445. if(Js::Configuration::Global.flags.EnforceExecutionModeLimits &&
  1446. functionBody->GetExecutionMode() != ExecutionMode::SimpleJit &&
  1447. functionBody->TryTransitionToJitExecutionMode())
  1448. {
  1449. nativeCodeGen->Processor()->PrioritizeJobAndWait(nativeCodeGen, entryPoint, function);
  1450. return CheckCodeGenDone(functionBody, entryPoint, function);
  1451. }
  1452. if(!nativeCodeGen->Processor()->PrioritizeJob(nativeCodeGen, entryPoint, function))
  1453. {
  1454. #if defined(ENABLE_SCRIPT_PROFILING) || defined(ENABLE_SCRIPT_DEBUGGING)
  1455. #define originalEntryPoint_IS_ProfileDeferredParsingThunk \
  1456. (originalEntryPoint == ProfileDeferredParsingThunk)
  1457. #else
  1458. #define originalEntryPoint_IS_ProfileDeferredParsingThunk \
  1459. false
  1460. #endif
  1461. // Job was not yet processed
  1462. // originalEntryPoint is the last known good entry point for the function body. Here we verify that
  1463. // it either corresponds with this codegen episode (identified by function->entryPointIndex) of the function body
  1464. // or one that was scheduled after. In the latter case originalEntryPoint will get updated if and when
  1465. // that last episode completes successfully.
  1466. Assert(functionBody->GetDefaultEntryPointInfo() == function->GetEntryPointInfo() &&
  1467. (
  1468. originalEntryPoint == DefaultEntryThunk
  1469. || originalEntryPoint == Js::InterpreterStackFrame::StaticInterpreterThunk
  1470. || scriptContext->IsDynamicInterpreterThunk(originalEntryPoint)
  1471. || originalEntryPoint_IS_ProfileDeferredParsingThunk
  1472. || originalEntryPoint == DefaultDeferredParsingThunk
  1473. || (
  1474. functionBody->GetSimpleJitEntryPointInfo() &&
  1475. originalEntryPoint == functionBody->GetSimpleJitEntryPointInfo()->GetNativeEntrypoint()
  1476. )
  1477. ) ||
  1478. functionBody->GetDefaultFunctionEntryPointInfo()->entryPointIndex > function->GetFunctionEntryPointInfo()->entryPointIndex);
  1479. return (scriptContext->CurrentThunk == ProfileEntryThunk) ? ProfileEntryThunk : originalEntryPoint;
  1480. }
  1481. return CheckCodeGenDone(functionBody, entryPoint, function);
  1482. }
  1483. Js::JavascriptMethod
  1484. NativeCodeGenerator::CheckCodeGenDone(
  1485. Js::FunctionBody *const functionBody,
  1486. Js::FunctionEntryPointInfo *const entryPointInfo,
  1487. Js::ScriptFunction * function)
  1488. {
  1489. Assert(!function || function->GetFunctionBody() == functionBody);
  1490. Assert(!function || function->GetFunctionEntryPointInfo() == entryPointInfo);
  1491. // Job was processed or failed and cleaned up
  1492. // We won't call CheckCodeGenDone if the job is still pending since
  1493. // PrioritizeJob will return false
  1494. Assert(entryPointInfo->IsCodeGenDone() || entryPointInfo->IsCleanedUp() || entryPointInfo->IsPendingCleanup());
  1495. if (!functionBody->GetHasBailoutInstrInJittedCode() && functionBody->GetHasAllocatedLoopHeaders()
  1496. #ifdef ASMJS_PLAT
  1497. && (!functionBody->GetIsAsmJsFunction() || !(((Js::FunctionEntryPointInfo*)functionBody->GetDefaultEntryPointInfo())->GetIsTJMode()))
  1498. #endif
  1499. )
  1500. {
  1501. if (functionBody->GetCanReleaseLoopHeaders())
  1502. {
  1503. functionBody->ReleaseLoopHeaders();
  1504. }
  1505. else
  1506. {
  1507. functionBody->SetPendingLoopHeaderRelease(true);
  1508. }
  1509. }
  1510. Js::ScriptContext *scriptContext = functionBody->GetScriptContext();
  1511. if (!functionBody->GetNativeEntryPointUsed())
  1512. {
  1513. #ifdef BGJIT_STATS
  1514. scriptContext->jitCodeUsed += functionBody->GetByteCodeCount();
  1515. scriptContext->funcJitCodeUsed++;
  1516. #endif
  1517. functionBody->SetNativeEntryPointUsed(true);
  1518. }
  1519. // Replace the entry point
  1520. Js::JavascriptMethod jsMethod;
  1521. if (!entryPointInfo->IsCodeGenDone())
  1522. {
  1523. if (entryPointInfo->IsPendingCleanup())
  1524. {
  1525. entryPointInfo->Cleanup(false /* isShutdown */, true /* capture cleanup stack */);
  1526. }
  1527. // Do not profile WebAssembly functions
  1528. jsMethod = (functionBody->GetScriptContext()->CurrentThunk == ProfileEntryThunk
  1529. && !functionBody->IsWasmFunction()) ? ProfileEntryThunk : functionBody->GetOriginalEntryPoint();
  1530. entryPointInfo->jsMethod = jsMethod;
  1531. }
  1532. else
  1533. {
  1534. scriptContext->GetNativeCodeGenerator()->SetNativeEntryPoint(
  1535. entryPointInfo,
  1536. functionBody,
  1537. entryPointInfo->GetNativeEntrypoint());
  1538. jsMethod = entryPointInfo->jsMethod;
  1539. Assert(!functionBody->NeedEnsureDynamicProfileInfo() || jsMethod == Js::DynamicProfileInfo::EnsureDynamicProfileInfoThunk || functionBody->GetIsAsmjsMode());
  1540. if (functionBody->GetIsAsmjsMode() && functionBody->NeedEnsureDynamicProfileInfo())
  1541. {
  1542. functionBody->EnsureDynamicProfileInfo();
  1543. }
  1544. }
  1545. Assert(!IsThunk(jsMethod));
  1546. if(function)
  1547. {
  1548. function->UpdateThunkEntryPoint(entryPointInfo, jsMethod);
  1549. }
  1550. // call the direct entry point, which will ensure dynamic profile info if necessary
  1551. return jsMethod;
  1552. }
  1553. CodeGenWorkItem *
  1554. NativeCodeGenerator::GetJob(Js::EntryPointInfo * const entryPoint) const
  1555. {
  1556. ASSERT_THREAD();
  1557. Assert(entryPoint);
  1558. return entryPoint->GetWorkItem();
  1559. }
  1560. bool
  1561. NativeCodeGenerator::WasAddedToJobProcessor(JsUtil::Job *const job) const
  1562. {
  1563. // This function is called from inside the lock
  1564. ASSERT_THREAD();
  1565. Assert(job);
  1566. return static_cast<CodeGenWorkItem *>(job)->IsInJitQueue();
  1567. }
  1568. bool
  1569. NativeCodeGenerator::ShouldProcessInForeground(const bool willWaitForJob, const unsigned int numJobsInQueue) const
  1570. {
  1571. // This function is called from inside the lock
  1572. ASSERT_THREAD();
  1573. // Process the job synchronously in the foreground thread if we're waiting for the job to be processed, or if the background
  1574. // job queue is long enough and this native code generator is optimized for many instances (web workers)
  1575. return
  1576. willWaitForJob ||
  1577. (numJobsInQueue > (uint)CONFIG_FLAG(HybridFgJitBgQueueLengthThreshold) &&
  1578. (CONFIG_FLAG(HybridFgJit) || isOptimizedForManyInstances));
  1579. }
  1580. void
  1581. NativeCodeGenerator::PrioritizedButNotYetProcessed(JsUtil::Job *const job)
  1582. {
  1583. // This function is called from inside the lock
  1584. ASSERT_THREAD();
  1585. Assert(job);
  1586. CodeGenWorkItem *const codeGenWorkItem = static_cast<CodeGenWorkItem *>(job);
  1587. if(codeGenWorkItem->Type() == JsFunctionType && codeGenWorkItem->IsInJitQueue())
  1588. {
  1589. #ifdef BGJIT_STATS
  1590. codeGenWorkItem->GetScriptContext()->interpretedCallsHighPri++;
  1591. #endif
  1592. if(codeGenWorkItem->GetJitMode() == ExecutionMode::FullJit)
  1593. {
  1594. QueuedFullJitWorkItem *const queuedFullJitWorkItem = codeGenWorkItem->GetQueuedFullJitWorkItem();
  1595. if(queuedFullJitWorkItem)
  1596. {
  1597. queuedFullJitWorkItems.MoveToBeginning(queuedFullJitWorkItem);
  1598. }
  1599. }
  1600. }
  1601. }
  1602. void
  1603. NativeCodeGenerator::BeforeWaitForJob(Js::EntryPointInfo *const entryPoint) const
  1604. {
  1605. ASSERT_THREAD();
  1606. Assert(entryPoint);
  1607. #ifdef PROFILE_EXEC
  1608. ProfileBegin(this->foregroundCodeGenProfiler, Js::DelayPhase);
  1609. #endif
  1610. }
  1611. void
  1612. NativeCodeGenerator::AfterWaitForJob(Js::EntryPointInfo *const entryPoint) const
  1613. {
  1614. ASSERT_THREAD();
  1615. Assert(entryPoint);
  1616. #ifdef PROFILE_EXEC
  1617. ProfileEnd(this->foregroundCodeGenProfiler, Js::DelayPhase);
  1618. #endif
  1619. }
  1620. /*
  1621. * A workitem exceeds JIT limits if we've already generated MaxThreadJITCodeHeapSize
  1622. * (currently 7 MB) of code on this thread or MaxProcessJITCodeHeapSize (currently 55 MB)
  1623. * in the process. In real world websites we rarely (if at all) hit this limit.
  1624. * Also, if this workitem's byte code size is in excess of MaxJITFunctionBytecodeSize instructions,
  1625. * it exceeds the JIT limits
  1626. */
  1627. bool
  1628. NativeCodeGenerator::WorkItemExceedsJITLimits(CodeGenWorkItem *const codeGenWork)
  1629. {
  1630. return
  1631. (codeGenWork->GetScriptContext()->GetThreadContext()->GetCodeSize() >= Js::Constants::MaxThreadJITCodeHeapSize) ||
  1632. (ThreadContext::GetProcessCodeSize() >= Js::Constants::MaxProcessJITCodeHeapSize) ||
  1633. (codeGenWork->GetByteCodeLength() >= (uint)CONFIG_FLAG(MaxJITFunctionBytecodeByteLength)) ||
  1634. (codeGenWork->GetByteCodeCount() >= (uint)CONFIG_FLAG(MaxJITFunctionBytecodeCount));
  1635. }
  1636. bool
  1637. NativeCodeGenerator::Process(JsUtil::Job *const job, JsUtil::ParallelThreadData *threadData)
  1638. {
  1639. const bool foreground = !threadData;
  1640. PageAllocator *pageAllocator;
  1641. if (foreground)
  1642. {
  1643. pageAllocator = scriptContext->GetThreadContext()->GetPageAllocator();
  1644. }
  1645. else
  1646. {
  1647. pageAllocator = threadData->GetPageAllocator();
  1648. }
  1649. CodeGenWorkItem *const codeGenWork = static_cast<CodeGenWorkItem *>(job);
  1650. switch (codeGenWork->Type())
  1651. {
  1652. case JsLoopBodyWorkItemType:
  1653. {
  1654. JsLoopBodyCodeGen* loopBodyCodeGenWorkItem = (JsLoopBodyCodeGen*)codeGenWork;
  1655. Js::FunctionBody* fn = loopBodyCodeGenWorkItem->GetFunctionBody();
  1656. if (fn->GetNativeEntryPointUsed() && fn->GetCanReleaseLoopHeaders()
  1657. #ifdef ASMJS_PLAT
  1658. && (!fn->GetIsAsmJsFunction() || !(loopBodyCodeGenWorkItem->loopHeader->GetCurrentEntryPointInfo()->GetIsTJMode()))
  1659. #endif
  1660. )
  1661. {
  1662. loopBodyCodeGenWorkItem->loopHeader->ResetInterpreterCount();
  1663. return false;
  1664. }
  1665. // Unless we're in a ForceNative configuration, ignore this workitem if it exceeds JIT limits
  1666. if (fn->ForceJITLoopBody() || !WorkItemExceedsJITLimits(codeGenWork))
  1667. {
  1668. CodeGen(pageAllocator, codeGenWork, foreground);
  1669. return true;
  1670. }
  1671. Js::EntryPointInfo * entryPoint = loopBodyCodeGenWorkItem->GetEntryPoint();
  1672. entryPoint->SetJITCapReached();
  1673. return false;
  1674. }
  1675. case JsFunctionType:
  1676. {
  1677. // Unless we're in a ForceNative configuration, ignore this workitem if it exceeds JIT limits
  1678. if (IS_PREJIT_ON() || Js::Configuration::Global.flags.ForceNative || !WorkItemExceedsJITLimits(codeGenWork))
  1679. {
  1680. CodeGen(pageAllocator, codeGenWork, foreground);
  1681. return true;
  1682. }
  1683. #if ENABLE_DEBUG_CONFIG_OPTIONS
  1684. job->failureReason = Job::FailureReason::ExceedJITLimit;
  1685. #endif
  1686. return false;
  1687. }
  1688. default:
  1689. Assume(UNREACHED);
  1690. }
  1691. #if ENABLE_DEBUG_CONFIG_OPTIONS
  1692. job->failureReason = Job::FailureReason::Unknown;
  1693. #endif
  1694. return false;
  1695. }
  1696. void
  1697. NativeCodeGenerator::Prioritize(JsUtil::Job *const job, const bool forceAddJobToProcessor, void* function)
  1698. {
  1699. // This function is called from inside the lock
  1700. ASSERT_THREAD();
  1701. Assert(job);
  1702. Assert(static_cast<const CodeGenWorkItem *>(job)->Type() == CodeGenWorkItemType::JsFunctionType);
  1703. Assert(!WasAddedToJobProcessor(job));
  1704. JsFunctionCodeGen *const workItem = static_cast<JsFunctionCodeGen *>(job);
  1705. Js::FunctionBody *const functionBody = workItem->GetFunctionBody();
  1706. Assert(workItem->GetEntryPoint() == functionBody->GetDefaultFunctionEntryPointInfo());
  1707. ExecutionMode jitMode;
  1708. if (functionBody->GetIsAsmjsMode())
  1709. {
  1710. jitMode = ExecutionMode::FullJit;
  1711. functionBody->SetAsmJsExecutionMode();
  1712. }
  1713. else
  1714. {
  1715. if (!forceAddJobToProcessor)
  1716. {
  1717. if (!functionBody->TryTransitionToJitExecutionMode())
  1718. {
  1719. return;
  1720. }
  1721. #if ENABLE_OOP_NATIVE_CODEGEN
  1722. // If for some reason OOP JIT isn't connected (e.g. it crashed), don't attempt to JIT
  1723. if (JITManager::GetJITManager()->IsOOPJITEnabled() && !JITManager::GetJITManager()->IsConnected())
  1724. {
  1725. return;
  1726. }
  1727. #endif
  1728. }
  1729. jitMode = functionBody->GetExecutionMode();
  1730. Assert(jitMode == ExecutionMode::SimpleJit || jitMode == ExecutionMode::FullJit);
  1731. }
  1732. workItems.Unlink(workItem);
  1733. workItem->SetJitMode(jitMode);
  1734. try
  1735. {
  1736. // Prioritize full JIT work items over simple JIT work items. This simple solution seems sufficient for now, but it
  1737. // might be better to use a priority queue if it becomes necessary to prioritize recent simple JIT work items relative
  1738. // to the older simple JIT work items.
  1739. AddToJitQueue(
  1740. workItem,
  1741. jitMode == ExecutionMode::FullJit || queuedFullJitWorkItemCount == 0 /* prioritize */,
  1742. false /* lock */,
  1743. function);
  1744. }
  1745. catch (...)
  1746. {
  1747. // Add the item back to the list if AddToJitQueue throws. The position in the list is not important.
  1748. workItem->ResetJitMode();
  1749. workItems.LinkToEnd(workItem);
  1750. throw;
  1751. }
  1752. }
  1753. ExecutionMode NativeCodeGenerator::PrejitJitMode(Js::FunctionBody *const functionBody)
  1754. {
  1755. Assert(IS_PREJIT_ON() || functionBody->GetIsAsmjsMode());
  1756. Assert(functionBody->DoSimpleJit() || !PHASE_OFF(Js::FullJitPhase, functionBody));
  1757. // Prefer full JIT for prejitting unless it's off or simple JIT is forced
  1758. return
  1759. !PHASE_OFF(Js::FullJitPhase, functionBody) && !(PHASE_FORCE(Js::Phase::SimpleJitPhase, functionBody) && functionBody->DoSimpleJit())
  1760. ? ExecutionMode::FullJit
  1761. : ExecutionMode::SimpleJit;
  1762. }
  1763. void
  1764. NativeCodeGenerator::UpdateQueueForDebugMode()
  1765. {
  1766. Assert(!this->hasUpdatedQForDebugMode);
  1767. // If we're going to debug mode, drain the job processors queue of
  1768. // all jobs belonging this native code generator
  1769. // JobProcessed will be called for existing jobs, and in debug mode
  1770. // that method will simply add them back to the NativeCodeGen's queue
  1771. Processor()->RemoveManager(this);
  1772. this->hasUpdatedQForDebugMode = true;
  1773. Processor()->AddManager(this);
  1774. }
  1775. void
  1776. NativeCodeGenerator::JobProcessed(JsUtil::Job *const job, const bool succeeded)
  1777. {
  1778. // This function is called from inside the lock
  1779. Assert(job);
  1780. CodeGenWorkItem *workItem = static_cast<CodeGenWorkItem *>(job);
  1781. class AutoCleanup
  1782. {
  1783. private:
  1784. Js::ScriptContext *const scriptContext;
  1785. Js::CodeGenRecyclableData *const recyclableData;
  1786. public:
  1787. AutoCleanup(Js::ScriptContext *const scriptContext, Js::CodeGenRecyclableData *const recyclableData)
  1788. : scriptContext(scriptContext), recyclableData(recyclableData)
  1789. {
  1790. Assert(scriptContext);
  1791. }
  1792. ~AutoCleanup()
  1793. {
  1794. if(recyclableData)
  1795. {
  1796. scriptContext->GetThreadContext()->UnregisterCodeGenRecyclableData(recyclableData);
  1797. }
  1798. }
  1799. } autoCleanup(scriptContext, workItem->RecyclableData());
  1800. const ExecutionMode jitMode = workItem->GetJitMode();
  1801. if(jitMode == ExecutionMode::FullJit && workItem->IsInJitQueue())
  1802. {
  1803. QueuedFullJitWorkItem *const queuedFullJitWorkItem = workItem->GetQueuedFullJitWorkItem();
  1804. if(queuedFullJitWorkItem)
  1805. {
  1806. queuedFullJitWorkItems.Unlink(queuedFullJitWorkItem);
  1807. --queuedFullJitWorkItemCount;
  1808. }
  1809. }
  1810. Js::FunctionBody* functionBody = nullptr;
  1811. CodeGenWorkItemType workitemType = workItem->Type();
  1812. if (workitemType == JsFunctionType)
  1813. {
  1814. JsFunctionCodeGen * functionCodeGen = (JsFunctionCodeGen *)workItem;
  1815. functionBody = functionCodeGen->GetFunctionBody();
  1816. if (succeeded)
  1817. {
  1818. Js::FunctionEntryPointInfo* entryPointInfo = static_cast<Js::FunctionEntryPointInfo*>(functionCodeGen->GetEntryPoint());
  1819. entryPointInfo->SetJitMode(jitMode);
  1820. entryPointInfo->SetCodeGenDone();
  1821. }
  1822. else
  1823. {
  1824. #if DBG
  1825. functionBody->m_nativeEntryPointIsInterpreterThunk = true;
  1826. #endif
  1827. // It's okay if the entry point has been reclaimed at this point
  1828. // since the job failed anyway so the entry point should never get used
  1829. // If it's still around, clean it up. If not, its finalizer would clean
  1830. // it up anyway.
  1831. Js::EntryPointInfo* entryPointInfo = functionCodeGen->GetEntryPoint();
  1832. if (entryPointInfo)
  1833. {
  1834. #if ENABLE_ENTRYPOINT_CLEANUP_TRACE
  1835. #if ENABLE_DEBUG_CONFIG_OPTIONS
  1836. switch (job->failureReason)
  1837. {
  1838. case Job::FailureReason::OOM: entryPointInfo->SetCleanupReason(Js::EntryPointInfo::CleanupReason::CodeGenFailedOOM); break;
  1839. case Job::FailureReason::StackOverflow: entryPointInfo->SetCleanupReason(Js::EntryPointInfo::CleanupReason::CodeGenFailedStackOverflow); break;
  1840. case Job::FailureReason::Aborted: entryPointInfo->SetCleanupReason(Js::EntryPointInfo::CleanupReason::CodeGenFailedAborted); break;
  1841. case Job::FailureReason::ExceedJITLimit: entryPointInfo->SetCleanupReason(Js::EntryPointInfo::CleanupReason::CodeGenFailedExceedJITLimit); break;
  1842. case Job::FailureReason::Unknown: entryPointInfo->SetCleanupReason(Js::EntryPointInfo::CleanupReason::CodeGenFailedUnknown); break;
  1843. default: Assert(job->failureReason == Job::FailureReason::NotFailed);
  1844. }
  1845. #endif
  1846. #endif
  1847. entryPointInfo->SetPendingCleanup();
  1848. }
  1849. functionCodeGen->OnWorkItemProcessFail(this);
  1850. }
  1851. InterlockedDecrement(&pendingCodeGenWorkItems);
  1852. HeapDelete(functionCodeGen);
  1853. }
  1854. else if (workitemType == JsLoopBodyWorkItemType)
  1855. {
  1856. JsLoopBodyCodeGen * loopBodyCodeGen = (JsLoopBodyCodeGen*)workItem;
  1857. functionBody = loopBodyCodeGen->GetFunctionBody();
  1858. Js::EntryPointInfo * entryPoint = loopBodyCodeGen->GetEntryPoint();
  1859. if (succeeded)
  1860. {
  1861. Assert(loopBodyCodeGen->GetCodeAddress() != NULL);
  1862. uint loopNum = loopBodyCodeGen->GetJITData()->loopNumber;
  1863. functionBody->SetLoopBodyEntryPoint(loopBodyCodeGen->loopHeader, entryPoint, (Js::JavascriptMethod)loopBodyCodeGen->GetCodeAddress(), loopNum);
  1864. entryPoint->SetCodeGenDone();
  1865. }
  1866. else
  1867. {
  1868. // We re-use failed loop body entry points.
  1869. // The loop body entry point could have been cleaned up if the parent function JITed,
  1870. // in which case we don't want to reset it.
  1871. if (entryPoint && !entryPoint->IsCleanedUp())
  1872. {
  1873. entryPoint->Reset(!entryPoint->IsJITCapReached()); // reset state to NotScheduled if JIT cap hasn't been reached
  1874. }
  1875. loopBodyCodeGen->OnWorkItemProcessFail(this);
  1876. }
  1877. HeapDelete(loopBodyCodeGen);
  1878. }
  1879. else
  1880. {
  1881. AssertMsg(false, "Unknown work item type");
  1882. }
  1883. }
  1884. void
  1885. NativeCodeGenerator::UpdateJITState()
  1886. {
  1887. if (JITManager::GetJITManager()->IsOOPJITEnabled())
  1888. {
  1889. // TODO: OOP JIT, move server calls to background thread to reduce foreground thread delay
  1890. if (!this->scriptContext->GetRemoteScriptAddr() || !JITManager::GetJITManager()->IsConnected())
  1891. {
  1892. return;
  1893. }
  1894. if (scriptContext->GetThreadContext()->JITNeedsPropUpdate())
  1895. {
  1896. typedef BVSparseNode<JitArenaAllocator> BVSparseNode;
  1897. CompileAssert(sizeof(BVSparseNode) == sizeof(BVSparseNodeIDL));
  1898. BVSparseNodeIDL * bvHead = (BVSparseNodeIDL*)scriptContext->GetThreadContext()->GetJITNumericProperties()->head;
  1899. HRESULT hr = JITManager::GetJITManager()->UpdatePropertyRecordMap(scriptContext->GetThreadContext()->GetRemoteThreadContextAddr(), bvHead);
  1900. JITManager::HandleServerCallResult(hr, RemoteCallType::StateUpdate);
  1901. scriptContext->GetThreadContext()->ResetJITNeedsPropUpdate();
  1902. }
  1903. }
  1904. }
  1905. JsUtil::Job *
  1906. NativeCodeGenerator::GetJobToProcessProactively()
  1907. {
  1908. ASSERT_THREAD();
  1909. // Look for work, starting with high priority items first, and above LowPri
  1910. CodeGenWorkItem* workItem = workItems.Head();
  1911. while(workItem != nullptr)
  1912. {
  1913. if(workItem->ShouldSpeculativelyJit(this->byteCodeSizeGenerated))
  1914. {
  1915. workItem->SetJitMode(ExecutionMode::FullJit);
  1916. // Note: This gives a perf regression in fre build, but it is useful for debugging and won't be there for the final build
  1917. // anyway, so I left it in.
  1918. if (PHASE_TRACE(Js::DelayPhase, workItem->GetFunctionBody())) {
  1919. OUTPUT_TRACE(Js::DelayPhase, _u("ScriptContext: 0x%p, Speculative JIT: %-25s, Byte code generated: %d \n"),
  1920. this->scriptContext, workItem->GetFunctionBody()->GetExternalDisplayName(), this->byteCodeSizeGenerated);
  1921. }
  1922. Js::FunctionBody *fn = workItem->GetFunctionBody();
  1923. Js::EntryPointInfo *entryPoint = workItem->GetEntryPoint();
  1924. const auto recyclableData = GatherCodeGenData(fn, fn, entryPoint, workItem);
  1925. workItems.Unlink(workItem);
  1926. workItem->SetRecyclableData(recyclableData);
  1927. {
  1928. AutoOptionalCriticalSection lock(Processor()->GetCriticalSection());
  1929. scriptContext->GetThreadContext()->RegisterCodeGenRecyclableData(recyclableData);
  1930. }
  1931. #ifdef BGJIT_STATS
  1932. scriptContext->speculativeJitCount++;
  1933. #endif
  1934. QueuedFullJitWorkItem *const queuedFullJitWorkItem = workItem->EnsureQueuedFullJitWorkItem();
  1935. if(queuedFullJitWorkItem) // ignore OOM, this work item just won't be removed from the job processor's queue
  1936. {
  1937. queuedFullJitWorkItems.LinkToBeginning(queuedFullJitWorkItem);
  1938. ++queuedFullJitWorkItemCount;
  1939. }
  1940. workItem->OnAddToJitQueue();
  1941. workItem->GetFunctionBody()->TraceExecutionMode("SpeculativeJit (before)");
  1942. workItem->GetFunctionBody()->TransitionToFullJitExecutionMode();
  1943. workItem->GetFunctionBody()->TraceExecutionMode("SpeculativeJit");
  1944. break;
  1945. }
  1946. workItem = static_cast<CodeGenWorkItem*>(workItem->Next());
  1947. }
  1948. return workItem;
  1949. }
  1950. // Removes all of the proactive jobs from the generator. Used when switching between attached/detached
  1951. // debug modes in order to drain the queue of jobs (since we switch from interpreted to native and back).
  1952. void
  1953. NativeCodeGenerator::RemoveProactiveJobs()
  1954. {
  1955. CodeGenWorkItem* workItem = workItems.Head();
  1956. while (workItem)
  1957. {
  1958. CodeGenWorkItem* temp = static_cast<CodeGenWorkItem*>(workItem->Next());
  1959. workItem->Delete();
  1960. workItem = temp;
  1961. }
  1962. workItems.Clear();
  1963. //for(JsUtil::Job *job = workItems.Head(); job;)
  1964. //{
  1965. // JsUtil::Job *const next = job->Next();
  1966. // JobProcessed(job, /*succeeded*/ false);
  1967. // job = next;
  1968. //}
  1969. }
  1970. template<bool IsInlinee>
  1971. void
  1972. NativeCodeGenerator::GatherCodeGenData(
  1973. Recycler *const recycler,
  1974. Js::FunctionBody *const topFunctionBody,
  1975. Js::FunctionBody *const functionBody,
  1976. Js::EntryPointInfo *const entryPoint,
  1977. InliningDecider &inliningDecider,
  1978. ObjTypeSpecFldInfoList *objTypeSpecFldInfoList,
  1979. Js::FunctionCodeGenJitTimeData *const jitTimeData,
  1980. Js::FunctionCodeGenRuntimeData *const runtimeData,
  1981. Js::JavascriptFunction* function,
  1982. bool isJitTimeDataComputed,
  1983. uint32 recursiveInlineDepth)
  1984. {
  1985. ASSERT_THREAD();
  1986. Assert(recycler);
  1987. Assert(functionBody);
  1988. Assert(jitTimeData);
  1989. Assert(IsInlinee == !!runtimeData);
  1990. Assert(!IsInlinee || (!inliningDecider.GetIsLoopBody() || !PHASE_OFF(Js::InlineInJitLoopBodyPhase, topFunctionBody)));
  1991. Assert(topFunctionBody != nullptr && (!entryPoint->GetWorkItem() || entryPoint->GetWorkItem()->GetFunctionBody() == topFunctionBody));
  1992. Assert(objTypeSpecFldInfoList != nullptr);
  1993. #ifdef FIELD_ACCESS_STATS
  1994. jitTimeData->EnsureInlineCacheStats(recycler);
  1995. #define SetInlineCacheCount(counter, value) jitTimeData->inlineCacheStats->counter = value;
  1996. #define IncInlineCacheCount(counter) if(!isJitTimeDataComputed) {jitTimeData->inlineCacheStats->counter++;}
  1997. #define AddInlineCacheStats(callerData, inlineeData) callerData->AddInlineeInlineCacheStats(inlineeData);
  1998. #define InlineCacheStatsArg(jitTimeData) !isJitTimeDataComputed ? jitTimeData->inlineCacheStats : nullptr
  1999. #else
  2000. #define SetInlineCacheCount(counter, value)
  2001. #define IncInlineCacheCount(counter)
  2002. #define AddInlineCacheStats(callerData, inlineeData)
  2003. #define InlineCacheStatsArg(jitTimeData) nullptr
  2004. #endif
  2005. #if DBG
  2006. Assert(
  2007. PHASE_ON(Js::Phase::SimulatePolyCacheWithOneTypeForFunctionPhase, functionBody) ==
  2008. CONFIG_ISENABLED(Js::Flag::SimulatePolyCacheWithOneTypeForInlineCacheIndexFlag));
  2009. if (PHASE_ON(Js::Phase::SimulatePolyCacheWithOneTypeForFunctionPhase, functionBody))
  2010. {
  2011. const Js::InlineCacheIndex inlineCacheIndex = CONFIG_FLAG(SimulatePolyCacheWithOneTypeForInlineCacheIndex);
  2012. functionBody->CreateNewPolymorphicInlineCache(
  2013. inlineCacheIndex,
  2014. functionBody->GetPropertyIdFromCacheId(inlineCacheIndex),
  2015. functionBody->GetInlineCache(inlineCacheIndex));
  2016. if (functionBody->HasDynamicProfileInfo())
  2017. {
  2018. functionBody->GetAnyDynamicProfileInfo()->RecordPolymorphicFieldAccess(functionBody, inlineCacheIndex);
  2019. }
  2020. }
  2021. #endif
  2022. NativeEntryPointData * nativeEntryPointData;
  2023. if (IsInlinee)
  2024. {
  2025. // This function is recursive
  2026. PROBE_STACK_NO_DISPOSE(scriptContext, Js::Constants::MinStackDefault);
  2027. nativeEntryPointData = entryPoint->GetNativeEntryPointData();;
  2028. }
  2029. else
  2030. {
  2031. // TODO: For now, we create the native entry point data and the jit transfer data when we queue up
  2032. // the entry point for code gen, but not clear/free then then the work item got knocked off the queue
  2033. // without code gen happening.
  2034. nativeEntryPointData = entryPoint->EnsureNativeEntryPointData();
  2035. nativeEntryPointData->EnsureJitTransferData(recycler);
  2036. //TryAggressiveInlining adjusts inlining heuristics and walks the call tree. If it can inlining everything it will set the InliningThreshold to be aggressive.
  2037. if (!inliningDecider.GetIsLoopBody())
  2038. {
  2039. uint32 inlineeCount = 0;
  2040. if (!PHASE_OFF(Js::TryAggressiveInliningPhase, topFunctionBody))
  2041. {
  2042. Assert(topFunctionBody == functionBody);
  2043. inliningDecider.SetAggressiveHeuristics();
  2044. if (!TryAggressiveInlining(topFunctionBody, functionBody, inliningDecider, inlineeCount, 0))
  2045. {
  2046. uint countOfInlineesWithLoops = inliningDecider.GetNumberOfInlineesWithLoop();
  2047. //TryAggressiveInlining failed, set back to default heuristics.
  2048. inliningDecider.ResetInlineHeuristics();
  2049. inliningDecider.SetLimitOnInlineesWithLoop(countOfInlineesWithLoops);
  2050. }
  2051. else
  2052. {
  2053. jitTimeData->SetIsAggressiveInliningEnabled();
  2054. }
  2055. inliningDecider.ResetState();
  2056. }
  2057. }
  2058. nativeEntryPointData->EnsurePolymorphicInlineCacheInfo(recycler, functionBody);
  2059. }
  2060. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2061. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2062. #endif
  2063. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2064. if (PHASE_VERBOSE_TRACE(Js::ObjTypeSpecPhase, topFunctionBody) || PHASE_VERBOSE_TRACE(Js::EquivObjTypeSpecPhase, topFunctionBody))
  2065. {
  2066. Output::Print(_u("ObjTypeSpec: top function %s (%s), function %s (%s): GatherCodeGenData(): \n"),
  2067. topFunctionBody->GetDisplayName(), topFunctionBody->GetDebugNumberSet(debugStringBuffer), functionBody->GetDisplayName(), functionBody->GetDebugNumberSet(debugStringBuffer));
  2068. Output::Flush();
  2069. }
  2070. #endif
  2071. const auto profileData =
  2072. functionBody->HasDynamicProfileInfo()
  2073. ? functionBody->GetAnyDynamicProfileInfo()
  2074. : functionBody->EnsureDynamicProfileInfo();
  2075. bool inlineGetterSetter = false;
  2076. bool inlineApplyTarget = false; //to indicate whether we can inline apply target or not.
  2077. bool inlineCallTarget = false;
  2078. if (profileData)
  2079. {
  2080. if (!IsInlinee)
  2081. {
  2082. PHASE_PRINT_TRACE(
  2083. Js::ObjTypeSpecPhase, functionBody,
  2084. _u("Objtypespec (%s): Pending cache state on add %x to JIT queue: %d\n"),
  2085. functionBody->GetDebugNumberSet(debugStringBuffer), entryPoint, profileData->GetPolymorphicCacheState());
  2086. nativeEntryPointData->SetPendingPolymorphicCacheState(profileData->GetPolymorphicCacheState());
  2087. nativeEntryPointData->SetPendingInlinerVersion(profileData->GetInlinerVersion());
  2088. nativeEntryPointData->SetPendingImplicitCallFlags(profileData->GetImplicitCallFlags());
  2089. }
  2090. if (functionBody->GetProfiledArrayCallSiteCount() != 0)
  2091. {
  2092. RecyclerWeakReference<Js::FunctionBody> *weakFuncRef = recycler->CreateWeakReferenceHandle(functionBody);
  2093. if (!isJitTimeDataComputed)
  2094. {
  2095. jitTimeData->SetWeakFuncRef(weakFuncRef);
  2096. }
  2097. entryPoint->GetNativeEntryPointData()->AddWeakFuncRef(weakFuncRef, recycler);
  2098. }
  2099. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2100. if (PHASE_VERBOSE_TESTTRACE(Js::ObjTypeSpecPhase, functionBody) ||
  2101. PHASE_VERBOSE_TRACE1(Js::PolymorphicInlineCachePhase))
  2102. {
  2103. if (functionBody->GetInlineCacheCount() > 0)
  2104. {
  2105. if (!IsInlinee)
  2106. {
  2107. Output::Print(_u("-----------------------------------------------------------------------------\n"));
  2108. }
  2109. else
  2110. {
  2111. Output::Print(_u("\tInlinee:\t"));
  2112. }
  2113. functionBody->DumpFullFunctionName();
  2114. Output::Print(_u("\n"));
  2115. }
  2116. }
  2117. #endif
  2118. SetInlineCacheCount(totalInlineCacheCount, functionBody->GetInlineCacheCount());
  2119. Assert(functionBody->GetProfiledFldCount() == functionBody->GetInlineCacheCount()); // otherwise, isInst inline caches need to be cloned
  2120. for(uint i = 0; i < functionBody->GetInlineCacheCount(); ++i)
  2121. {
  2122. const auto cacheType = profileData->GetFldInfo(functionBody, i)->flags;
  2123. PHASE_PRINT_VERBOSE_TESTTRACE(
  2124. Js::ObjTypeSpecPhase, functionBody,
  2125. _u("Cache #%3d, Layout: %s, Profile info: %s\n"),
  2126. i,
  2127. functionBody->GetInlineCache(i)->LayoutString(),
  2128. cacheType == Js::FldInfo_NoInfo ? _u("none") :
  2129. (cacheType & Js::FldInfo_Polymorphic) ? _u("polymorphic") : _u("monomorphic"));
  2130. if (cacheType == Js::FldInfo_NoInfo)
  2131. {
  2132. IncInlineCacheCount(noInfoInlineCacheCount);
  2133. continue;
  2134. }
  2135. Js::PolymorphicInlineCache * polymorphicCacheOnFunctionBody = functionBody->GetPolymorphicInlineCache(i);
  2136. bool isPolymorphic = (cacheType & Js::FldInfo_Polymorphic) != 0;
  2137. if (!isPolymorphic)
  2138. {
  2139. Js::InlineCache *inlineCache = nullptr;
  2140. if(function && Js::VarIs<Js::ScriptFunctionWithInlineCache>(function))
  2141. {
  2142. if (Js::VarTo<Js::ScriptFunctionWithInlineCache>(function)->GetInlineCaches() != nullptr)
  2143. {
  2144. inlineCache = Js::VarTo<Js::ScriptFunctionWithInlineCache>(function)->GetInlineCache(i);
  2145. }
  2146. }
  2147. else
  2148. {
  2149. inlineCache = functionBody->GetInlineCache(i);
  2150. }
  2151. if (inlineCache != nullptr)
  2152. {
  2153. ObjTypeSpecFldInfo* objTypeSpecFldInfo = nullptr;
  2154. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2155. if (PHASE_VERBOSE_TRACE(Js::ObjTypeSpecPhase, topFunctionBody) || PHASE_VERBOSE_TRACE(Js::EquivObjTypeSpecPhase, topFunctionBody))
  2156. {
  2157. char16 debugStringBuffer2[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2158. Js::PropertyId propertyId = functionBody->GetPropertyIdFromCacheId(i);
  2159. Js::PropertyRecord const * const propertyRecord = functionBody->GetScriptContext()->GetPropertyName(propertyId);
  2160. Output::Print(_u("ObTypeSpec: top function %s (%s), function %s (%s): cloning mono cache for %s (#%d) cache %d \n"),
  2161. topFunctionBody->GetDisplayName(), topFunctionBody->GetDebugNumberSet(debugStringBuffer),
  2162. functionBody->GetDisplayName(), functionBody->GetDebugNumberSet(debugStringBuffer2), propertyRecord->GetBuffer(), propertyId, i);
  2163. Output::Flush();
  2164. }
  2165. #endif
  2166. IncInlineCacheCount(monoInlineCacheCount);
  2167. if (inlineCache->IsEmpty())
  2168. {
  2169. IncInlineCacheCount(emptyMonoInlineCacheCount);
  2170. }
  2171. if(!PHASE_OFF(Js::ObjTypeSpecPhase, functionBody) || !PHASE_OFF(Js::FixedMethodsPhase, functionBody) || !PHASE_OFF(Js::UseFixedDataPropsPhase, functionBody))
  2172. {
  2173. if(cacheType & (Js::FldInfo_FromLocal | Js::FldInfo_FromLocalWithoutProperty | Js::FldInfo_FromProto))
  2174. {
  2175. // WinBlue 170722: Disable ObjTypeSpec optimization for activation object in debug mode,
  2176. // as it can result in BailOutFailedTypeCheck before locals are set to undefined,
  2177. // which can result in using garbage object during bailout/restore values.
  2178. if (!(functionBody->IsInDebugMode() && inlineCache->GetType() &&
  2179. inlineCache->GetType()->GetTypeId() == Js::TypeIds_ActivationObject))
  2180. {
  2181. objTypeSpecFldInfo = ObjTypeSpecFldInfo::CreateFrom(objTypeSpecFldInfoList->Count(), inlineCache, i, entryPoint, topFunctionBody, functionBody, InlineCacheStatsArg(jitTimeData));
  2182. if (objTypeSpecFldInfo)
  2183. {
  2184. IncInlineCacheCount(clonedMonoInlineCacheCount);
  2185. if (!PHASE_OFF(Js::InlineApplyTargetPhase, functionBody) && (cacheType & Js::FldInfo_InlineCandidate))
  2186. {
  2187. if (IsInlinee || objTypeSpecFldInfo->IsBuiltin())
  2188. {
  2189. inlineApplyTarget = true;
  2190. }
  2191. }
  2192. if (!PHASE_OFF(Js::InlineCallTargetPhase, functionBody) && (cacheType & Js::FldInfo_InlineCandidate))
  2193. {
  2194. inlineCallTarget = true;
  2195. }
  2196. if (!isJitTimeDataComputed)
  2197. {
  2198. jitTimeData->GetObjTypeSpecFldInfoArray()->SetInfo(recycler, functionBody, i, objTypeSpecFldInfo);
  2199. objTypeSpecFldInfoList->Prepend(objTypeSpecFldInfo);
  2200. }
  2201. }
  2202. }
  2203. }
  2204. }
  2205. if(!PHASE_OFF(Js::FixAccessorPropsPhase, functionBody))
  2206. {
  2207. if (!objTypeSpecFldInfo && (cacheType & Js::FldInfo_FromAccessor) && (cacheType & Js::FldInfo_InlineCandidate))
  2208. {
  2209. objTypeSpecFldInfo = ObjTypeSpecFldInfo::CreateFrom(objTypeSpecFldInfoList->Count(), inlineCache, i, entryPoint, topFunctionBody, functionBody, InlineCacheStatsArg(jitTimeData));
  2210. if (objTypeSpecFldInfo)
  2211. {
  2212. inlineGetterSetter = true;
  2213. if (!isJitTimeDataComputed)
  2214. {
  2215. IncInlineCacheCount(clonedMonoInlineCacheCount);
  2216. jitTimeData->GetObjTypeSpecFldInfoArray()->SetInfo(recycler, functionBody, i, objTypeSpecFldInfo);
  2217. objTypeSpecFldInfoList->Prepend(objTypeSpecFldInfo);
  2218. }
  2219. }
  2220. }
  2221. }
  2222. if (!PHASE_OFF(Js::RootObjectFldFastPathPhase, functionBody))
  2223. {
  2224. if (i >= functionBody->GetRootObjectLoadInlineCacheStart() && inlineCache->IsLocal())
  2225. {
  2226. void * rawType = inlineCache->u.local.type;
  2227. Js::Type * type = TypeWithoutAuxSlotTag(rawType);
  2228. Js::RootObjectBase * rootObject = functionBody->GetRootObject();
  2229. if (rootObject->GetType() == type)
  2230. {
  2231. Js::BigPropertyIndex propertyIndex = inlineCache->u.local.slotIndex;
  2232. if (rawType == type)
  2233. {
  2234. // type is not tagged, inline slot
  2235. propertyIndex = rootObject->GetPropertyIndexFromInlineSlotIndex(inlineCache->u.local.slotIndex);
  2236. }
  2237. else
  2238. {
  2239. propertyIndex = rootObject->GetPropertyIndexFromAuxSlotIndex(inlineCache->u.local.slotIndex);
  2240. }
  2241. Js::PropertyAttributes attributes;
  2242. if (rootObject->GetAttributesWithPropertyIndex(functionBody->GetPropertyIdFromCacheId(i), propertyIndex, &attributes)
  2243. && (attributes & PropertyConfigurable) == 0
  2244. && !isJitTimeDataComputed)
  2245. {
  2246. // non configurable
  2247. if (objTypeSpecFldInfo == nullptr)
  2248. {
  2249. objTypeSpecFldInfo = ObjTypeSpecFldInfo::CreateFrom(objTypeSpecFldInfoList->Count(), inlineCache, i, entryPoint, topFunctionBody, functionBody, InlineCacheStatsArg(jitTimeData));
  2250. if (objTypeSpecFldInfo)
  2251. {
  2252. IncInlineCacheCount(clonedMonoInlineCacheCount);
  2253. jitTimeData->GetObjTypeSpecFldInfoArray()->SetInfo(recycler, functionBody, i, objTypeSpecFldInfo);
  2254. objTypeSpecFldInfoList->Prepend(objTypeSpecFldInfo);
  2255. }
  2256. }
  2257. if (objTypeSpecFldInfo != nullptr)
  2258. {
  2259. objTypeSpecFldInfo->SetRootObjectNonConfigurableField(i < functionBody->GetRootObjectStoreInlineCacheStart());
  2260. }
  2261. }
  2262. }
  2263. }
  2264. }
  2265. }
  2266. }
  2267. // Even if the FldInfo says that the field access may be polymorphic, be optimistic that if the function object has inline caches, they'll be monomorphic
  2268. else if(function && Js::VarIs<Js::ScriptFunctionWithInlineCache>(function) && (cacheType & Js::FldInfo_InlineCandidate || !polymorphicCacheOnFunctionBody))
  2269. {
  2270. if (Js::VarTo<Js::ScriptFunctionWithInlineCache>(function)->GetInlineCaches() != nullptr)
  2271. {
  2272. Js::InlineCache *inlineCache = Js::VarTo<Js::ScriptFunctionWithInlineCache>(function)->GetInlineCache(i);
  2273. ObjTypeSpecFldInfo* objTypeSpecFldInfo = nullptr;
  2274. if(!PHASE_OFF(Js::ObjTypeSpecPhase, functionBody) || !PHASE_OFF(Js::FixedMethodsPhase, functionBody))
  2275. {
  2276. if(cacheType & (Js::FldInfo_FromLocal | Js::FldInfo_FromProto)) // Remove FldInfo_FromLocal?
  2277. {
  2278. // WinBlue 170722: Disable ObjTypeSpec optimization for activation object in debug mode,
  2279. // as it can result in BailOutFailedTypeCheck before locals are set to undefined,
  2280. // which can result in using garbage object during bailout/restore values.
  2281. if (!(functionBody->IsInDebugMode() && inlineCache->GetType() &&
  2282. inlineCache->GetType()->GetTypeId() == Js::TypeIds_ActivationObject))
  2283. {
  2284. objTypeSpecFldInfo = ObjTypeSpecFldInfo::CreateFrom(objTypeSpecFldInfoList->Count(), inlineCache, i, entryPoint, topFunctionBody, functionBody, InlineCacheStatsArg(jitTimeData));
  2285. if (objTypeSpecFldInfo)
  2286. {
  2287. IncInlineCacheCount(clonedMonoInlineCacheCount);
  2288. if (!PHASE_OFF(Js::InlineApplyTargetPhase, functionBody) && IsInlinee && (cacheType & Js::FldInfo_InlineCandidate))
  2289. {
  2290. inlineApplyTarget = true;
  2291. }
  2292. if (!isJitTimeDataComputed)
  2293. {
  2294. jitTimeData->GetObjTypeSpecFldInfoArray()->SetInfo(recycler, functionBody, i, objTypeSpecFldInfo);
  2295. objTypeSpecFldInfoList->Prepend(objTypeSpecFldInfo);
  2296. }
  2297. }
  2298. }
  2299. }
  2300. }
  2301. }
  2302. }
  2303. else
  2304. {
  2305. const auto polymorphicInlineCache = functionBody->GetPolymorphicInlineCache(i);
  2306. if (polymorphicInlineCache != nullptr)
  2307. {
  2308. IncInlineCacheCount(polyInlineCacheCount);
  2309. if (profileData->GetFldInfo(functionBody, i)->ShouldUsePolymorphicInlineCache())
  2310. {
  2311. IncInlineCacheCount(highUtilPolyInlineCacheCount);
  2312. }
  2313. else
  2314. {
  2315. IncInlineCacheCount(lowUtilPolyInlineCacheCount);
  2316. }
  2317. if (!PHASE_OFF(Js::EquivObjTypeSpecPhase, topFunctionBody) && !topFunctionBody->GetAnyDynamicProfileInfo()->IsEquivalentObjTypeSpecDisabled())
  2318. {
  2319. if (!polymorphicInlineCache->GetIgnoreForEquivalentObjTypeSpec() || (polymorphicInlineCache->GetCloneForJitTimeUse() && !PHASE_OFF(Js::PolymorphicInlinePhase, functionBody) && !PHASE_OFF(Js::PolymorphicInlineFixedMethodsPhase, functionBody)))
  2320. {
  2321. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2322. if (PHASE_VERBOSE_TRACE(Js::ObjTypeSpecPhase, topFunctionBody) || PHASE_VERBOSE_TRACE(Js::EquivObjTypeSpecPhase, topFunctionBody))
  2323. {
  2324. char16 debugStringBuffer2[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2325. Js::PropertyId propertyId = functionBody->GetPropertyIdFromCacheId(i);
  2326. Js::PropertyRecord const * const propertyRecord = functionBody->GetScriptContext()->GetPropertyName(propertyId);
  2327. Output::Print(_u("ObTypeSpec: top function %s (%s), function %s (%s): cloning poly cache for %s (#%d) cache %d \n"),
  2328. topFunctionBody->GetDisplayName(), topFunctionBody->GetDebugNumberSet(debugStringBuffer),
  2329. functionBody->GetDisplayName(), functionBody->GetDebugNumberSet(debugStringBuffer2), propertyRecord->GetBuffer(), propertyId, i);
  2330. Output::Flush();
  2331. }
  2332. #endif
  2333. ObjTypeSpecFldInfo* objTypeSpecFldInfo = ObjTypeSpecFldInfo::CreateFrom(objTypeSpecFldInfoList->Count(), polymorphicInlineCache, i, entryPoint, topFunctionBody, functionBody, InlineCacheStatsArg(jitTimeData));
  2334. if (objTypeSpecFldInfo != nullptr)
  2335. {
  2336. if (!isJitTimeDataComputed)
  2337. {
  2338. jitTimeData->GetObjTypeSpecFldInfoArray()->SetInfo(recycler, functionBody, i, objTypeSpecFldInfo);
  2339. IncInlineCacheCount(clonedPolyInlineCacheCount);
  2340. objTypeSpecFldInfoList->Prepend(objTypeSpecFldInfo);
  2341. }
  2342. if (!PHASE_OFF(Js::InlineAccessorsPhase, functionBody) && (cacheType & Js::FldInfo_FromAccessor) && (cacheType & Js::FldInfo_InlineCandidate))
  2343. {
  2344. inlineGetterSetter = true;
  2345. }
  2346. }
  2347. }
  2348. else
  2349. {
  2350. IncInlineCacheCount(ignoredPolyInlineCacheCount);
  2351. }
  2352. }
  2353. else
  2354. {
  2355. IncInlineCacheCount(disabledPolyInlineCacheCount);
  2356. }
  2357. }
  2358. else
  2359. {
  2360. IncInlineCacheCount(nullPolyInlineCacheCount);
  2361. }
  2362. if (polymorphicInlineCache != nullptr)
  2363. {
  2364. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2365. if (PHASE_VERBOSE_TRACE1(Js::PolymorphicInlineCachePhase))
  2366. {
  2367. if (IsInlinee) Output::Print(_u("\t"));
  2368. Output::Print(_u("\t%d: PIC size = %d\n"), i, polymorphicInlineCache->GetSize());
  2369. #if DBG_DUMP
  2370. polymorphicInlineCache->Dump();
  2371. #endif
  2372. }
  2373. else if (PHASE_TRACE1(Js::PolymorphicInlineCachePhase))
  2374. {
  2375. Js::PropertyId propertyId = functionBody->GetPropertyIdFromCacheId(i);
  2376. Js::PropertyRecord const * const propertyRecord = functionBody->GetScriptContext()->GetPropertyName(propertyId);
  2377. Output::Print(_u("Trace PIC JIT function %s (%s) field: %s (index: %d) \n"), functionBody->GetDisplayName(), functionBody->GetDebugNumberSet(debugStringBuffer),
  2378. propertyRecord->GetBuffer(), i);
  2379. }
  2380. #endif
  2381. byte polyCacheUtil = profileData->GetFldInfo(functionBody, i)->polymorphicInlineCacheUtilization;
  2382. nativeEntryPointData->GetPolymorphicInlineCacheInfo()->SetPolymorphicInlineCache(functionBody, i, polymorphicInlineCache, IsInlinee, polyCacheUtil);
  2383. if (IsInlinee)
  2384. {
  2385. Assert(nativeEntryPointData->GetPolymorphicInlineCacheInfo()->GetInlineeInfo(functionBody)->GetPolymorphicInlineCaches()->GetInlineCache(functionBody, i) == polymorphicInlineCache);
  2386. }
  2387. else
  2388. {
  2389. Assert(nativeEntryPointData->GetPolymorphicInlineCacheInfo()->GetSelfInfo()->GetPolymorphicInlineCaches()->GetInlineCache(functionBody, i) == polymorphicInlineCache);
  2390. }
  2391. }
  2392. else if(IsInlinee && CONFIG_FLAG(CloneInlinedPolymorphicCaches))
  2393. {
  2394. // Clone polymorphic inline caches for runtime usage in this inlinee. The JIT should only use the pointers to
  2395. // the inline caches, as their cached data is not guaranteed to be stable while jitting.
  2396. Js::InlineCache *const inlineCache =
  2397. function && Js::VarIs<Js::ScriptFunctionWithInlineCache>(function)
  2398. ? (Js::VarTo<Js::ScriptFunctionWithInlineCache>(function)->GetInlineCaches() != nullptr ? Js::VarTo<Js::ScriptFunctionWithInlineCache>(function)->GetInlineCache(i) : nullptr)
  2399. : functionBody->GetInlineCache(i);
  2400. if (inlineCache != nullptr)
  2401. {
  2402. Js::PropertyId propertyId = functionBody->GetPropertyIdFromCacheId(i);
  2403. const auto clone = runtimeData->ClonedInlineCaches()->GetInlineCache(functionBody, i);
  2404. if (clone)
  2405. {
  2406. inlineCache->CopyTo(propertyId, functionBody->GetScriptContext(), clone);
  2407. }
  2408. else
  2409. {
  2410. runtimeData->ClonedInlineCaches()->SetInlineCache(
  2411. recycler,
  2412. functionBody,
  2413. i,
  2414. inlineCache->Clone(propertyId, functionBody->GetScriptContext()));
  2415. }
  2416. }
  2417. }
  2418. }
  2419. }
  2420. }
  2421. // Gather code gen data for inlinees
  2422. if(IsInlinee ? !inliningDecider.InlineIntoInliner(functionBody) : !inliningDecider.InlineIntoTopFunc())
  2423. {
  2424. return;
  2425. }
  2426. class AutoCleanup
  2427. {
  2428. private:
  2429. Js::FunctionBody *const functionBody;
  2430. public:
  2431. AutoCleanup(Js::FunctionBody *const functionBody) : functionBody(functionBody)
  2432. {
  2433. functionBody->OnBeginInlineInto();
  2434. }
  2435. ~AutoCleanup()
  2436. {
  2437. functionBody->OnEndInlineInto();
  2438. }
  2439. } autoCleanup(functionBody);
  2440. const auto profiledCallSiteCount = functionBody->GetProfiledCallSiteCount();
  2441. Assert(profiledCallSiteCount != 0 || functionBody->GetAnyDynamicProfileInfo()->HasLdFldCallSiteInfo());
  2442. if (profiledCallSiteCount && !isJitTimeDataComputed)
  2443. {
  2444. jitTimeData->inlineesBv = BVFixed::New<Recycler>(profiledCallSiteCount, recycler);
  2445. }
  2446. // Iterate through profiled call sites recursively and determine what should be inlined
  2447. for(Js::ProfileId profiledCallSiteId = 0; profiledCallSiteId < profiledCallSiteCount; ++profiledCallSiteId)
  2448. {
  2449. Js::FunctionInfo *const inlinee = inliningDecider.InlineCallSite(functionBody, profiledCallSiteId, recursiveInlineDepth);
  2450. if(!inlinee)
  2451. {
  2452. if (profileData->CallSiteHasProfileData(profiledCallSiteId))
  2453. {
  2454. jitTimeData->inlineesBv->Set(profiledCallSiteId);
  2455. }
  2456. //Try and see if this polymorphic call
  2457. Js::FunctionBody* inlineeFunctionBodyArray[Js::DynamicProfileInfo::maxPolymorphicInliningSize] = {0};
  2458. bool canInlineArray[Js::DynamicProfileInfo::maxPolymorphicInliningSize] = { 0 };
  2459. uint polyInlineeCount = inliningDecider.InlinePolymorphicCallSite(functionBody, profiledCallSiteId, inlineeFunctionBodyArray,
  2460. Js::DynamicProfileInfo::maxPolymorphicInliningSize, canInlineArray);
  2461. //We should be able to inline at least two functions here.
  2462. if (polyInlineeCount >= 2)
  2463. {
  2464. for (uint id = 0; id < polyInlineeCount; id++)
  2465. {
  2466. bool isInlined = canInlineArray[id];
  2467. Js::FunctionCodeGenRuntimeData *inlineeRunTimeData = IsInlinee ? runtimeData->EnsureInlinee(recycler, profiledCallSiteId, inlineeFunctionBodyArray[id]) : functionBody->EnsureInlineeCodeGenRuntimeData(recycler, profiledCallSiteId, inlineeFunctionBodyArray[id]);
  2468. if (!isJitTimeDataComputed)
  2469. {
  2470. Js::FunctionCodeGenJitTimeData *inlineeJitTimeData = jitTimeData->AddInlinee(recycler, profiledCallSiteId, inlineeFunctionBodyArray[id]->GetFunctionInfo(), isInlined);
  2471. if (isInlined)
  2472. {
  2473. GatherCodeGenData<true>(
  2474. recycler,
  2475. topFunctionBody,
  2476. inlineeFunctionBodyArray[id],
  2477. entryPoint,
  2478. inliningDecider,
  2479. objTypeSpecFldInfoList,
  2480. inlineeJitTimeData,
  2481. inlineeRunTimeData
  2482. );
  2483. AddInlineCacheStats(jitTimeData, inlineeJitTimeData);
  2484. }
  2485. }
  2486. }
  2487. }
  2488. }
  2489. else
  2490. {
  2491. jitTimeData->inlineesBv->Set(profiledCallSiteId);
  2492. Js::FunctionBody *const inlineeFunctionBody = inlinee->GetFunctionBody();
  2493. if(!inlineeFunctionBody )
  2494. {
  2495. if (!isJitTimeDataComputed)
  2496. {
  2497. jitTimeData->AddInlinee(recycler, profiledCallSiteId, inlinee);
  2498. if (inlinee->IsBuiltInApplyFunction() || inlinee->IsBuiltInCallFunction())
  2499. {
  2500. // .call/.apply targets
  2501. Js::FunctionInfo *const targetFunctionInfo = inliningDecider.InlineCallApplyTarget(functionBody, profiledCallSiteId, recursiveInlineDepth);
  2502. if (targetFunctionInfo != nullptr)
  2503. {
  2504. Js::FunctionBody *const targetFunctionBody = targetFunctionInfo->GetFunctionBody();
  2505. Js::ProfileId callApplyCallSiteId = functionBody->GetCallSiteToCallApplyCallSiteArray()[profiledCallSiteId];
  2506. if (!targetFunctionBody)
  2507. {
  2508. jitTimeData->AddCallApplyTargetInlinee(recycler, profiledCallSiteId, callApplyCallSiteId, targetFunctionInfo);
  2509. }
  2510. else if (targetFunctionBody != functionBody)
  2511. {
  2512. Js::FunctionCodeGenJitTimeData * targetJittimeData = jitTimeData->AddCallApplyTargetInlinee(recycler, profiledCallSiteId, callApplyCallSiteId, targetFunctionInfo);
  2513. Js::FunctionCodeGenRuntimeData * targetRuntimeData = IsInlinee ? runtimeData->EnsureCallApplyTargetInlinee(recycler, callApplyCallSiteId, targetFunctionBody) : functionBody->EnsureCallApplyTargetInlineeCodeGenRuntimeData(recycler, callApplyCallSiteId, targetFunctionBody);
  2514. GatherCodeGenData<true>(
  2515. recycler,
  2516. topFunctionBody,
  2517. targetFunctionBody,
  2518. entryPoint,
  2519. inliningDecider,
  2520. objTypeSpecFldInfoList,
  2521. targetJittimeData,
  2522. targetRuntimeData);
  2523. AddInlineCacheStats(jitTimeData, targetJittimeData);
  2524. }
  2525. }
  2526. }
  2527. }
  2528. continue;
  2529. }
  2530. // We are at a callsite that can be inlined. Let the callsite be foo().
  2531. // If foo has inline caches on it, we need to be able to get those for cloning.
  2532. // To do this,
  2533. // 1. Retrieve the inline cache associated with the load of "foo",
  2534. // 2. Try to get the fixed function object corresponding to "foo",
  2535. // 3. Pass the fixed function object to GatherCodeGenData which can clone its inline caches.
  2536. uint ldFldInlineCacheIndex = profileData->GetLdFldCacheIndexFromCallSiteInfo(functionBody, profiledCallSiteId);
  2537. Js::InlineCache * inlineCache = nullptr;
  2538. if ((ldFldInlineCacheIndex != Js::Constants::NoInlineCacheIndex) && (ldFldInlineCacheIndex < functionBody->GetInlineCacheCount()))
  2539. {
  2540. if(function && Js::VarIs<Js::ScriptFunctionWithInlineCache>(function))
  2541. {
  2542. if (Js::VarTo<Js::ScriptFunctionWithInlineCache>(function)->GetInlineCaches() != nullptr)
  2543. {
  2544. inlineCache = Js::VarTo<Js::ScriptFunctionWithInlineCache>(function)->GetInlineCache(ldFldInlineCacheIndex);
  2545. }
  2546. }
  2547. else
  2548. {
  2549. inlineCache = functionBody->GetInlineCache(ldFldInlineCacheIndex);
  2550. }
  2551. }
  2552. Js::JavascriptFunction* fixedFunctionObject = nullptr;
  2553. #if ENABLE_FIXED_FIELDS
  2554. if (inlineCache && (inlineCache->IsLocal() || inlineCache->IsProto()))
  2555. {
  2556. inlineCache->TryGetFixedMethodFromCache(functionBody, ldFldInlineCacheIndex, &fixedFunctionObject);
  2557. }
  2558. if (fixedFunctionObject && fixedFunctionObject->GetFunctionInfo() != inlineeFunctionBody->GetFunctionInfo())
  2559. {
  2560. fixedFunctionObject = nullptr;
  2561. }
  2562. #endif
  2563. if (!PHASE_OFF(Js::InlineRecursivePhase, functionBody))
  2564. {
  2565. if (!isJitTimeDataComputed)
  2566. {
  2567. Js::FunctionCodeGenRuntimeData *inlineeRuntimeData = IsInlinee ? runtimeData->EnsureInlinee(recycler, profiledCallSiteId, inlineeFunctionBody) : functionBody->EnsureInlineeCodeGenRuntimeData(recycler, profiledCallSiteId, inlineeFunctionBody);
  2568. Js::FunctionCodeGenJitTimeData *inlineeJitTimeData = nullptr;
  2569. bool doShareJitTimeData = false;
  2570. // Share the jitTime data if i) it is a recursive call, ii) jitTimeData is not from a polymorphic chain, and iii) all the call sites are recursive
  2571. if (functionBody == inlineeFunctionBody // recursive call
  2572. && jitTimeData->GetNext() == nullptr // not from a polymorphic call site
  2573. && profiledCallSiteCount == functionBody->GetNumberOfRecursiveCallSites() && !inlineGetterSetter) // all the callsites are recursive
  2574. {
  2575. jitTimeData->SetupRecursiveInlineeChain(recycler, profiledCallSiteId);
  2576. inlineeJitTimeData = jitTimeData;
  2577. doShareJitTimeData = true;
  2578. // If a recursive inliner has multiple recursive inlinees and if they hit the InlineCountMax
  2579. // threshold, then runtimeData for the inlinees may not be available (bug 2269097) for the inlinees
  2580. // as InlineCountMax threshold heuristics has higher priority than recursive inline heuristics. Since
  2581. // we share runtime data between recursive inliner and recursive inlinees, and all the call sites
  2582. // are recursive (we only do recursive inlining for functions where all the callsites are recursive),
  2583. // we can iterate over all the callsites of the inliner and setup the runtime data recursive inlinee chain
  2584. for (Js::ProfileId id = 0; id < profiledCallSiteCount; id++)
  2585. {
  2586. inlineeRuntimeData->SetupRecursiveInlineeChain(recycler, id, inlineeFunctionBody);
  2587. }
  2588. }
  2589. else
  2590. {
  2591. inlineeJitTimeData = jitTimeData->AddInlinee(recycler, profiledCallSiteId, inlinee);
  2592. }
  2593. GatherCodeGenData<true>(
  2594. recycler,
  2595. topFunctionBody,
  2596. inlineeFunctionBody,
  2597. entryPoint,
  2598. inliningDecider,
  2599. objTypeSpecFldInfoList,
  2600. inlineeJitTimeData,
  2601. inlineeRuntimeData,
  2602. fixedFunctionObject,
  2603. doShareJitTimeData,
  2604. functionBody == inlineeFunctionBody ? recursiveInlineDepth + 1 : 0);
  2605. if (jitTimeData != inlineeJitTimeData)
  2606. {
  2607. AddInlineCacheStats(jitTimeData, inlineeJitTimeData);
  2608. }
  2609. }
  2610. }
  2611. else
  2612. {
  2613. Js::FunctionCodeGenJitTimeData *const inlineeJitTimeData = jitTimeData->AddInlinee(recycler, profiledCallSiteId, inlinee);
  2614. GatherCodeGenData<true>(
  2615. recycler,
  2616. topFunctionBody,
  2617. inlineeFunctionBody,
  2618. entryPoint,
  2619. inliningDecider,
  2620. objTypeSpecFldInfoList,
  2621. inlineeJitTimeData,
  2622. IsInlinee
  2623. ? runtimeData->EnsureInlinee(recycler, profiledCallSiteId, inlineeFunctionBody)
  2624. : functionBody->EnsureInlineeCodeGenRuntimeData(recycler, profiledCallSiteId, inlineeFunctionBody),
  2625. fixedFunctionObject);
  2626. AddInlineCacheStats(jitTimeData, inlineeJitTimeData);
  2627. }
  2628. if (PHASE_ENABLED(InlineCallbacksPhase, functionBody))
  2629. {
  2630. if (!isJitTimeDataComputed)
  2631. {
  2632. Js::FunctionInfo *const callbackInfo = inliningDecider.InlineCallback(functionBody, profiledCallSiteId, recursiveInlineDepth);
  2633. if (callbackInfo != nullptr)
  2634. {
  2635. Js::FunctionBody *const callbackBody = callbackInfo->GetFunctionBody();
  2636. if (callbackBody != nullptr && callbackBody != functionBody)
  2637. {
  2638. Js::FunctionCodeGenJitTimeData * callbackJitTimeData = jitTimeData->AddCallbackInlinee(recycler, profiledCallSiteId, callbackInfo);
  2639. Js::FunctionCodeGenRuntimeData * callbackRuntimeData = IsInlinee ? runtimeData->EnsureCallbackInlinee(recycler, profiledCallSiteId, callbackBody) : functionBody->EnsureCallbackInlineeCodeGenRuntimeData(recycler, profiledCallSiteId, callbackBody);
  2640. GatherCodeGenData<true>(
  2641. recycler,
  2642. topFunctionBody,
  2643. callbackBody,
  2644. entryPoint,
  2645. inliningDecider,
  2646. objTypeSpecFldInfoList,
  2647. callbackJitTimeData,
  2648. callbackRuntimeData);
  2649. AddInlineCacheStats(jitTimeData, callbackJitTimeData);
  2650. }
  2651. }
  2652. }
  2653. }
  2654. }
  2655. }
  2656. // Iterate through inlineCache getter setter and apply call sites recursively and determine what should be inlined
  2657. if (inlineGetterSetter || inlineApplyTarget || inlineCallTarget)
  2658. {
  2659. for(uint inlineCacheIndex = 0; inlineCacheIndex < functionBody->GetInlineCacheCount(); ++inlineCacheIndex)
  2660. {
  2661. const auto cacheType = profileData->GetFldInfo(functionBody, inlineCacheIndex)->flags;
  2662. if(cacheType == Js::FldInfo_NoInfo)
  2663. {
  2664. continue;
  2665. }
  2666. bool getSetInlineCandidate = inlineGetterSetter && ((cacheType & Js::FldInfo_InlineCandidate) != 0) && ((cacheType & Js::FldInfo_FromAccessor) != 0);
  2667. bool callApplyInlineCandidate = (inlineCallTarget || inlineApplyTarget) && ((cacheType & Js::FldInfo_InlineCandidate) != 0) && ((cacheType & Js::FldInfo_FromAccessor) == 0);
  2668. // 1. Do not inline if the x in a.x is both a getter/setter and is followed by a .apply
  2669. // 2. If we were optimistic earlier in assuming that the inline caches on the function object would be monomorphic and asserted that we may possibly inline apply target,
  2670. // then even if the field info flags say that the field access may be polymorphic, carry that optimism forward and try to inline apply target.
  2671. if (getSetInlineCandidate ^ callApplyInlineCandidate)
  2672. {
  2673. ObjTypeSpecFldInfo* info = jitTimeData->GetObjTypeSpecFldInfoArray()->GetInfo(functionBody, inlineCacheIndex);
  2674. if (info == nullptr)
  2675. {
  2676. continue;
  2677. }
  2678. if (!(getSetInlineCandidate && info->UsesAccessor()) && !(callApplyInlineCandidate && !info->IsPoly()))
  2679. {
  2680. continue;
  2681. }
  2682. Js::JavascriptFunction* inlineeFunction = info->GetFieldValueAsFunctionIfAvailable();
  2683. if (inlineeFunction == nullptr)
  2684. {
  2685. continue;
  2686. }
  2687. Js::FunctionInfo* inlineeFunctionInfo = inlineeFunction->GetFunctionInfo();
  2688. Js::FunctionProxy* inlineeFunctionProxy = inlineeFunctionInfo->GetFunctionProxy();
  2689. if (inlineeFunctionProxy != nullptr && !functionBody->CheckCalleeContextForInlining(inlineeFunctionProxy))
  2690. {
  2691. continue;
  2692. }
  2693. const auto inlinee = inliningDecider.Inline(functionBody, inlineeFunctionInfo, false /*isConstructorCall*/, false /*isPolymorphicCall*/, false /*isCallback*/, 0, (uint16)inlineCacheIndex, 0, false);
  2694. if(!inlinee)
  2695. {
  2696. continue;
  2697. }
  2698. const auto inlineeFunctionBody = inlinee->GetFunctionBody();
  2699. if(!inlineeFunctionBody)
  2700. {
  2701. if (((inlineeFunctionInfo->GetAttributes() & Js::FunctionInfo::Attributes::BuiltInInlinableAsLdFldInlinee) != 0) && !isJitTimeDataComputed)
  2702. {
  2703. jitTimeData->AddLdFldInlinee(recycler, inlineCacheIndex, inlinee);
  2704. }
  2705. continue;
  2706. }
  2707. Js::FunctionCodeGenRuntimeData *const inlineeRuntimeData = IsInlinee ? runtimeData->EnsureLdFldInlinee(recycler, inlineCacheIndex, inlineeFunctionBody) :
  2708. functionBody->EnsureLdFldInlineeCodeGenRuntimeData(recycler, inlineCacheIndex, inlineeFunctionBody);
  2709. if (inlineeRuntimeData->GetFunctionBody() != inlineeFunctionBody)
  2710. {
  2711. //There are obscure cases where profileData has not yet seen the polymorphic LdFld but the inlineCache has the newer object from which getter is invoked.
  2712. //In this case we don't want to inline that getter. Polymorphic bit will be set later correctly.
  2713. //See WinBlue 54540
  2714. continue;
  2715. }
  2716. Js::FunctionCodeGenJitTimeData *inlineeJitTimeData = jitTimeData->AddLdFldInlinee(recycler, inlineCacheIndex, inlinee);
  2717. GatherCodeGenData<true>(
  2718. recycler,
  2719. topFunctionBody,
  2720. inlineeFunctionBody,
  2721. entryPoint,
  2722. inliningDecider,
  2723. objTypeSpecFldInfoList,
  2724. inlineeJitTimeData,
  2725. inlineeRuntimeData,
  2726. nullptr);
  2727. AddInlineCacheStats(jitTimeData, inlineeJitTimeData);
  2728. }
  2729. }
  2730. }
  2731. #ifdef FIELD_ACCESS_STATS
  2732. if (PHASE_VERBOSE_TRACE(Js::ObjTypeSpecPhase, topFunctionBody) || PHASE_VERBOSE_TRACE(Js::EquivObjTypeSpecPhase, topFunctionBody))
  2733. {
  2734. if (jitTimeData->inlineCacheStats)
  2735. {
  2736. Output::Print(_u("ObTypeSpec: gathered code gen data for function %s (#%u) inlined %s (#%u): inline cache stats:\n"),
  2737. topFunctionBody->GetDisplayName(), topFunctionBody->GetFunctionNumber(), functionBody->GetDisplayName(), functionBody->GetFunctionNumber());
  2738. Output::Print(_u(" overall: total %u, no profile info %u\n"),
  2739. jitTimeData->inlineCacheStats->totalInlineCacheCount, jitTimeData->inlineCacheStats->noInfoInlineCacheCount);
  2740. Output::Print(_u(" mono: total %u, empty %u, cloned %u\n"),
  2741. jitTimeData->inlineCacheStats->monoInlineCacheCount, jitTimeData->inlineCacheStats->emptyMonoInlineCacheCount,
  2742. jitTimeData->inlineCacheStats->clonedMonoInlineCacheCount);
  2743. Output::Print(_u(" poly: total %u (high %u, low %u), empty %u, equivalent %u, cloned %u\n"),
  2744. jitTimeData->inlineCacheStats->polyInlineCacheCount, jitTimeData->inlineCacheStats->highUtilPolyInlineCacheCount,
  2745. jitTimeData->inlineCacheStats->lowUtilPolyInlineCacheCount, jitTimeData->inlineCacheStats->emptyPolyInlineCacheCount,
  2746. jitTimeData->inlineCacheStats->equivPolyInlineCacheCount, jitTimeData->inlineCacheStats->clonedPolyInlineCacheCount);
  2747. }
  2748. else
  2749. {
  2750. Output::Print(_u("ObTypeSpec: function %s (%s): inline cache stats unavailable\n"), topFunctionBody->GetDisplayName(), topFunctionBody->GetDebugNumberSet(debugStringBuffer));
  2751. }
  2752. Output::Flush();
  2753. }
  2754. #endif
  2755. #undef SetInlineCacheCount
  2756. #undef IncInlineCacheCount
  2757. #undef AddInlineCacheStats
  2758. }
  2759. Js::CodeGenRecyclableData *
  2760. NativeCodeGenerator::GatherCodeGenData(Js::FunctionBody *const topFunctionBody, Js::FunctionBody *const functionBody, Js::EntryPointInfo *const entryPoint, CodeGenWorkItem* workItem, void* function)
  2761. {
  2762. ASSERT_THREAD();
  2763. Assert(functionBody);
  2764. #ifdef PROFILE_EXEC
  2765. class AutoProfile
  2766. {
  2767. private:
  2768. Js::ScriptContextProfiler *const codeGenProfiler;
  2769. public:
  2770. AutoProfile(Js::ScriptContextProfiler *const codeGenProfiler) : codeGenProfiler(codeGenProfiler)
  2771. {
  2772. ProfileBegin(codeGenProfiler, Js::DelayPhase);
  2773. ProfileBegin(codeGenProfiler, Js::GatherCodeGenDataPhase);
  2774. }
  2775. ~AutoProfile()
  2776. {
  2777. ProfileEnd(codeGenProfiler, Js::GatherCodeGenDataPhase);
  2778. ProfileEnd(codeGenProfiler, Js::DelayPhase);
  2779. }
  2780. } autoProfile(foregroundCodeGenProfiler);
  2781. #endif
  2782. UpdateJITState();
  2783. const auto recycler = scriptContext->GetRecycler();
  2784. {
  2785. const auto jitTimeData = Js::FunctionCodeGenJitTimeData::New(recycler, functionBody->GetFunctionInfo(), entryPoint);
  2786. InliningDecider inliningDecider(functionBody, workItem->Type() == JsLoopBodyWorkItemType, functionBody->IsInDebugMode(), workItem->GetJitMode());
  2787. BEGIN_TEMP_ALLOCATOR(gatherCodeGenDataAllocator, scriptContext, _u("GatherCodeGenData"));
  2788. ObjTypeSpecFldInfoList* objTypeSpecFldInfoList = JitAnew(gatherCodeGenDataAllocator, ObjTypeSpecFldInfoList, gatherCodeGenDataAllocator);
  2789. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2790. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2791. char16 debugStringBuffer2[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2792. if (PHASE_TRACE(Js::ObjTypeSpecPhase, topFunctionBody) || PHASE_TRACE(Js::EquivObjTypeSpecPhase, topFunctionBody))
  2793. {
  2794. Output::Print(_u("ObjTypeSpec: top function %s (%s), function %s (%s): GatherCodeGenData(): \n"),
  2795. topFunctionBody->GetDisplayName(), topFunctionBody->GetDebugNumberSet(debugStringBuffer), functionBody->GetDisplayName(), functionBody->GetDebugNumberSet(debugStringBuffer2));
  2796. }
  2797. #endif
  2798. GatherCodeGenData<false>(recycler, topFunctionBody, functionBody, entryPoint, inliningDecider, objTypeSpecFldInfoList, jitTimeData, nullptr, function ? Js::VarTo<Js::JavascriptFunction>(function) : nullptr, 0);
  2799. jitTimeData->sharedPropertyGuards = entryPoint->GetNativeEntryPointData()->GetSharedPropertyGuards(recycler, jitTimeData->sharedPropertyGuardCount);
  2800. #ifdef FIELD_ACCESS_STATS
  2801. Js::FieldAccessStats* fieldAccessStats = entryPoint->EnsureFieldAccessStats(recycler);
  2802. fieldAccessStats->Add(jitTimeData->inlineCacheStats);
  2803. entryPoint->GetScriptContext()->RecordFieldAccessStats(topFunctionBody, fieldAccessStats);
  2804. #endif
  2805. #ifdef FIELD_ACCESS_STATS
  2806. if (PHASE_TRACE(Js::ObjTypeSpecPhase, topFunctionBody) || PHASE_TRACE(Js::EquivObjTypeSpecPhase, topFunctionBody))
  2807. {
  2808. auto stats = jitTimeData->inlineCacheStats;
  2809. Output::Print(_u("ObjTypeSpec: gathered code gen data for function %s (%s): inline cache stats:\n"), topFunctionBody->GetDisplayName(), topFunctionBody->GetDebugNumberSet(debugStringBuffer));
  2810. Output::Print(_u(" overall: total %u, no profile info %u\n"), stats->totalInlineCacheCount, stats->noInfoInlineCacheCount);
  2811. Output::Print(_u(" mono: total %u, empty %u, cloned %u\n"),
  2812. stats->monoInlineCacheCount, stats->emptyMonoInlineCacheCount, stats->clonedMonoInlineCacheCount);
  2813. Output::Print(_u(" poly: total %u (high %u, low %u), null %u, empty %u, ignored %u, disabled %u, equivalent %u, non-equivalent %u, cloned %u\n"),
  2814. stats->polyInlineCacheCount, stats->highUtilPolyInlineCacheCount, stats->lowUtilPolyInlineCacheCount,
  2815. stats->nullPolyInlineCacheCount, stats->emptyPolyInlineCacheCount, stats->ignoredPolyInlineCacheCount, stats->disabledPolyInlineCacheCount,
  2816. stats->equivPolyInlineCacheCount, stats->nonEquivPolyInlineCacheCount, stats->clonedPolyInlineCacheCount);
  2817. }
  2818. #endif
  2819. uint objTypeSpecFldInfoCount = objTypeSpecFldInfoList->Count();
  2820. jitTimeData->SetGlobalObjTypeSpecFldInfoArray(RecyclerNewArray(recycler, Field(ObjTypeSpecFldInfo*), objTypeSpecFldInfoCount), objTypeSpecFldInfoCount);
  2821. uint propertyInfoId = objTypeSpecFldInfoCount - 1;
  2822. FOREACH_SLISTCOUNTED_ENTRY(ObjTypeSpecFldInfo*, info, objTypeSpecFldInfoList)
  2823. {
  2824. // Clear field values we don't need so we don't unnecessarily pin them while JIT-ing.
  2825. if (!info->GetKeepFieldValue() && !(info->IsPoly() && info->DoesntHaveEquivalence()))
  2826. {
  2827. info->SetFieldValue(nullptr);
  2828. }
  2829. jitTimeData->SetGlobalObjTypeSpecFldInfo(propertyInfoId--, info);
  2830. }
  2831. NEXT_SLISTCOUNTED_ENTRY;
  2832. END_TEMP_ALLOCATOR(gatherCodeGenDataAllocator, scriptContext);
  2833. auto jitData = workItem->GetJITData();
  2834. JITTimePolymorphicInlineCacheInfo::InitializeEntryPointPolymorphicInlineCacheInfo(
  2835. recycler,
  2836. entryPoint->GetNativeEntryPointData()->EnsurePolymorphicInlineCacheInfo(recycler, workItem->GetFunctionBody()),
  2837. jitData);
  2838. jitTimeData->SetPolymorphicInlineInfo(jitData->inlineeInfo, jitData->selfInfo, jitData->selfInfo->polymorphicInlineCaches);
  2839. return RecyclerNew(recycler, Js::CodeGenRecyclableData, jitTimeData);
  2840. }
  2841. }
  2842. bool
  2843. NativeCodeGenerator::IsBackgroundJIT() const
  2844. {
  2845. return Processor()->ProcessesInBackground();
  2846. }
  2847. void
  2848. NativeCodeGenerator::EnterScriptStart()
  2849. {
  2850. // We should be in execution
  2851. Assert(scriptContext->GetThreadContext()->IsScriptActive());
  2852. Assert(scriptContext->GetThreadContext()->IsInScript());
  2853. if(CONFIG_FLAG(BgJitDelay) == 0 ||
  2854. Js::Configuration::Global.flags.EnforceExecutionModeLimits ||
  2855. scriptContext->GetThreadContext()->GetCallRootLevel() > 2)
  2856. {
  2857. return;
  2858. }
  2859. if (pendingCodeGenWorkItems == 0 || pendingCodeGenWorkItems > (uint)CONFIG_FLAG(BgJitPendingFuncCap))
  2860. {
  2861. // We have already finish code gen for this script context
  2862. // Only wait if the script is small and we can easily pre-JIT all of it.
  2863. return;
  2864. }
  2865. if (this->IsClosed())
  2866. {
  2867. return;
  2868. }
  2869. // We've already done a few calls to this scriptContext, don't bother waiting.
  2870. if (scriptContext->callCount >= 3)
  2871. {
  2872. return;
  2873. }
  2874. scriptContext->callCount++;
  2875. if (scriptContext->GetDeferredBody())
  2876. {
  2877. OUTPUT_TRACE(Js::DelayPhase, _u("No delay because the script has a deferred body\n"));
  2878. return;
  2879. }
  2880. if(CONFIG_FLAG(BgJitDelayFgBuffer) >= CONFIG_FLAG(BgJitDelay))
  2881. {
  2882. return;
  2883. }
  2884. class AutoCleanup
  2885. {
  2886. private:
  2887. Js::ScriptContextProfiler *const codeGenProfiler;
  2888. public:
  2889. AutoCleanup(Js::ScriptContextProfiler *const codeGenProfiler) : codeGenProfiler(codeGenProfiler)
  2890. {
  2891. EDGE_ETW_INTERNAL(EventWriteJSCRIPT_NATIVECODEGEN_DELAY_START(this, 0));
  2892. #ifdef PROFILE_EXEC
  2893. ProfileBegin(codeGenProfiler, Js::DelayPhase);
  2894. ProfileBegin(codeGenProfiler, Js::SpeculationPhase);
  2895. #endif
  2896. }
  2897. ~AutoCleanup()
  2898. {
  2899. #ifdef PROFILE_EXEC
  2900. ProfileEnd(codeGenProfiler, Js::SpeculationPhase);
  2901. ProfileEnd(codeGenProfiler, Js::DelayPhase);
  2902. #endif
  2903. EDGE_ETW_INTERNAL(EventWriteJSCRIPT_NATIVECODEGEN_DELAY_STOP(this, 0));
  2904. }
  2905. } autoCleanup(
  2906. #ifdef PROFILE_EXEC
  2907. this->foregroundCodeGenProfiler
  2908. #else
  2909. nullptr
  2910. #endif
  2911. );
  2912. Processor()->PrioritizeManagerAndWait(this, CONFIG_FLAG(BgJitDelay) - CONFIG_FLAG(BgJitDelayFgBuffer));
  2913. }
  2914. void
  2915. FreeNativeCodeGenAllocation(Js::ScriptContext *scriptContext, Js::JavascriptMethod codeAddress, Js::JavascriptMethod thunkAddress)
  2916. {
  2917. if (!scriptContext->GetNativeCodeGenerator())
  2918. {
  2919. return;
  2920. }
  2921. scriptContext->GetNativeCodeGenerator()->QueueFreeNativeCodeGenAllocation((void*)codeAddress, (void*)thunkAddress);
  2922. }
  2923. bool TryReleaseNonHiPriWorkItem(Js::ScriptContext* scriptContext, CodeGenWorkItem* workItem)
  2924. {
  2925. if (!scriptContext->GetNativeCodeGenerator())
  2926. {
  2927. return false;
  2928. }
  2929. return scriptContext->GetNativeCodeGenerator()->TryReleaseNonHiPriWorkItem(workItem);
  2930. }
  2931. // Called from within the lock
  2932. // The work item cannot be used after this point if it returns true
  2933. bool NativeCodeGenerator::TryReleaseNonHiPriWorkItem(CodeGenWorkItem* workItem)
  2934. {
  2935. // If its the highest priority, don't release it, let the job continue
  2936. if (workItem->IsInJitQueue())
  2937. {
  2938. return false;
  2939. }
  2940. workItems.Unlink(workItem);
  2941. Assert(!workItem->RecyclableData());
  2942. workItem->Delete();
  2943. return true;
  2944. }
  2945. void
  2946. NativeCodeGenerator::FreeNativeCodeGenAllocation(void* codeAddress)
  2947. {
  2948. if (JITManager::GetJITManager()->IsOOPJITEnabled())
  2949. {
  2950. #if PDATA_ENABLED && defined(_WIN32)
  2951. DelayDeletingFunctionTable::Clear();
  2952. #endif
  2953. HRESULT hr = JITManager::GetJITManager()->FreeAllocation(this->scriptContext->GetRemoteScriptAddr(), (intptr_t)codeAddress);
  2954. JITManager::HandleServerCallResult(hr, RemoteCallType::MemFree);
  2955. }
  2956. else if(this->backgroundAllocators)
  2957. {
  2958. this->backgroundAllocators->emitBufferManager.FreeAllocation(codeAddress);
  2959. }
  2960. }
  2961. void
  2962. NativeCodeGenerator::QueueFreeNativeCodeGenAllocation(void* codeAddress, void * thunkAddress)
  2963. {
  2964. ASSERT_THREAD();
  2965. if(IsClosed())
  2966. {
  2967. return;
  2968. }
  2969. if (JITManager::GetJITManager()->IsOOPJITEnabled() && !CONFIG_FLAG(OOPCFGRegistration))
  2970. {
  2971. //DeRegister Entry Point for CFG
  2972. if (thunkAddress)
  2973. {
  2974. ThreadContext::GetContextForCurrentThread()->SetValidCallTargetForCFG(thunkAddress, false);
  2975. }
  2976. else
  2977. {
  2978. ThreadContext::GetContextForCurrentThread()->SetValidCallTargetForCFG(codeAddress, false);
  2979. }
  2980. }
  2981. if ((!JITManager::GetJITManager()->IsOOPJITEnabled() && !this->scriptContext->GetThreadContext()->GetPreReservedVirtualAllocator()->IsInRange((void*)codeAddress)) ||
  2982. (JITManager::GetJITManager()->IsOOPJITEnabled() && !PreReservedVirtualAllocWrapper::IsInRange((void*)this->scriptContext->GetThreadContext()->GetPreReservedRegionAddr(), (void*)codeAddress)))
  2983. {
  2984. this->scriptContext->GetJitFuncRangeCache()->RemoveFuncRange((void*)codeAddress);
  2985. }
  2986. // OOP JIT will always queue a job
  2987. // The foreground allocators may have been used
  2988. if (this->foregroundAllocators && this->foregroundAllocators->emitBufferManager.FreeAllocation(codeAddress))
  2989. {
  2990. return;
  2991. }
  2992. // The background allocators were used. Queue a job to free the allocation from the background thread.
  2993. this->freeLoopBodyManager.QueueFreeLoopBodyJob(codeAddress, thunkAddress);
  2994. }
  2995. void NativeCodeGenerator::FreeLoopBodyJobManager::QueueFreeLoopBodyJob(void* codeAddress, void * thunkAddress)
  2996. {
  2997. Assert(!this->isClosed);
  2998. FreeLoopBodyJob* job = HeapNewNoThrow(FreeLoopBodyJob, this, codeAddress, thunkAddress);
  2999. if (job == nullptr)
  3000. {
  3001. FreeLoopBodyJob stackJob(this, codeAddress, thunkAddress, false /* heapAllocated */);
  3002. {
  3003. AutoOptionalCriticalSection lock(Processor()->GetCriticalSection());
  3004. #if DBG
  3005. this->waitingForStackJob = true;
  3006. #endif
  3007. this->stackJobProcessed = false;
  3008. Processor()->AddJob(&stackJob);
  3009. }
  3010. Processor()->PrioritizeJobAndWait(this, &stackJob);
  3011. }
  3012. else
  3013. {
  3014. AutoOptionalCriticalSection lock(Processor()->GetCriticalSection());
  3015. if (Processor()->HasManager(this))
  3016. {
  3017. Processor()->AddJobAndProcessProactively<FreeLoopBodyJobManager, FreeLoopBodyJob*>(this, job);
  3018. }
  3019. else
  3020. {
  3021. HeapDelete(job);
  3022. }
  3023. }
  3024. }
  3025. #ifdef PROFILE_EXEC
  3026. void
  3027. NativeCodeGenerator::CreateProfiler(Js::ScriptContextProfiler * profiler)
  3028. {
  3029. Assert(this->foregroundCodeGenProfiler == nullptr);
  3030. this->foregroundCodeGenProfiler = profiler;
  3031. profiler->AddRef();
  3032. }
  3033. Js::ScriptContextProfiler *
  3034. NativeCodeGenerator::EnsureForegroundCodeGenProfiler()
  3035. {
  3036. if (Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag))
  3037. {
  3038. Assert(this->foregroundCodeGenProfiler != nullptr);
  3039. Assert(this->foregroundCodeGenProfiler->IsInitialized());
  3040. }
  3041. return this->foregroundCodeGenProfiler;
  3042. }
  3043. void
  3044. NativeCodeGenerator::SetProfilerFromNativeCodeGen(NativeCodeGenerator * nativeCodeGen)
  3045. {
  3046. Assert(Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag));
  3047. Assert(this->foregroundCodeGenProfiler != nullptr);
  3048. Assert(this->foregroundCodeGenProfiler->IsInitialized());
  3049. Assert(nativeCodeGen->foregroundCodeGenProfiler != nullptr);
  3050. Assert(nativeCodeGen->foregroundCodeGenProfiler->IsInitialized());
  3051. this->foregroundCodeGenProfiler->Release();
  3052. this->foregroundCodeGenProfiler = nativeCodeGen->foregroundCodeGenProfiler;
  3053. this->foregroundCodeGenProfiler->AddRef();
  3054. }
  3055. void
  3056. NativeCodeGenerator::ProfilePrint()
  3057. {
  3058. this->backgroundCodeGenProfiler->ProfilePrint();
  3059. }
  3060. void
  3061. NativeCodeGenerator::ProfileBegin(Js::ScriptContextProfiler *const profiler, Js::Phase phase)
  3062. {
  3063. AssertMsg((profiler != nullptr) == Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag),
  3064. "Profiler tag is supplied but the profiler pointer is NULL");
  3065. if (profiler)
  3066. {
  3067. profiler->ProfileBegin(phase);
  3068. }
  3069. }
  3070. void
  3071. NativeCodeGenerator::ProfileEnd(Js::ScriptContextProfiler *const profiler, Js::Phase phase)
  3072. {
  3073. AssertMsg((profiler != nullptr) == Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag),
  3074. "Profiler tag is supplied but the profiler pointer is NULL");
  3075. if (profiler)
  3076. {
  3077. profiler->ProfileEnd(phase);
  3078. }
  3079. }
  3080. #endif
  3081. void NativeCodeGenerator::AddToJitQueue(CodeGenWorkItem *const codeGenWorkItem, bool prioritize, bool lock, void* function)
  3082. {
  3083. codeGenWorkItem->VerifyJitMode();
  3084. Js::CodeGenRecyclableData* recyclableData = GatherCodeGenData(codeGenWorkItem->GetFunctionBody(), codeGenWorkItem->GetFunctionBody(), codeGenWorkItem->GetEntryPoint(), codeGenWorkItem, function);
  3085. codeGenWorkItem->SetRecyclableData(recyclableData);
  3086. AutoOptionalCriticalSection autoLock(lock ? Processor()->GetCriticalSection() : nullptr);
  3087. scriptContext->GetThreadContext()->RegisterCodeGenRecyclableData(recyclableData);
  3088. // If we have added a lot of jobs that are still waiting to be jitted, remove the oldest job
  3089. // to ensure we do not spend time jitting stale work items.
  3090. const ExecutionMode jitMode = codeGenWorkItem->GetJitMode();
  3091. if(jitMode == ExecutionMode::FullJit &&
  3092. queuedFullJitWorkItemCount >= (unsigned int)CONFIG_FLAG(JitQueueThreshold))
  3093. {
  3094. CodeGenWorkItem *const workItemRemoved = queuedFullJitWorkItems.Tail()->WorkItem();
  3095. Assert(workItemRemoved->GetJitMode() == ExecutionMode::FullJit);
  3096. if(Processor()->RemoveJob(workItemRemoved))
  3097. {
  3098. queuedFullJitWorkItems.UnlinkFromEnd();
  3099. --queuedFullJitWorkItemCount;
  3100. workItemRemoved->OnRemoveFromJitQueue(this);
  3101. }
  3102. }
  3103. Processor()->AddJob(codeGenWorkItem, prioritize); // This one can throw (really unlikely though), OOM specifically.
  3104. if(jitMode == ExecutionMode::FullJit)
  3105. {
  3106. QueuedFullJitWorkItem *const queuedFullJitWorkItem = codeGenWorkItem->EnsureQueuedFullJitWorkItem();
  3107. if(queuedFullJitWorkItem) // ignore OOM, this work item just won't be removed from the job processor's queue
  3108. {
  3109. if(prioritize)
  3110. {
  3111. queuedFullJitWorkItems.LinkToBeginning(queuedFullJitWorkItem);
  3112. }
  3113. else
  3114. {
  3115. queuedFullJitWorkItems.LinkToEnd(queuedFullJitWorkItem);
  3116. }
  3117. ++queuedFullJitWorkItemCount;
  3118. }
  3119. }
  3120. codeGenWorkItem->OnAddToJitQueue();
  3121. }
  3122. void NativeCodeGenerator::AddWorkItem(CodeGenWorkItem* workitem)
  3123. {
  3124. workitem->ResetJitMode();
  3125. workItems.LinkToEnd(workitem);
  3126. }
  3127. Js::ScriptContextProfiler * NativeCodeGenerator::GetBackgroundCodeGenProfiler(PageAllocator *allocator)
  3128. {
  3129. #ifdef PROFILE_EXEC
  3130. if (Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag))
  3131. {
  3132. Js::ScriptContextProfiler *codegenProfiler = this->backgroundCodeGenProfiler;
  3133. while (codegenProfiler)
  3134. {
  3135. if (codegenProfiler->pageAllocator == allocator)
  3136. {
  3137. if (!codegenProfiler->IsInitialized())
  3138. {
  3139. codegenProfiler->Initialize(allocator, nullptr);
  3140. }
  3141. return codegenProfiler;
  3142. }
  3143. codegenProfiler = codegenProfiler->next;
  3144. }
  3145. Assert(false);
  3146. }
  3147. return nullptr;
  3148. #else
  3149. return nullptr;
  3150. #endif
  3151. }
  3152. void NativeCodeGenerator::AllocateBackgroundCodeGenProfiler(PageAllocator *pageAllocator)
  3153. {
  3154. #ifdef PROFILE_EXEC
  3155. if (Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag))
  3156. {
  3157. Js::ScriptContextProfiler *codegenProfiler = NoCheckHeapNew(Js::ScriptContextProfiler);
  3158. codegenProfiler->pageAllocator = pageAllocator;
  3159. codegenProfiler->next = this->backgroundCodeGenProfiler;
  3160. this->backgroundCodeGenProfiler = codegenProfiler;
  3161. }
  3162. #endif
  3163. }
  3164. bool NativeCodeGenerator::TryAggressiveInlining(Js::FunctionBody *const topFunctionBody, Js::FunctionBody *const inlineeFunctionBody, InliningDecider &inliningDecider, uint& inlineeCount, uint recursiveInlineDepth)
  3165. {
  3166. PROBE_STACK_NO_DISPOSE(scriptContext, Js::Constants::MinStackDefault);
  3167. if (!inlineeFunctionBody->GetProfiledCallSiteCount())
  3168. {
  3169. // Nothing to inline. See this as fully inlinable function.
  3170. return true;
  3171. }
  3172. class AutoCleanup
  3173. {
  3174. private:
  3175. Js::FunctionBody *const functionBody;
  3176. public:
  3177. AutoCleanup(Js::FunctionBody *const functionBody) : functionBody(functionBody)
  3178. {
  3179. functionBody->OnBeginInlineInto();
  3180. }
  3181. ~AutoCleanup()
  3182. {
  3183. functionBody->OnEndInlineInto();
  3184. }
  3185. } autoCleanup(inlineeFunctionBody);
  3186. #if defined(DBG_DUMP) || defined(ENABLE_DEBUG_CONFIG_OPTIONS)
  3187. class AutoTrace
  3188. {
  3189. Js::FunctionBody *const topFunc;
  3190. Js::FunctionBody *const inlineeFunc;
  3191. uint32& inlineeCount;
  3192. bool done;
  3193. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  3194. char16 debugStringBuffer2[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  3195. public:
  3196. AutoTrace(Js::FunctionBody *const topFunctionBody, Js::FunctionBody *const inlineeFunctionBody, uint32& inlineeCount) : topFunc(topFunctionBody),
  3197. inlineeFunc(inlineeFunctionBody), done(false), inlineeCount(inlineeCount)
  3198. {
  3199. if (topFunc == inlineeFunc)
  3200. {
  3201. INLINE_TESTTRACE(_u("INLINING: Recursive tryAggressiveInlining started topFunc: %s (%s)\n"), topFunc->GetDisplayName(),
  3202. topFunc->GetDebugNumberSet(debugStringBuffer))
  3203. }
  3204. }
  3205. void Done(bool success)
  3206. {
  3207. if (success)
  3208. {
  3209. done = true;
  3210. if (topFunc == inlineeFunc)
  3211. {
  3212. INLINE_TESTTRACE(_u("INLINING: Recursive tryAggressiveInlining succeeded topFunc: %s (%s), inlinee count: %d\n"), topFunc->GetDisplayName(),
  3213. topFunc->GetDebugNumberSet(debugStringBuffer), inlineeCount);
  3214. }
  3215. else
  3216. {
  3217. INLINE_TESTTRACE(_u("INLINING: TryAggressiveInlining succeeded topFunc: %s (%s), inlinee: %s (%s) \n"), topFunc->GetDisplayName(),
  3218. topFunc->GetDebugNumberSet(debugStringBuffer),
  3219. inlineeFunc->GetDisplayName(),
  3220. inlineeFunc->GetDebugNumberSet(debugStringBuffer2));
  3221. }
  3222. }
  3223. else
  3224. {
  3225. Assert(done == false);
  3226. }
  3227. }
  3228. void TraceFailure(const char16 *message)
  3229. {
  3230. INLINE_TESTTRACE(_u("INLINING: TryAggressiveInlining failed topFunc (%s): %s (%s), inlinee: %s (%s) \n"), message, topFunc->GetDisplayName(),
  3231. topFunc->GetDebugNumberSet(debugStringBuffer),
  3232. inlineeFunc->GetDisplayName(),
  3233. inlineeFunc->GetDebugNumberSet(debugStringBuffer2));
  3234. }
  3235. ~AutoTrace()
  3236. {
  3237. if (!done)
  3238. {
  3239. if (topFunc == inlineeFunc)
  3240. {
  3241. INLINE_TESTTRACE(_u("INLINING: Recursive tryAggressiveInlining failed topFunc: %s (%s)\n"), topFunc->GetDisplayName(),
  3242. topFunc->GetDebugNumberSet(debugStringBuffer));
  3243. }
  3244. else
  3245. {
  3246. INLINE_TESTTRACE(_u("INLINING: TryAggressiveInlining failed topFunc: %s (%s), inlinee: %s (%s) \n"), topFunc->GetDisplayName(),
  3247. topFunc->GetDebugNumberSet(debugStringBuffer),
  3248. inlineeFunc->GetDisplayName(),
  3249. inlineeFunc->GetDebugNumberSet(debugStringBuffer2));
  3250. }
  3251. }
  3252. }
  3253. };
  3254. AutoTrace trace(topFunctionBody, inlineeFunctionBody, inlineeCount);
  3255. #endif
  3256. if (inlineeFunctionBody->GetProfiledSwitchCount())
  3257. {
  3258. #if defined(DBG_DUMP) || defined(ENABLE_DEBUG_CONFIG_OPTIONS)
  3259. trace.TraceFailure(_u("Switch statement in inlinee"));
  3260. #endif
  3261. return false;
  3262. }
  3263. bool isInlinee = topFunctionBody != inlineeFunctionBody;
  3264. if (isInlinee ? !inliningDecider.InlineIntoInliner(inlineeFunctionBody) : !inliningDecider.InlineIntoTopFunc())
  3265. {
  3266. return false;
  3267. }
  3268. const auto profiledCallSiteCount = inlineeFunctionBody->GetProfiledCallSiteCount();
  3269. for (Js::ProfileId profiledCallSiteId = 0; profiledCallSiteId < profiledCallSiteCount; ++profiledCallSiteId)
  3270. {
  3271. bool isConstructorCall = false;
  3272. bool isPolymorphicCall = false;
  3273. if (!inlineeFunctionBody->IsJsBuiltInCode() && !inliningDecider.HasCallSiteInfo(inlineeFunctionBody, profiledCallSiteId))
  3274. {
  3275. //There is no callsite information. We should hit bailonnoprofile for these callsites. Ignore.
  3276. continue;
  3277. }
  3278. Js::FunctionInfo *inlinee = inliningDecider.GetCallSiteFuncInfo(inlineeFunctionBody, profiledCallSiteId, &isConstructorCall, &isPolymorphicCall);
  3279. if (!inlinee)
  3280. {
  3281. if (isPolymorphicCall)
  3282. {
  3283. //Try and see if this polymorphic call
  3284. Js::FunctionBody* inlineeFunctionBodyArray[Js::DynamicProfileInfo::maxPolymorphicInliningSize] = { 0 };
  3285. bool canInlineArray[Js::DynamicProfileInfo::maxPolymorphicInliningSize] = { 0 };
  3286. uint polyInlineeCount = inliningDecider.InlinePolymorphicCallSite(inlineeFunctionBody, profiledCallSiteId, inlineeFunctionBodyArray,
  3287. Js::DynamicProfileInfo::maxPolymorphicInliningSize, canInlineArray);
  3288. //We should be able to inline everything here.
  3289. if (polyInlineeCount >= 2)
  3290. {
  3291. for (uint i = 0; i < polyInlineeCount; i++)
  3292. {
  3293. bool isInlined = canInlineArray[i];
  3294. if (isInlined)
  3295. {
  3296. ++inlineeCount;
  3297. if (!TryAggressiveInlining(topFunctionBody, inlineeFunctionBodyArray[i], inliningDecider, inlineeCount, inlineeFunctionBody == inlineeFunctionBodyArray[i] ? recursiveInlineDepth + 1 : 0))
  3298. {
  3299. return false;
  3300. }
  3301. }
  3302. else
  3303. {
  3304. return false;
  3305. }
  3306. }
  3307. }
  3308. else
  3309. {
  3310. return false;
  3311. }
  3312. }
  3313. else
  3314. {
  3315. return false;
  3316. }
  3317. }
  3318. else
  3319. {
  3320. inlinee = inliningDecider.Inline(inlineeFunctionBody, inlinee, isConstructorCall, false, false, inliningDecider.GetConstantArgInfo(inlineeFunctionBody, profiledCallSiteId), profiledCallSiteId, inlineeFunctionBody->GetFunctionInfo() == inlinee ? recursiveInlineDepth + 1 : 0, true);
  3321. if (!inlinee)
  3322. {
  3323. return false;
  3324. }
  3325. Js::FunctionBody *const functionBody = inlinee->GetFunctionBody();
  3326. if (!functionBody)
  3327. {
  3328. //Built-in
  3329. continue;
  3330. }
  3331. //Recursive call
  3332. ++inlineeCount;
  3333. if (!TryAggressiveInlining(topFunctionBody, functionBody, inliningDecider, inlineeCount, inlineeFunctionBody == functionBody ? recursiveInlineDepth + 1 : 0 ))
  3334. {
  3335. return false;
  3336. }
  3337. }
  3338. }
  3339. #if defined(DBG_DUMP) || defined(ENABLE_DEBUG_CONFIG_OPTIONS)
  3340. trace.Done(true);
  3341. #endif
  3342. return true;
  3343. }
  3344. #if _WIN32
  3345. bool
  3346. JITManager::HandleServerCallResult(HRESULT hr, RemoteCallType callType)
  3347. {
  3348. // handle the normal hresults
  3349. switch (hr)
  3350. {
  3351. case S_OK:
  3352. return true;
  3353. case E_ABORT:
  3354. throw Js::OperationAbortedException();
  3355. case 0x800705af: // = HRESULT_FROM_WIN32(ERROR_COMMITMENT_LIMIT) some of our tooling does not yet support constexpr switch labels.
  3356. case E_OUTOFMEMORY:
  3357. if (callType == RemoteCallType::MemFree)
  3358. {
  3359. // if freeing memory fails due to OOM, it means we failed to fill with debug breaks -- so failfast
  3360. RpcFailure_unrecoverable_error(hr);
  3361. }
  3362. else
  3363. {
  3364. Js::Throw::OutOfMemory();
  3365. }
  3366. case VBSERR_OutOfStack:
  3367. throw Js::StackOverflowException();
  3368. default:
  3369. break;
  3370. }
  3371. if (CONFIG_FLAG(CrashOnOOPJITFailure))
  3372. {
  3373. RpcFailure_unrecoverable_error(hr);
  3374. }
  3375. // we only expect to see these hresults in case server has been closed. failfast otherwise
  3376. if (hr != HRESULT_FROM_WIN32(RPC_S_CALL_FAILED) &&
  3377. hr != HRESULT_FROM_WIN32(RPC_S_CALL_FAILED_DNE))
  3378. {
  3379. RpcFailure_unrecoverable_error(hr);
  3380. }
  3381. // if JIT process is gone, record that and stop trying to call it
  3382. GetJITManager()->SetJITFailed(hr);
  3383. switch (callType)
  3384. {
  3385. case RemoteCallType::CodeGen:
  3386. // inform job manager that JIT work item has been cancelled
  3387. throw Js::OperationAbortedException();
  3388. #if DBG
  3389. case RemoteCallType::HeapQuery:
  3390. #endif
  3391. case RemoteCallType::ThunkCreation:
  3392. case RemoteCallType::StateUpdate:
  3393. case RemoteCallType::MemFree:
  3394. // if server process is gone, we can ignore failures updating its state
  3395. return false;
  3396. default:
  3397. Assert(UNREACHED);
  3398. RpcFailure_unrecoverable_error(hr);
  3399. }
  3400. return false;
  3401. }
  3402. #endif