NativeCodeGenerator.cpp 147 KB

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