BailOut.cpp 131 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft Corporation and contributors. 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. #ifdef ENABLE_SCRIPT_DEBUGGING
  7. #include "Debug/DebuggingFlags.h"
  8. #include "Debug/DiagProbe.h"
  9. #include "Debug/DebugManager.h"
  10. #endif
  11. #include "Language/JavascriptFunctionArgIndex.h"
  12. extern const IRType RegTypes[RegNumCount];
  13. void
  14. BailOutInfo::Clear(JitArenaAllocator * allocator)
  15. {
  16. // Currently, we don't have a case where we delete bailout info after we allocated the bailout record
  17. Assert(!bailOutRecord);
  18. if (this->capturedValues && this->capturedValues->DecrementRefCount() == 0)
  19. {
  20. this->capturedValues->constantValues.Clear(allocator);
  21. this->capturedValues->copyPropSyms.Clear(allocator);
  22. JitAdelete(allocator, this->capturedValues);
  23. }
  24. this->usedCapturedValues.constantValues.Clear(allocator);
  25. this->usedCapturedValues.copyPropSyms.Clear(allocator);
  26. if (byteCodeUpwardExposedUsed)
  27. {
  28. JitAdelete(allocator, byteCodeUpwardExposedUsed);
  29. }
  30. if (startCallInfo)
  31. {
  32. Assert(argOutSyms);
  33. JitAdeleteArray(allocator, startCallCount, startCallInfo);
  34. JitAdeleteArray(allocator, totalOutParamCount, argOutSyms);
  35. }
  36. if (liveVarSyms)
  37. {
  38. JitAdelete(allocator, liveVarSyms);
  39. JitAdelete(allocator, liveLosslessInt32Syms);
  40. JitAdelete(allocator, liveFloat64Syms);
  41. }
  42. #ifdef _M_IX86
  43. if (outParamFrameAdjustArgSlot)
  44. {
  45. JitAdelete(allocator, outParamFrameAdjustArgSlot);
  46. }
  47. #endif
  48. }
  49. #ifdef _M_IX86
  50. uint
  51. BailOutInfo::GetStartCallOutParamCount(uint i) const
  52. {
  53. Assert(i < this->startCallCount);
  54. Assert(this->startCallInfo);
  55. return this->startCallInfo[i].argCount;
  56. }
  57. bool
  58. BailOutInfo::NeedsStartCallAdjust(uint i, const IR::Instr * bailOutInstr) const
  59. {
  60. Assert(i < this->startCallCount);
  61. Assert(this->startCallInfo);
  62. Assert(bailOutInstr->m_func->HasInstrNumber());
  63. IR::Instr * instr = this->startCallInfo[i].instr;
  64. if (instr == nullptr || instr->m_opcode == Js::OpCode::StartCall)
  65. {
  66. // The StartCall was unlinked (because it was being deleted, or we know it was
  67. // moved below the bailout instr).
  68. // -------- or --------
  69. // StartCall wasn't lowered because the argouts were orphaned, in which case we don't need
  70. // the adjustment as the orphaned argouts are not stored with the non-orphaned ones
  71. return false;
  72. }
  73. // In scenarios related to partial polymorphic inlining where we move the lowered version of the start call - LEA esp, esp - argcount * 4
  74. // next to the call itself as part of one of the dispatch arms. In this scenario StartCall is marked
  75. // as cloned and we do not need to adjust the offsets from where the args need to be restored.
  76. return instr->GetNumber() < bailOutInstr->GetNumber() && !instr->IsCloned();
  77. }
  78. void
  79. BailOutInfo::RecordStartCallInfo(uint i, IR::Instr *instr)
  80. {
  81. Assert(i < this->startCallCount);
  82. Assert(this->startCallInfo);
  83. Assert(instr);
  84. Assert(instr->m_opcode == Js::OpCode::StartCall);
  85. this->startCallInfo[i].instr = instr;
  86. this->startCallInfo[i].argCount = instr->GetArgOutCount(/*getInterpreterArgOutCount*/ true);
  87. this->startCallInfo[i].argRestoreAdjustCount = 0;
  88. this->startCallInfo[i].isOrphanedCall = false;
  89. }
  90. void
  91. BailOutInfo::UnlinkStartCall(const IR::Instr * instr)
  92. {
  93. Assert(this->startCallCount == 0 || this->startCallInfo != nullptr);
  94. uint i;
  95. for (i = 0; i < this->startCallCount; i++)
  96. {
  97. StartCallInfo *info = &this->startCallInfo[i];
  98. if (info->instr == instr)
  99. {
  100. info->instr = nullptr;
  101. return;
  102. }
  103. }
  104. }
  105. #else
  106. uint
  107. BailOutInfo::GetStartCallOutParamCount(uint i) const
  108. {
  109. Assert(i < this->startCallCount);
  110. Assert(this->startCallInfo);
  111. return this->startCallInfo[i];
  112. }
  113. void
  114. BailOutInfo::RecordStartCallInfo(uint i, IR::Instr *instr)
  115. {
  116. Assert(i < this->startCallCount);
  117. Assert(this->startCallInfo);
  118. Assert(instr);
  119. Assert(instr->m_opcode == Js::OpCode::StartCall);
  120. Assert(instr->GetSrc1());
  121. this->startCallInfo[i] = instr->GetArgOutCount(/*getInterpreterArgOutCount*/ true);
  122. }
  123. #endif
  124. #ifdef MD_GROW_LOCALS_AREA_UP
  125. void
  126. BailOutInfo::FinalizeOffsets(__in_ecount(count) int * offsets, uint count, Func *func, BVSparse<JitArenaAllocator> *bvInlinedArgSlot)
  127. {
  128. // Turn positive SP-relative sym offsets into negative frame-pointer-relative offsets for the convenience
  129. // of the restore-value logic.
  130. int32 inlineeArgStackSize = func->GetInlineeArgumentStackSize();
  131. int localsSize = func->m_localStackHeight + func->m_ArgumentsOffset;
  132. for (uint i = 0; i < count; i++)
  133. {
  134. int offset = -(offsets[i] + StackSymBias);
  135. if (offset < 0)
  136. {
  137. // Not stack offset
  138. continue;
  139. }
  140. if (bvInlinedArgSlot && bvInlinedArgSlot->Test(i))
  141. {
  142. // Inlined out param: the positive offset is relative to the start of the inlinee arg area,
  143. // so we need to subtract the full locals area (including the inlined-arg-area) to get the proper result.
  144. offset -= localsSize;
  145. }
  146. else
  147. {
  148. // The locals size contains the inlined-arg-area size, so remove the inlined-arg-area size from the
  149. // adjustment for normal locals whose offsets are relative to the start of the locals area.
  150. offset -= (localsSize - inlineeArgStackSize);
  151. }
  152. Assert(offset < 0);
  153. offsets[i] = offset;
  154. }
  155. }
  156. #endif
  157. void
  158. BailOutInfo::FinalizeBailOutRecord(Func * func)
  159. {
  160. Assert(func->IsTopFunc());
  161. BailOutRecord * bailOutRecord = this->bailOutRecord;
  162. if (bailOutRecord == nullptr)
  163. {
  164. return;
  165. }
  166. BailOutRecord * currentBailOutRecord = bailOutRecord;
  167. Func * currentBailOutFunc = this->bailOutFunc;
  168. // Top of the inlined arg stack is at the beginning of the locals, find the offset from EBP+2
  169. #ifdef MD_GROW_LOCALS_AREA_UP
  170. uint inlinedArgSlotAdjust = (func->m_localStackHeight + func->m_ArgumentsOffset);
  171. #else
  172. uint inlinedArgSlotAdjust = (func->m_localStackHeight + (2 * MachPtr));
  173. #endif
  174. while (currentBailOutRecord->parent != nullptr)
  175. {
  176. Assert(currentBailOutRecord->globalBailOutRecordTable->firstActualStackOffset == -1 ||
  177. currentBailOutRecord->globalBailOutRecordTable->firstActualStackOffset == (int32)(currentBailOutFunc->firstActualStackOffset - inlinedArgSlotAdjust));
  178. Assert(!currentBailOutFunc->IsTopFunc());
  179. Assert(currentBailOutFunc->firstActualStackOffset != -1);
  180. // Find the top of the locals on the stack from EBP
  181. currentBailOutRecord->globalBailOutRecordTable->firstActualStackOffset = currentBailOutFunc->firstActualStackOffset - inlinedArgSlotAdjust;
  182. currentBailOutRecord = currentBailOutRecord->parent;
  183. currentBailOutFunc = currentBailOutFunc->GetParentFunc();
  184. }
  185. Assert(currentBailOutRecord->globalBailOutRecordTable->firstActualStackOffset == -1);
  186. Assert(currentBailOutFunc->IsTopFunc());
  187. Assert(currentBailOutFunc->firstActualStackOffset == -1);
  188. #ifndef MD_GROW_LOCALS_AREA_UP
  189. if (this->totalOutParamCount != 0)
  190. {
  191. if (func->HasInlinee())
  192. {
  193. FOREACH_BITSET_IN_SPARSEBV(index, this->outParamInlinedArgSlot)
  194. {
  195. this->outParamOffsets[index] -= inlinedArgSlotAdjust;
  196. }
  197. NEXT_BITSET_IN_SPARSEBV;
  198. }
  199. #ifdef _M_IX86
  200. int frameSize = func->frameSize;
  201. AssertMsg(frameSize != 0, "Frame size not calculated");
  202. FOREACH_BITSET_IN_SPARSEBV(index, this->outParamFrameAdjustArgSlot)
  203. {
  204. this->outParamOffsets[index] -= frameSize;
  205. }
  206. NEXT_BITSET_IN_SPARSEBV;
  207. #endif
  208. }
  209. #else
  210. if (func->IsJitInDebugMode())
  211. {
  212. // Turn positive SP-relative base locals offset into negative frame-pointer-relative offset
  213. func->AjustLocalVarSlotOffset();
  214. }
  215. currentBailOutRecord = bailOutRecord;
  216. int32 inlineeArgStackSize = func->GetInlineeArgumentStackSize();
  217. do
  218. {
  219. // Note: do this only once
  220. currentBailOutRecord->globalBailOutRecordTable->VisitGlobalBailOutRecordTableRowsAtFirstBailOut(
  221. currentBailOutRecord->m_bailOutRecordId, [=](GlobalBailOutRecordDataRow *row) {
  222. int offset = -(row->offset + StackSymBias);
  223. if (offset < 0)
  224. {
  225. // Not stack offset
  226. return;
  227. }
  228. // The locals size contains the inlined-arg-area size, so remove the inlined-arg-area size from the
  229. // adjustment for normal locals whose offsets are relative to the start of the locals area.
  230. offset -= (inlinedArgSlotAdjust - inlineeArgStackSize);
  231. Assert(offset < 0);
  232. row->offset = offset;
  233. });
  234. // Only adjust once
  235. int forInEnumeratorArrayRestoreOffset = currentBailOutRecord->globalBailOutRecordTable->forInEnumeratorArrayRestoreOffset;
  236. if (forInEnumeratorArrayRestoreOffset >= 0)
  237. {
  238. forInEnumeratorArrayRestoreOffset -= (inlinedArgSlotAdjust - inlineeArgStackSize);
  239. Assert(forInEnumeratorArrayRestoreOffset < 0);
  240. currentBailOutRecord->globalBailOutRecordTable->forInEnumeratorArrayRestoreOffset = forInEnumeratorArrayRestoreOffset;
  241. }
  242. currentBailOutRecord = currentBailOutRecord->parent;
  243. }
  244. while (currentBailOutRecord != nullptr);
  245. this->FinalizeOffsets(this->outParamOffsets, this->totalOutParamCount, func, func->HasInlinee() ? this->outParamInlinedArgSlot : nullptr);
  246. #endif
  247. // set the bailOutRecord to null so we don't adjust it again if the info is shared
  248. bailOutRecord = nullptr;
  249. }
  250. #if DBG
  251. bool
  252. BailOutInfo::IsBailOutHelper(IR::JnHelperMethod helper)
  253. {
  254. switch (helper)
  255. {
  256. case IR::HelperSaveAllRegistersAndBailOut:
  257. case IR::HelperSaveAllRegistersAndBranchBailOut:
  258. #ifdef _M_IX86
  259. case IR::HelperSaveAllRegistersNoSse2AndBailOut:
  260. case IR::HelperSaveAllRegistersNoSse2AndBranchBailOut:
  261. #endif
  262. return true;
  263. };
  264. return false;
  265. };
  266. #endif
  267. //===================================================================================================================================
  268. // BailOutRecord
  269. //===================================================================================================================================
  270. BailOutRecord::BailOutRecord(uint32 bailOutOffset, uint bailOutCacheIndex, IR::BailOutKind kind, Func * bailOutFunc) :
  271. argOutOffsetInfo(nullptr), bailOutOffset(bailOutOffset),
  272. bailOutCount(0), polymorphicCacheIndex(bailOutCacheIndex), bailOutKind(kind),
  273. branchValueRegSlot(Js::Constants::NoRegister),
  274. ehBailoutData(nullptr), m_bailOutRecordId(0), type(Normal)
  275. #if DBG
  276. , inlineDepth(0)
  277. #endif
  278. {
  279. CompileAssert(offsetof(BailOutRecord, globalBailOutRecordTable) == 0); // the offset is hard-coded in LinearScanMD::SaveAllRegisters
  280. CompileAssert(offsetof(GlobalBailOutRecordDataTable, registerSaveSpace) == 0); // the offset is hard-coded in LinearScanMD::SaveAllRegisters}
  281. Assert(bailOutOffset != Js::Constants::NoByteCodeOffset);
  282. #if DBG
  283. actualCount = bailOutFunc->actualCount;
  284. Assert(bailOutFunc->IsTopFunc() || actualCount != -1);
  285. #endif
  286. }
  287. #if ENABLE_DEBUG_CONFIG_OPTIONS
  288. #define REJIT_KIND_TESTTRACE(bailOutKind, ...) \
  289. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::ReJITPhase)) \
  290. { \
  291. if (Js::Configuration::Global.flags.RejitTraceFilter.Empty() || Js::Configuration::Global.flags.RejitTraceFilter.Contains(bailOutKind)) \
  292. { \
  293. Output::Print(__VA_ARGS__); \
  294. Output::Flush(); \
  295. } \
  296. }
  297. const char16 * const trueString = _u("true");
  298. const char16 * const falseString = _u("false");
  299. #else
  300. #define REJIT_KIND_TESTTRACE(...)
  301. #endif
  302. #if ENABLE_DEBUG_CONFIG_OPTIONS
  303. #define BAILOUT_KIND_TRACE(functionBody, bailOutKind, ...) \
  304. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::BailOutPhase, functionBody->GetSourceContextId(),functionBody->GetLocalFunctionId()) && \
  305. ((bailOutKind) != IR::BailOnSimpleJitToFullJitLoopBody || CONFIG_FLAG(Verbose))) \
  306. { \
  307. if (Js::Configuration::Global.flags.BailoutTraceFilter.Empty() || Js::Configuration::Global.flags.BailoutTraceFilter.Contains(bailOutKind)) \
  308. { \
  309. Output::Print(__VA_ARGS__); \
  310. if (bailOutKind != IR::BailOutInvalid) \
  311. { \
  312. Output::Print(_u(" Kind: %S"), ::GetBailOutKindName(bailOutKind)); \
  313. } \
  314. Output::Print(_u("\n")); \
  315. } \
  316. }
  317. #define BAILOUT_VERBOSE_TRACE(functionBody, bailOutKind, ...) \
  318. if (Js::Configuration::Global.flags.Verbose && Js::Configuration::Global.flags.Trace.IsEnabled(Js::BailOutPhase,functionBody->GetSourceContextId(),functionBody->GetLocalFunctionId())) \
  319. { \
  320. if (Js::Configuration::Global.flags.BailoutTraceFilter.Empty() || Js::Configuration::Global.flags.BailoutTraceFilter.Contains(bailOutKind)) \
  321. { \
  322. Output::Print(__VA_ARGS__); \
  323. } \
  324. }
  325. #define BAILOUT_TESTTRACE(functionBody, bailOutKind, ...) \
  326. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::BailOutPhase, functionBody->GetSourceContextId(),functionBody->GetLocalFunctionId()) && \
  327. ((bailOutKind) != IR::BailOnSimpleJitToFullJitLoopBody || CONFIG_FLAG(Verbose))) \
  328. { \
  329. if (Js::Configuration::Global.flags.BailoutTraceFilter.Empty() || Js::Configuration::Global.flags.BailoutTraceFilter.Contains(bailOutKind)) \
  330. { \
  331. Output::Print(__VA_ARGS__); \
  332. if (bailOutKind != IR::BailOutInvalid) \
  333. { \
  334. Output::Print(_u(" Kind: %S"), ::GetBailOutKindName(bailOutKind)); \
  335. } \
  336. Output::Print(_u("\n")); \
  337. } \
  338. }
  339. #define BAILOUT_FLUSH(functionBody) \
  340. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::BailOutPhase, functionBody->GetSourceContextId(),functionBody->GetLocalFunctionId()) || \
  341. Js::Configuration::Global.flags.Trace.IsEnabled(Js::BailOutPhase, functionBody->GetSourceContextId(),functionBody->GetLocalFunctionId())) \
  342. { \
  343. Output::Flush(); \
  344. }
  345. #else
  346. #define BAILOUT_KIND_TRACE(functionBody, bailOutKind, ...)
  347. #define BAILOUT_TESTTRACE(functionBody, bailOutKind, ...)
  348. #define BAILOUT_VERBOSE_TRACE(functionBody, bailOutKind, ...)
  349. #define BAILOUT_FLUSH(functionBody)
  350. #endif
  351. #if DBG
  352. void BailOutRecord::DumpArgOffsets(uint count, int* offsets, int argOutSlotStart)
  353. {
  354. char16 const * name = _u("OutParam");
  355. Js::RegSlot regSlotOffset = 0;
  356. for (uint i = 0; i < count; i++)
  357. {
  358. int offset = offsets[i];
  359. // The variables below determine whether we have a Var or native float/int.
  360. bool isFloat64 = this->argOutOffsetInfo->argOutFloat64Syms->Test(argOutSlotStart + i) != 0;
  361. bool isInt32 = this->argOutOffsetInfo->argOutLosslessInt32Syms->Test(argOutSlotStart + i) != 0;
  362. Assert(!isFloat64 || !isInt32);
  363. Output::Print(_u("%s #%3d: "), name, i + regSlotOffset);
  364. this->DumpValue(offset, isFloat64);
  365. Output::Print(_u("\n"));
  366. }
  367. }
  368. void BailOutRecord::DumpLocalOffsets(uint count, int argOutSlotStart)
  369. {
  370. char16 const * name = _u("Register");
  371. globalBailOutRecordTable->IterateGlobalBailOutRecordTableRows(m_bailOutRecordId, [=](GlobalBailOutRecordDataRow *row) {
  372. Assert(row != nullptr);
  373. // The variables below determine whether we have a Var or native float/int.
  374. bool isFloat64 = row->isFloat;
  375. bool isInt32 = row->isInt;
  376. Assert(!isFloat64 || !isInt32);
  377. Output::Print(_u("%s #%3d: "), name, row->regSlot);
  378. this->DumpValue(row->offset, isFloat64);
  379. Output::Print(_u("\n"));
  380. });
  381. }
  382. void BailOutRecord::DumpValue(int offset, bool isFloat64)
  383. {
  384. if (offset < 0)
  385. {
  386. Output::Print(_u("Stack offset %6d"), offset);
  387. }
  388. else if (offset > 0)
  389. {
  390. if ((uint)offset <= GetBailOutRegisterSaveSlotCount())
  391. {
  392. if (isFloat64)
  393. {
  394. #ifdef _M_ARM
  395. Output::Print(_u("Register %-4S %4d"), RegNames[(offset - RegD0) / 2 + RegD0], offset);
  396. #else
  397. Output::Print(_u("Register %-4S %4d"), RegNames[offset], offset);
  398. #endif
  399. }
  400. else
  401. {
  402. Output::Print(_u("Register %-4S %4d"), RegNames[offset], offset);
  403. }
  404. }
  405. else if (BailOutRecord::IsArgumentsObject((uint)offset))
  406. {
  407. Output::Print(_u("Arguments object"));
  408. }
  409. else
  410. {
  411. // Constants offset starts from max bail out register save slot count
  412. uint constantIndex = offset - (GetBailOutRegisterSaveSlotCount() + GetBailOutReserveSlotCount()) - 1;
  413. Output::Print(_u("Constant index %4d value:0x%p (Var)"), constantIndex, this->constants[constantIndex]);
  414. Assert(!isFloat64);
  415. }
  416. }
  417. else
  418. {
  419. Output::Print(_u("Not live"));
  420. }
  421. }
  422. void BailOutRecord::Dump()
  423. {
  424. if (this->localOffsetsCount)
  425. {
  426. Output::Print(_u("**** Locals ***\n"));
  427. DumpLocalOffsets(this->localOffsetsCount, 0);
  428. }
  429. uint outParamSlot = 0;
  430. if(this->argOutOffsetInfo)
  431. {
  432. Output::Print(_u("**** Out params ***\n"));
  433. for (uint i = 0; i < this->argOutOffsetInfo->startCallCount; i++)
  434. {
  435. uint startCallOutParamCount = this->argOutOffsetInfo->startCallOutParamCounts[i];
  436. DumpArgOffsets(startCallOutParamCount, &this->argOutOffsetInfo->outParamOffsets[outParamSlot], this->argOutOffsetInfo->argOutSymStart + outParamSlot);
  437. outParamSlot += startCallOutParamCount;
  438. }
  439. }
  440. }
  441. #endif
  442. /*static*/
  443. bool BailOutRecord::IsArgumentsObject(uint32 offset)
  444. {
  445. bool isArgumentsObject = (GetArgumentsObjectOffset() == offset);
  446. return isArgumentsObject;
  447. }
  448. /*static*/
  449. uint32 BailOutRecord::GetArgumentsObjectOffset()
  450. {
  451. uint32 argumentsObjectOffset = (GetBailOutRegisterSaveSlotCount() + GetBailOutReserveSlotCount());
  452. return argumentsObjectOffset;
  453. }
  454. Js::FunctionEntryPointInfo *BailOutRecord::GetFunctionEntryPointInfo() const
  455. {
  456. Js::EntryPointInfo* result = this->globalBailOutRecordTable->entryPointInfo;
  457. AssertOrFailFast(result->IsFunctionEntryPointInfo());
  458. return (Js::FunctionEntryPointInfo*)result;
  459. }
  460. Js::Var BailOutRecord::EnsureArguments(Js::InterpreterStackFrame * newInstance, Js::JavascriptCallStackLayout * layout, Js::ScriptContext* scriptContext, Js::Var* pArgumentsObject) const
  461. {
  462. Assert(globalBailOutRecordTable->hasStackArgOpt);
  463. if (PHASE_OFF1(Js::StackArgFormalsOptPhase))
  464. {
  465. newInstance->OP_LdHeapArguments(scriptContext);
  466. }
  467. else
  468. {
  469. newInstance->CreateEmptyHeapArgumentsObject(scriptContext);
  470. }
  471. Assert(newInstance->m_arguments);
  472. *pArgumentsObject = (Js::ArgumentsObject*)newInstance->m_arguments;
  473. return newInstance->m_arguments;
  474. }
  475. Js::JavascriptCallStackLayout *BailOutRecord::GetStackLayout() const
  476. {
  477. return
  478. Js::JavascriptCallStackLayout::FromFramePointer(
  479. globalBailOutRecordTable->registerSaveSpace[LinearScanMD::GetRegisterSaveIndex(LowererMD::GetRegFramePointer()) - 1]);
  480. }
  481. void
  482. BailOutRecord::RestoreValues(IR::BailOutKind bailOutKind, Js::JavascriptCallStackLayout * layout, Js::InterpreterStackFrame * newInstance,
  483. Js::ScriptContext * scriptContext, bool fromLoopBody, Js::Var * registerSaves, BailOutReturnValue * bailOutReturnValue, Js::Var* pArgumentsObject,
  484. Js::Var branchValue, void * returnAddress, bool useStartCall /* = true */, void * argoutRestoreAddress) const
  485. {
  486. Js::AutoPushReturnAddressForStackWalker saveReturnAddress(scriptContext, returnAddress);
  487. if (this->stackLiteralBailOutRecordCount)
  488. {
  489. // Null out the field on the stack literal that hasn't fully initialized yet.
  490. globalBailOutRecordTable->IterateGlobalBailOutRecordTableRows(m_bailOutRecordId, [=](GlobalBailOutRecordDataRow *row)
  491. {
  492. for (uint i = 0; i < this->stackLiteralBailOutRecordCount; i++)
  493. {
  494. BailOutRecord::StackLiteralBailOutRecord& record = this->stackLiteralBailOutRecord[i];
  495. if (record.regSlot == row->regSlot)
  496. {
  497. // Partially initialized stack literal shouldn't be type specialized yet.
  498. Assert(!row->isFloat);
  499. Assert(!row->isInt);
  500. int offset = row->offset;
  501. Js::Var value;
  502. if (offset < 0)
  503. {
  504. // Stack offset
  505. value = layout->GetOffset(offset);
  506. }
  507. else
  508. {
  509. // The value is in register
  510. // Index is one based, so subtract one
  511. Assert((uint)offset <= GetBailOutRegisterSaveSlotCount());
  512. Js::Var * registerSaveSpace = registerSaves ? registerSaves : (Js::Var *)scriptContext->GetThreadContext()->GetBailOutRegisterSaveSpace();
  513. Assert(RegTypes[LinearScanMD::GetRegisterFromSaveIndex(offset)] != TyFloat64);
  514. value = registerSaveSpace[offset - 1];
  515. }
  516. Assert(Js::DynamicObject::Is(value));
  517. Assert(ThreadContext::IsOnStack(value));
  518. Js::DynamicObject * obj = Js::DynamicObject::FromVar(value);
  519. uint propertyCount = obj->GetPropertyCount();
  520. for (uint j = record.initFldCount; j < propertyCount; j++)
  521. {
  522. obj->SetSlot(SetSlotArgumentsRoot(Js::Constants::NoProperty, false, j, nullptr));
  523. }
  524. }
  525. }
  526. });
  527. }
  528. if (this->localOffsetsCount)
  529. {
  530. Js::FunctionBody* functionBody = newInstance->function->GetFunctionBody();
  531. #if ENABLE_DEBUG_CONFIG_OPTIONS
  532. BAILOUT_VERBOSE_TRACE(functionBody, bailOutKind, _u("BailOut: Register #%3d: Not live\n"), 0);
  533. for (uint i = 1; i < functionBody->GetConstantCount(); i++)
  534. {
  535. BAILOUT_VERBOSE_TRACE(functionBody, bailOutKind, _u("BailOut: Register #%3d: Constant table\n"), i);
  536. }
  537. #endif
  538. if (functionBody->IsInDebugMode())
  539. {
  540. this->AdjustOffsetsForDiagMode(layout, newInstance->GetJavascriptFunction());
  541. }
  542. this->RestoreValues(bailOutKind, layout, this->localOffsetsCount,
  543. nullptr, 0, newInstance->m_localSlots, scriptContext, fromLoopBody, registerSaves, newInstance, pArgumentsObject);
  544. }
  545. if (useStartCall && this->argOutOffsetInfo)
  546. {
  547. uint outParamSlot = 0;
  548. void * argRestoreAddr = nullptr;
  549. for (uint i = 0; i < this->argOutOffsetInfo->startCallCount; i++)
  550. {
  551. uint startCallOutParamCount = this->argOutOffsetInfo->startCallOutParamCounts[i];
  552. #ifdef _M_IX86
  553. if (argoutRestoreAddress)
  554. {
  555. argRestoreAddr = (void*)((char*)argoutRestoreAddress + (this->startCallArgRestoreAdjustCounts[i] * MachPtr));
  556. }
  557. #endif
  558. newInstance->OP_StartCall(startCallOutParamCount);
  559. this->RestoreValues(bailOutKind, layout, startCallOutParamCount, &this->argOutOffsetInfo->outParamOffsets[outParamSlot],
  560. this->argOutOffsetInfo->argOutSymStart + outParamSlot, newInstance->m_outParams,
  561. scriptContext, fromLoopBody, registerSaves, newInstance, pArgumentsObject, argRestoreAddr);
  562. outParamSlot += startCallOutParamCount;
  563. }
  564. }
  565. // If we're not in a loop body, then the arguments object is not on the local frame.
  566. // If the RestoreValues created an arguments object for us, then it's already on the interpreter instance.
  567. // Otherwise, we need to propagate the object from the jitted frame to the interpreter.
  568. Assert(newInstance->function && newInstance->function->GetFunctionBody());
  569. bool hasArgumentSlot = // Be consistent with Func::HasArgumentSlot.
  570. !fromLoopBody && newInstance->function->GetFunctionBody()->GetInParamsCount() != 0;
  571. if (hasArgumentSlot && newInstance->m_arguments == nullptr)
  572. {
  573. newInstance->m_arguments = *pArgumentsObject;
  574. }
  575. if (bailOutReturnValue != nullptr && bailOutReturnValue->returnValueRegSlot != Js::Constants::NoRegister)
  576. {
  577. Assert(bailOutReturnValue->returnValue != nullptr);
  578. Assert(bailOutReturnValue->returnValueRegSlot < newInstance->GetJavascriptFunction()->GetFunctionBody()->GetLocalsCount());
  579. newInstance->m_localSlots[bailOutReturnValue->returnValueRegSlot] = bailOutReturnValue->returnValue;
  580. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, _u("BailOut: Register #%3d: Return, value: 0x%p\n"),
  581. bailOutReturnValue->returnValueRegSlot, bailOutReturnValue->returnValue);
  582. }
  583. if (branchValueRegSlot != Js::Constants::NoRegister)
  584. {
  585. // Used when a t1 = CmCC is optimize to BrCC, and the branch bails out. T1 needs to be restored
  586. Assert(branchValue && Js::JavascriptBoolean::Is(branchValue));
  587. Assert(branchValueRegSlot < newInstance->GetJavascriptFunction()->GetFunctionBody()->GetLocalsCount());
  588. newInstance->m_localSlots[branchValueRegSlot] = branchValue;
  589. }
  590. #if DBG
  591. // Clear the register save area for the next bailout
  592. memset((void*)scriptContext->GetThreadContext()->GetBailOutRegisterSaveSpace(), 0, GetBailOutRegisterSaveSlotCount() * sizeof(Js::Var));
  593. #endif
  594. }
  595. void
  596. BailOutRecord::AdjustOffsetsForDiagMode(Js::JavascriptCallStackLayout * layout, Js::ScriptFunction * function) const
  597. {
  598. // In this function we are going to do
  599. // 1. Check if the value got changed (by checking at the particular location at the stack)
  600. // 2. In that case update the offset to point to the stack offset
  601. Js::FunctionBody *functionBody = function->GetFunctionBody();
  602. Assert(functionBody != nullptr);
  603. Assert(functionBody->IsInDebugMode());
  604. Js::FunctionEntryPointInfo *entryPointInfo = functionBody->GetDefaultFunctionEntryPointInfo();
  605. Assert(entryPointInfo != nullptr);
  606. // Note: the offset may be not initialized/InvalidOffset when there are no non-temp local vars.
  607. if (entryPointInfo->localVarChangedOffset != Js::Constants::InvalidOffset)
  608. {
  609. Assert(functionBody->GetNonTempLocalVarCount() != 0);
  610. char * valueChangeOffset = layout->GetValueChangeOffset(entryPointInfo->localVarChangedOffset);
  611. if (*valueChangeOffset == Js::FunctionBody::LocalsChangeDirtyValue)
  612. {
  613. // The value got changed due to debugger, lets read values from the stack position
  614. // Get the corresponding offset on the stack related to the frame.
  615. globalBailOutRecordTable->IterateGlobalBailOutRecordTableRows(m_bailOutRecordId, [=](GlobalBailOutRecordDataRow *row) {
  616. int32 offset = row->offset;
  617. // offset is zero, is it possible that a locals is not living in the debug mode?
  618. Assert(offset != 0);
  619. int32 slotOffset;
  620. if (functionBody->GetSlotOffset(row->regSlot, &slotOffset))
  621. {
  622. slotOffset = entryPointInfo->localVarSlotsOffset + slotOffset;
  623. // If it was taken from the stack location, we should have arrived to the same stack location.
  624. Assert(offset > 0 || offset == slotOffset);
  625. row->offset = slotOffset;
  626. }
  627. });
  628. }
  629. }
  630. }
  631. void
  632. BailOutRecord::IsOffsetNativeIntOrFloat(uint offsetIndex, int argOutSlotStart, bool * pIsFloat64, bool * pIsInt32) const
  633. {
  634. bool isFloat64 = this->argOutOffsetInfo->argOutFloat64Syms->Test(argOutSlotStart + offsetIndex) != 0;
  635. bool isInt32 = this->argOutOffsetInfo->argOutLosslessInt32Syms->Test(argOutSlotStart + offsetIndex) != 0;
  636. Assert(!isFloat64 || !isInt32);
  637. *pIsFloat64 = isFloat64;
  638. *pIsInt32 = isInt32;
  639. }
  640. void
  641. BailOutRecord::RestoreValue(IR::BailOutKind bailOutKind, Js::JavascriptCallStackLayout * layout, Js::Var * values, Js::ScriptContext * scriptContext,
  642. bool fromLoopBody, Js::Var * registerSaves, Js::InterpreterStackFrame * newInstance, Js::Var* pArgumentsObject, void * argoutRestoreAddress,
  643. uint regSlot, int offset, bool isLocal, bool isFloat64, bool isInt32) const
  644. {
  645. bool boxStackInstance = true;
  646. Js::Var value = 0;
  647. double dblValue = 0.0;
  648. int32 int32Value = 0;
  649. #if ENABLE_DEBUG_CONFIG_OPTIONS
  650. char16 const * name = _u("OutParam");
  651. if (isLocal)
  652. {
  653. name = _u("Register");
  654. }
  655. #endif
  656. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, _u("BailOut: %s #%3d: "), name, regSlot);
  657. if (offset < 0)
  658. {
  659. // Stack offset are negative
  660. if (!argoutRestoreAddress)
  661. {
  662. if (isFloat64)
  663. {
  664. dblValue = layout->GetDoubleAtOffset(offset);
  665. }
  666. else if (isInt32)
  667. {
  668. int32Value = layout->GetInt32AtOffset(offset);
  669. }
  670. else
  671. {
  672. value = layout->GetOffset(offset);
  673. AssertMsg(!(newInstance->function->GetFunctionBody()->IsInDebugMode() &&
  674. newInstance->function->GetFunctionBody()->IsNonTempLocalVar(regSlot) &&
  675. value == (Js::Var)Func::c_debugFillPattern),
  676. "Uninitialized value (debug mode only)? Try -trace:bailout -verbose and check last traced reg in byte code.");
  677. }
  678. }
  679. else if (!isLocal)
  680. {
  681. // If we have:
  682. // try {
  683. // bar(a, b, c);
  684. // } catch(..) {..}
  685. // and we bailout during bar args evaluation, we recover from args from argoutRestoreAddress, not from caller function frame.
  686. // This is because try-catch is implemented as a C wrapper, so args will be a different offset from rbp in that case.
  687. Assert(!isFloat64 && !isInt32);
  688. value = *((Js::Var *)(((char *)argoutRestoreAddress) + regSlot * MachPtr));
  689. AssertMsg(!(newInstance->function->GetFunctionBody()->IsInDebugMode() &&
  690. newInstance->function->GetFunctionBody()->IsNonTempLocalVar(regSlot) &&
  691. value == (Js::Var)Func::c_debugFillPattern),
  692. "Uninitialized value (debug mode only)? Try -trace:bailout -verbose and check last traced reg in byte code.");
  693. }
  694. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, _u("Stack offset %6d"), offset);
  695. }
  696. else if (offset > 0)
  697. {
  698. if ((uint)offset <= GetBailOutRegisterSaveSlotCount())
  699. {
  700. // Register save space (offset is the register number and index into the register save space)
  701. // Index is one based, so subtract one
  702. AssertOrFailFast(registerSaves);
  703. if (isFloat64)
  704. {
  705. Assert(RegTypes[LinearScanMD::GetRegisterFromSaveIndex(offset)] == TyFloat64);
  706. dblValue = *((double*)&(registerSaves[offset - 1]));
  707. #ifdef _M_ARM
  708. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, _u("Register %-4S %4d"), RegNames[(offset - RegD0) / 2 + RegD0], offset);
  709. #else
  710. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, _u("Register %-4S %4d"), RegNames[LinearScanMD::GetRegisterFromSaveIndex(offset)], offset);
  711. #endif
  712. }
  713. else
  714. {
  715. if (isInt32)
  716. {
  717. Assert(RegTypes[LinearScanMD::GetRegisterFromSaveIndex(offset)] != TyFloat64);
  718. int32Value = ::Math::PointerCastToIntegralTruncate<int32>(registerSaves[offset - 1]);
  719. }
  720. else
  721. {
  722. Assert(RegTypes[LinearScanMD::GetRegisterFromSaveIndex(offset)] != TyFloat64);
  723. value = registerSaves[offset - 1];
  724. }
  725. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, _u("Register %-4S %4d"), RegNames[LinearScanMD::GetRegisterFromSaveIndex(offset)], offset);
  726. }
  727. }
  728. else if (BailOutRecord::IsArgumentsObject((uint)offset))
  729. {
  730. Assert(!isFloat64);
  731. Assert(!isInt32);
  732. Assert(!fromLoopBody);
  733. value = *pArgumentsObject;
  734. if (value == nullptr)
  735. {
  736. value = EnsureArguments(newInstance, layout, scriptContext, pArgumentsObject);
  737. }
  738. Assert(value);
  739. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, _u("Arguments object"));
  740. boxStackInstance = false;
  741. }
  742. else
  743. {
  744. // Constants offset starts from max bail out register save slot count;
  745. uint constantIndex = offset - (GetBailOutRegisterSaveSlotCount() + GetBailOutReserveSlotCount()) - 1;
  746. if (isInt32)
  747. {
  748. int32Value = ::Math::PointerCastToIntegralTruncate<int32>(this->constants[constantIndex]);
  749. }
  750. else
  751. {
  752. value = this->constants[constantIndex];
  753. }
  754. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, _u("Constant index %4d"), constantIndex);
  755. boxStackInstance = false;
  756. }
  757. }
  758. else
  759. {
  760. // Consider Assert(false) here
  761. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, _u("Not live\n"));
  762. return;
  763. }
  764. if (isFloat64)
  765. {
  766. value = Js::JavascriptNumber::New(dblValue, scriptContext);
  767. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, _u(", value: %f (ToVar: 0x%p)"), dblValue, value);
  768. }
  769. else if (isInt32)
  770. {
  771. Assert(!value);
  772. value = Js::JavascriptNumber::ToVar(int32Value, scriptContext);
  773. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, _u(", value: %10d (ToVar: 0x%p)"), int32Value, value);
  774. }
  775. else
  776. {
  777. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, _u(", value: 0x%p"), value);
  778. if (boxStackInstance)
  779. {
  780. Js::Var oldValue = value;
  781. value = Js::JavascriptOperators::BoxStackInstance(oldValue, scriptContext, /* allowStackFunction */ true, /* deepCopy */ false);
  782. if (oldValue != value)
  783. {
  784. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, _u(" (Boxed: 0x%p)"), value);
  785. }
  786. }
  787. }
  788. values[regSlot] = value;
  789. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, _u("\n"));
  790. }
  791. void
  792. BailOutRecord::RestoreValues(IR::BailOutKind bailOutKind, Js::JavascriptCallStackLayout * layout, uint count, __in_ecount_opt(count) int * offsets, int argOutSlotStart,
  793. __out_ecount(count) Js::Var * values, Js::ScriptContext * scriptContext,
  794. bool fromLoopBody, Js::Var * registerSaves, Js::InterpreterStackFrame * newInstance, Js::Var* pArgumentsObject, void * argoutRestoreAddress) const
  795. {
  796. bool isLocal = offsets == nullptr;
  797. if (isLocal == true)
  798. {
  799. globalBailOutRecordTable->IterateGlobalBailOutRecordTableRows(m_bailOutRecordId, [=](GlobalBailOutRecordDataRow *row) {
  800. Assert(row->offset != 0);
  801. RestoreValue(bailOutKind, layout, values, scriptContext, fromLoopBody, registerSaves, newInstance, pArgumentsObject,
  802. argoutRestoreAddress, row->regSlot, row->offset, true, row->isFloat, row->isInt);
  803. });
  804. }
  805. else
  806. {
  807. for (uint i = 0; i < count; i++)
  808. {
  809. int offset = 0;
  810. // The variables below determine whether we have a Var or native float/int.
  811. bool isFloat64;
  812. bool isInt32;
  813. offset = offsets[i];
  814. this->IsOffsetNativeIntOrFloat(i, argOutSlotStart, &isFloat64, &isInt32);
  815. #ifdef _M_IX86
  816. if (this->argOutOffsetInfo->isOrphanedArgSlot->Test(argOutSlotStart + i))
  817. {
  818. RestoreValue(bailOutKind, layout, values, scriptContext, fromLoopBody, registerSaves, newInstance, pArgumentsObject,
  819. nullptr, i, offset, /* isLocal */ true, isFloat64, isInt32);
  820. continue;
  821. }
  822. #endif
  823. RestoreValue(bailOutKind, layout, values, scriptContext, fromLoopBody, registerSaves, newInstance, pArgumentsObject,
  824. argoutRestoreAddress, i, offset, false, isFloat64, isInt32);
  825. }
  826. }
  827. }
  828. Js::Var BailOutRecord::BailOut(BailOutRecord const * bailOutRecord)
  829. {
  830. Assert(bailOutRecord);
  831. void * argoutRestoreAddr = nullptr;
  832. #ifdef _M_IX86
  833. void * addressOfRetAddress = _AddressOfReturnAddress();
  834. if (bailOutRecord->ehBailoutData && (bailOutRecord->ehBailoutData->catchOffset != 0 || bailOutRecord->ehBailoutData->finallyOffset != 0 || bailOutRecord->ehBailoutData->ht == Js::HandlerType::HT_Finally))
  835. {
  836. // For a bailout in argument evaluation from an EH region, the esp is offset by the TryCatch helper's frame. So, the argouts are not at the offsets
  837. // stored in the bailout record, which are relative to ebp. Need to restore the argouts from the actual value of esp before calling the Bailout helper
  838. argoutRestoreAddr = (void *)((char*)addressOfRetAddress + ((1 + 1) * MachPtr)); // Account for the parameter and return address of this function
  839. }
  840. #endif
  841. Js::JavascriptCallStackLayout *const layout = bailOutRecord->GetStackLayout();
  842. Js::ScriptFunction * function = (Js::ScriptFunction *)layout->functionObject;
  843. Assert(function->GetScriptContext()->GetThreadContext()->GetPendingFinallyException() == nullptr ||
  844. bailOutRecord->bailOutKind == IR::BailOutOnException);
  845. if (bailOutRecord->bailOutKind == IR::BailOutOnImplicitCalls)
  846. {
  847. function->GetScriptContext()->GetThreadContext()->CheckAndResetImplicitCallAccessorFlag();
  848. }
  849. Js::ImplicitCallFlags savedImplicitCallFlags = function->GetScriptContext()->GetThreadContext()->GetImplicitCallFlags();
  850. if(bailOutRecord->globalBailOutRecordTable->isLoopBody)
  851. {
  852. if (bailOutRecord->globalBailOutRecordTable->isInlinedFunction)
  853. {
  854. return reinterpret_cast<Js::Var>(BailOutFromLoopBodyInlined(layout, bailOutRecord, _ReturnAddress()));
  855. }
  856. return reinterpret_cast<Js::Var>(BailOutFromLoopBody(layout, bailOutRecord));
  857. }
  858. if(bailOutRecord->globalBailOutRecordTable->isInlinedFunction)
  859. {
  860. return BailOutInlined(layout, bailOutRecord, _ReturnAddress(), savedImplicitCallFlags);
  861. }
  862. return BailOutFromFunction(layout, bailOutRecord, _ReturnAddress(), argoutRestoreAddr, savedImplicitCallFlags);
  863. }
  864. uint32
  865. BailOutRecord::BailOutFromLoopBody(Js::JavascriptCallStackLayout * layout, BailOutRecord const * bailOutRecord)
  866. {
  867. Assert(bailOutRecord->parent == nullptr);
  868. return BailOutFromLoopBodyCommon(layout, bailOutRecord, bailOutRecord->bailOutOffset, bailOutRecord->bailOutKind);
  869. }
  870. Js::Var
  871. BailOutRecord::BailOutFromFunction(Js::JavascriptCallStackLayout * layout, BailOutRecord const * bailOutRecord, void * returnAddress, void * argoutRestoreAddress, Js::ImplicitCallFlags savedImplicitCallFlags)
  872. {
  873. Assert(bailOutRecord->parent == nullptr);
  874. return BailOutCommon(layout, bailOutRecord, bailOutRecord->bailOutOffset, returnAddress, bailOutRecord->bailOutKind, savedImplicitCallFlags, nullptr, nullptr, argoutRestoreAddress);
  875. }
  876. Js::Var
  877. BailOutRecord::BailOutInlined(Js::JavascriptCallStackLayout * layout, BailOutRecord const * bailOutRecord, void * returnAddress, Js::ImplicitCallFlags savedImplicitCallFlags)
  878. {
  879. Assert(bailOutRecord->parent != nullptr);
  880. return BailOutInlinedCommon(layout, bailOutRecord, bailOutRecord->bailOutOffset, returnAddress, bailOutRecord->bailOutKind, savedImplicitCallFlags);
  881. }
  882. uint32
  883. BailOutRecord::BailOutFromLoopBodyInlined(Js::JavascriptCallStackLayout * layout, BailOutRecord const * bailOutRecord, void * returnAddress)
  884. {
  885. Assert(bailOutRecord->parent != nullptr);
  886. return BailOutFromLoopBodyInlinedCommon(layout, bailOutRecord, bailOutRecord->bailOutOffset, returnAddress, bailOutRecord->bailOutKind);
  887. }
  888. Js::Var
  889. BailOutRecord::BailOutCommonNoCodeGen(Js::JavascriptCallStackLayout * layout, BailOutRecord const * bailOutRecord,
  890. uint32 bailOutOffset, void * returnAddress, IR::BailOutKind bailOutKind, Js::Var branchValue, Js::Var * registerSaves,
  891. BailOutReturnValue * bailOutReturnValue, void * argoutRestoreAddress)
  892. {
  893. Assert(bailOutRecord->parent == nullptr);
  894. Assert(Js::ScriptFunction::Is(layout->functionObject));
  895. Js::ScriptFunction ** functionRef = (Js::ScriptFunction **)&layout->functionObject;
  896. Js::ArgumentReader args(&layout->callInfo, layout->args);
  897. Js::Var result = BailOutHelper(layout, functionRef, args, false, bailOutRecord, bailOutOffset, returnAddress, bailOutKind, registerSaves, bailOutReturnValue, layout->GetArgumentsObjectLocation(), branchValue, argoutRestoreAddress);
  898. return result;
  899. }
  900. Js::Var
  901. BailOutRecord::BailOutCommon(Js::JavascriptCallStackLayout * layout, BailOutRecord const * bailOutRecord,
  902. uint32 bailOutOffset, void * returnAddress, IR::BailOutKind bailOutKind, Js::ImplicitCallFlags savedImplicitCallFlags, Js::Var branchValue, BailOutReturnValue * bailOutReturnValue, void * argoutRestoreAddress)
  903. {
  904. // Do not remove the following code.
  905. // Need to capture the int registers on stack as threadContext->bailOutRegisterSaveSpace is allocated from ThreadAlloc and is not scanned by recycler.
  906. // We don't want to save float (xmm) registers as they can be huge and they cannot contain a var.
  907. // However, we're somewhat stuck. We need to keep the references around until we restore values, but
  908. // we don't have a use for them. The easiest solution is to simply pass this into the corresponding
  909. // parameter for BailOutcommonNoCodeGen, but that requires us to save all of the vars, not just the
  910. // int ones. This is ultimately significantly more predictable than attempting to manage the lifetimes
  911. // in some other way though. We can't just do what we were doing previously, which is saving values
  912. // here and not passing them into BailOutCommonNoCodeGen, because then the compiler will likely get
  913. // rid of the memcpy and then the dead registerSaves array, since it can figure out that there's no
  914. // side effect (due to the GC not being something that the optimizer can, or should, reason about).
  915. Js::Var registerSaves[BailOutRegisterSaveSlotCount];
  916. js_memcpy_s(registerSaves, sizeof(registerSaves), (Js::Var *)layout->functionObject->GetScriptContext()->GetThreadContext()->GetBailOutRegisterSaveSpace(),
  917. sizeof(registerSaves));
  918. Js::Var result = BailOutCommonNoCodeGen(layout, bailOutRecord, bailOutOffset, returnAddress, bailOutKind, branchValue, registerSaves, bailOutReturnValue, argoutRestoreAddress);
  919. ScheduleFunctionCodeGen(Js::ScriptFunction::FromVar(layout->functionObject), nullptr, bailOutRecord, bailOutKind, bailOutOffset, savedImplicitCallFlags, returnAddress);
  920. return result;
  921. }
  922. Js::Var
  923. BailOutRecord::BailOutInlinedCommon(Js::JavascriptCallStackLayout * layout, BailOutRecord const * bailOutRecord, uint32 bailOutOffset,
  924. void * returnAddress, IR::BailOutKind bailOutKind, Js::ImplicitCallFlags savedImplicitCallFlags, Js::Var branchValue)
  925. {
  926. Assert(bailOutRecord->parent != nullptr);
  927. // Need to capture the register save, one of the bailout might get into jitted code again and bailout again
  928. // overwriting the current register saves
  929. Js::Var registerSaves[BailOutRegisterSaveSlotCount];
  930. js_memcpy_s(registerSaves, sizeof(registerSaves), (Js::Var *)layout->functionObject->GetScriptContext()->GetThreadContext()->GetBailOutRegisterSaveSpace(),
  931. sizeof(registerSaves));
  932. BailOutRecord const * currentBailOutRecord = bailOutRecord;
  933. BailOutReturnValue bailOutReturnValue;
  934. Js::ScriptFunction * innerMostInlinee = nullptr;
  935. BailOutInlinedHelper(layout, currentBailOutRecord, bailOutOffset, returnAddress, bailOutKind, registerSaves, &bailOutReturnValue, &innerMostInlinee, false, branchValue);
  936. bool * hasBailedOutBitPtr = layout->functionObject->GetScriptContext()->GetThreadContext()->GetHasBailedOutBitPtr();
  937. Assert(!bailOutRecord->ehBailoutData || hasBailedOutBitPtr ||
  938. bailOutRecord->ehBailoutData->ht == Js::HandlerType::HT_Finally /* When we bailout from inlinee in non exception finally, we maynot see hasBailedOutBitPtr*/);
  939. if (hasBailedOutBitPtr && bailOutRecord->ehBailoutData)
  940. {
  941. *hasBailedOutBitPtr = true;
  942. }
  943. Js::Var result = BailOutCommonNoCodeGen(layout, currentBailOutRecord, currentBailOutRecord->bailOutOffset, returnAddress, bailOutKind, branchValue,
  944. registerSaves, &bailOutReturnValue);
  945. ScheduleFunctionCodeGen(Js::ScriptFunction::FromVar(layout->functionObject), innerMostInlinee, currentBailOutRecord, bailOutKind, bailOutOffset, savedImplicitCallFlags, returnAddress);
  946. return result;
  947. }
  948. uint32
  949. BailOutRecord::BailOutFromLoopBodyCommon(Js::JavascriptCallStackLayout * layout, BailOutRecord const * bailOutRecord, uint32 bailOutOffset,
  950. IR::BailOutKind bailOutKind, Js::Var branchValue)
  951. {
  952. // This isn't strictly necessary if there's no allocations on this path, but because such an
  953. // issue would be hard to notice and introduce some significant issues, we can do this copy.
  954. // The problem from not doing this and then doing an allocation before RestoreValues is that
  955. // the GC doesn't check the BailOutRegisterSaveSpace.
  956. Js::Var registerSaves[BailOutRegisterSaveSlotCount];
  957. js_memcpy_s(registerSaves, sizeof(registerSaves), (Js::Var *)layout->functionObject->GetScriptContext()->GetThreadContext()->GetBailOutRegisterSaveSpace(),
  958. sizeof(registerSaves));
  959. uint32 result = BailOutFromLoopBodyHelper(layout, bailOutRecord, bailOutOffset, bailOutKind, branchValue, registerSaves);
  960. ScheduleLoopBodyCodeGen(Js::ScriptFunction::FromVar(layout->functionObject), nullptr, bailOutRecord, bailOutKind);
  961. return result;
  962. }
  963. uint32
  964. BailOutRecord::BailOutFromLoopBodyInlinedCommon(Js::JavascriptCallStackLayout * layout, BailOutRecord const * bailOutRecord,
  965. uint32 bailOutOffset, void * returnAddress, IR::BailOutKind bailOutKind, Js::Var branchValue)
  966. {
  967. Assert(bailOutRecord->parent != nullptr);
  968. // This isn't strictly necessary if there's no allocations on this path, but because such an
  969. // issue would be hard to notice and introduce some significant issues, we can do this copy.
  970. // The problem from not doing this and then doing an allocation before RestoreValues is that
  971. // the GC doesn't check the BailOutRegisterSaveSpace.
  972. Js::Var registerSaves[BailOutRegisterSaveSlotCount];
  973. js_memcpy_s(registerSaves, sizeof(registerSaves), (Js::Var *)layout->functionObject->GetScriptContext()->GetThreadContext()->GetBailOutRegisterSaveSpace(),
  974. sizeof(registerSaves));
  975. BailOutRecord const * currentBailOutRecord = bailOutRecord;
  976. BailOutReturnValue bailOutReturnValue;
  977. Js::ScriptFunction * innerMostInlinee = nullptr;
  978. BailOutInlinedHelper(layout, currentBailOutRecord, bailOutOffset, returnAddress, bailOutKind, registerSaves, &bailOutReturnValue, &innerMostInlinee, true, branchValue);
  979. bool * hasBailedOutBitPtr = layout->functionObject->GetScriptContext()->GetThreadContext()->GetHasBailedOutBitPtr();
  980. Assert(!bailOutRecord->ehBailoutData || hasBailedOutBitPtr ||
  981. bailOutRecord->ehBailoutData->ht == Js::HandlerType::HT_Finally /* When we bailout from inlinee in non exception finally, we maynot see hasBailedOutBitPtr*/);
  982. if (hasBailedOutBitPtr && bailOutRecord->ehBailoutData)
  983. {
  984. *hasBailedOutBitPtr = true;
  985. }
  986. uint32 result = BailOutFromLoopBodyHelper(layout, currentBailOutRecord, currentBailOutRecord->bailOutOffset,
  987. bailOutKind, nullptr, registerSaves, &bailOutReturnValue);
  988. ScheduleLoopBodyCodeGen(Js::ScriptFunction::FromVar(layout->functionObject), innerMostInlinee, currentBailOutRecord, bailOutKind);
  989. return result;
  990. }
  991. void
  992. BailOutRecord::BailOutInlinedHelper(Js::JavascriptCallStackLayout * layout, BailOutRecord const *& currentBailOutRecord,
  993. uint32 bailOutOffset, void * returnAddress, IR::BailOutKind bailOutKind, Js::Var * registerSaves, BailOutReturnValue * bailOutReturnValue, Js::ScriptFunction ** innerMostInlinee, bool isInLoopBody, Js::Var branchValue)
  994. {
  995. Assert(currentBailOutRecord->parent != nullptr);
  996. BailOutReturnValue * lastBailOutReturnValue = nullptr;
  997. *innerMostInlinee = nullptr;
  998. Js::FunctionBody* functionBody = Js::ScriptFunction::FromVar(layout->functionObject)->GetFunctionBody();
  999. Js::EntryPointInfo *entryPointInfo;
  1000. if(isInLoopBody)
  1001. {
  1002. Js::InterpreterStackFrame * interpreterFrame = functionBody->GetScriptContext()->GetThreadContext()->GetLeafInterpreterFrame();
  1003. uint loopNum = interpreterFrame->GetCurrentLoopNum();
  1004. entryPointInfo = (Js::EntryPointInfo*)functionBody->GetLoopEntryPointInfoFromNativeAddress((DWORD_PTR)returnAddress, loopNum);
  1005. }
  1006. else
  1007. {
  1008. entryPointInfo = (Js::EntryPointInfo*)functionBody->GetEntryPointFromNativeAddress((DWORD_PTR)returnAddress);
  1009. }
  1010. // Let's restore the inline stack - so that in case of a stack walk we have it available
  1011. if (entryPointInfo->HasInlinees())
  1012. {
  1013. InlineeFrameRecord* inlineeFrameRecord = entryPointInfo->FindInlineeFrame(returnAddress);
  1014. if (inlineeFrameRecord)
  1015. {
  1016. // While bailing out, RestoreFrames should box all Vars on the stack. If there are multiple Vars pointing to the same
  1017. // object, the cached version (that was previously boxed) will be reused to maintain pointer identity and correctness
  1018. // after the transition to the interpreter.
  1019. InlinedFrameLayout* outerMostFrame = (InlinedFrameLayout *)(((uint8 *)Js::JavascriptCallStackLayout::ToFramePointer(layout)) - entryPointInfo->GetFrameHeight());
  1020. inlineeFrameRecord->RestoreFrames(functionBody, outerMostFrame, layout, true /* boxArgs */);
  1021. }
  1022. }
  1023. do
  1024. {
  1025. InlinedFrameLayout *inlinedFrame = (InlinedFrameLayout *)(((char *)layout) + currentBailOutRecord->globalBailOutRecordTable->firstActualStackOffset);
  1026. Js::InlineeCallInfo inlineeCallInfo = inlinedFrame->callInfo;
  1027. Assert((Js::ArgSlot)inlineeCallInfo.Count == currentBailOutRecord->actualCount);
  1028. Js::CallFlags callFlags = Js::CallFlags_Value;
  1029. if (currentBailOutRecord->globalBailOutRecordTable->isInlinedConstructor)
  1030. {
  1031. callFlags |= Js::CallFlags_New;
  1032. }
  1033. Js::CallInfo callInfo(callFlags, (Js::ArgSlot)inlineeCallInfo.Count);
  1034. Js::ScriptFunction ** functionRef = (Js::ScriptFunction **)&(inlinedFrame->function);
  1035. AnalysisAssert(*functionRef);
  1036. Assert(Js::ScriptFunction::Is(inlinedFrame->function));
  1037. if (*innerMostInlinee == nullptr)
  1038. {
  1039. *innerMostInlinee = *functionRef;
  1040. }
  1041. Js::ArgumentReader args(&callInfo, inlinedFrame->GetArguments());
  1042. Js::Var* pArgumentsObject = &inlinedFrame->arguments;
  1043. (*functionRef)->GetFunctionBody()->EnsureDynamicProfileInfo();
  1044. bailOutReturnValue->returnValue = BailOutHelper(layout, functionRef, args, true, currentBailOutRecord, bailOutOffset,
  1045. returnAddress, bailOutKind, registerSaves, lastBailOutReturnValue, pArgumentsObject, branchValue);
  1046. // Clear the inlinee frame CallInfo, just like we'd have done in JITted code.
  1047. inlinedFrame->callInfo.Clear();
  1048. bailOutReturnValue->returnValueRegSlot = currentBailOutRecord->globalBailOutRecordTable->returnValueRegSlot;
  1049. lastBailOutReturnValue = bailOutReturnValue;
  1050. currentBailOutRecord = currentBailOutRecord->parent;
  1051. bailOutOffset = currentBailOutRecord->bailOutOffset;
  1052. }
  1053. while (currentBailOutRecord->parent != nullptr);
  1054. }
  1055. uint32
  1056. BailOutRecord::BailOutFromLoopBodyHelper(Js::JavascriptCallStackLayout * layout, BailOutRecord const * bailOutRecord,
  1057. uint32 bailOutOffset, IR::BailOutKind bailOutKind, Js::Var branchValue, Js::Var *registerSaves, BailOutReturnValue * bailOutReturnValue)
  1058. {
  1059. Assert(bailOutRecord->parent == nullptr);
  1060. Js::JavascriptFunction * function = layout->functionObject;
  1061. Js::FunctionBody * executeFunction = function->GetFunctionBody();
  1062. executeFunction->SetRecentlyBailedOutOfJittedLoopBody(true);
  1063. Js::ScriptContext * functionScriptContext = executeFunction->GetScriptContext();
  1064. // Clear the disable implicit call bit in case we bail from that region
  1065. functionScriptContext->GetThreadContext()->ClearDisableImplicitFlags();
  1066. // The current interpreter frame for the loop body
  1067. Js::InterpreterStackFrame * interpreterFrame = functionScriptContext->GetThreadContext()->GetLeafInterpreterFrame();
  1068. #if defined(DBG_DUMP) || defined(ENABLE_DEBUG_CONFIG_OPTIONS)
  1069. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  1070. #endif
  1071. BAILOUT_KIND_TRACE(executeFunction, bailOutKind, _u("BailOut: function: %s (%s) Loop: %d offset: #%04x Opcode: %s"),
  1072. executeFunction->GetDisplayName(), executeFunction->GetDebugNumberSet(debugStringBuffer), interpreterFrame->GetCurrentLoopNum(),
  1073. bailOutOffset, Js::OpCodeUtil::GetOpCodeName(bailOutRecord->bailOutOpcode));
  1074. BAILOUT_TESTTRACE(executeFunction, bailOutKind, _u("BailOut: function %s, Loop: %d Opcode: %s"), executeFunction->GetDisplayName(),
  1075. interpreterFrame->GetCurrentLoopNum(), Js::OpCodeUtil::GetOpCodeName(bailOutRecord->bailOutOpcode));
  1076. // Restore bailout values
  1077. bailOutRecord->RestoreValues(bailOutKind, layout, interpreterFrame, functionScriptContext, true, registerSaves, bailOutReturnValue, layout->GetArgumentsObjectLocation(), branchValue);
  1078. BAILOUT_FLUSH(executeFunction);
  1079. UpdatePolymorphicFieldAccess(function, bailOutRecord);
  1080. // Return the resume byte code offset from the loop body to restart interpreter execution.
  1081. return bailOutOffset;
  1082. }
  1083. void BailOutRecord::UpdatePolymorphicFieldAccess(Js::JavascriptFunction * function, BailOutRecord const * bailOutRecord)
  1084. {
  1085. Js::FunctionBody * executeFunction = bailOutRecord->IsShared() ? ((SharedBailOutRecord*)bailOutRecord)->functionBody : function->GetFunctionBody();
  1086. Js::DynamicProfileInfo *dynamicProfileInfo = nullptr;
  1087. if (executeFunction->HasDynamicProfileInfo())
  1088. {
  1089. dynamicProfileInfo = executeFunction->GetAnyDynamicProfileInfo();
  1090. Assert(dynamicProfileInfo);
  1091. if (bailOutRecord->polymorphicCacheIndex != (uint)-1)
  1092. {
  1093. dynamicProfileInfo->RecordPolymorphicFieldAccess(executeFunction, bailOutRecord->polymorphicCacheIndex);
  1094. if (IR::IsEquivalentTypeCheckBailOutKind(bailOutRecord->bailOutKind))
  1095. {
  1096. // If we've already got a polymorphic inline cache, and if we've got an equivalent type check
  1097. // bailout here, make sure we don't try any more equivalent obj type spec using that cache.
  1098. Js::PolymorphicInlineCache *polymorphicInlineCache = executeFunction->GetPolymorphicInlineCache(
  1099. bailOutRecord->polymorphicCacheIndex);
  1100. if (polymorphicInlineCache)
  1101. {
  1102. polymorphicInlineCache->SetIgnoreForEquivalentObjTypeSpec(true);
  1103. }
  1104. }
  1105. }
  1106. }
  1107. }
  1108. Js::Var
  1109. BailOutRecord::BailOutHelper(Js::JavascriptCallStackLayout * layout, Js::ScriptFunction ** functionRef, Js::Arguments& args, const bool isInlinee,
  1110. BailOutRecord const * bailOutRecord, uint32 bailOutOffset, void * returnAddress, IR::BailOutKind bailOutKind, Js::Var * registerSaves, BailOutReturnValue * bailOutReturnValue, Js::Var* pArgumentsObject,
  1111. Js::Var branchValue, void * argoutRestoreAddress)
  1112. {
  1113. Js::ScriptFunction * function = *functionRef;
  1114. Js::FunctionBody * executeFunction = function->GetFunctionBody();
  1115. Js::ScriptContext * functionScriptContext = executeFunction->GetScriptContext();
  1116. // Whether to enter StartCall while doing RestoreValues. We don't do that when bailout due to ignore exception under debugger.
  1117. bool useStartCall = true;
  1118. // Clear the disable implicit call bit in case we bail from that region
  1119. functionScriptContext->GetThreadContext()->ClearDisableImplicitFlags();
  1120. #ifdef ENABLE_SCRIPT_DEBUGGING
  1121. bool isInDebugMode = executeFunction->IsInDebugMode();
  1122. AssertMsg(!isInDebugMode || Js::Configuration::Global.EnableJitInDebugMode(),
  1123. "In diag mode we can get here (function has to be JIT'ed) only when EnableJitInDiagMode is true!");
  1124. // Adjust bailout offset for debug mode (only scenario when we ignore exception).
  1125. if (isInDebugMode)
  1126. {
  1127. Js::DebugManager* debugManager = functionScriptContext->GetThreadContext()->GetDebugManager();
  1128. DebuggingFlags* debuggingFlags = debugManager->GetDebuggingFlags();
  1129. int byteCodeOffsetAfterEx = debuggingFlags->GetByteCodeOffsetAfterIgnoreException();
  1130. // Note that in case where bailout for ignore exception immediately follows regular bailout after a helper,
  1131. // and ignore exception happens, we would bail out with non-exception kind with exception data recorded.
  1132. // In this case we need to treat the bailout as ignore exception one and continue to next/set stmt.
  1133. // This is fine because we only set byteCodeOffsetAfterEx for helpers (HelperMethodWrapper, when enabled)
  1134. // and ignore exception is needed for all helpers.
  1135. if ((bailOutKind & IR::BailOutIgnoreException) || byteCodeOffsetAfterEx != DebuggingFlags::InvalidByteCodeOffset)
  1136. {
  1137. bool needResetData = true;
  1138. // Note: the func # in debuggingFlags still can be 0 in case actual b/o reason was not BailOutIgnoreException,
  1139. // but BailOutIgnoreException was on the OR'ed values for b/o check.
  1140. bool isSameFunction = debuggingFlags->GetFuncNumberAfterIgnoreException() == DebuggingFlags::InvalidFuncNumber ||
  1141. debuggingFlags->GetFuncNumberAfterIgnoreException() == function->GetFunctionBody()->GetFunctionNumber();
  1142. AssertMsg(isSameFunction, "Bailout due to ignore exception in different function, can't bail out cross functions!");
  1143. if (isSameFunction)
  1144. {
  1145. Assert(!(byteCodeOffsetAfterEx == DebuggingFlags::InvalidByteCodeOffset && debuggingFlags->GetFuncNumberAfterIgnoreException() != DebuggingFlags::InvalidFuncNumber));
  1146. if (byteCodeOffsetAfterEx != DebuggingFlags::InvalidByteCodeOffset)
  1147. {
  1148. // We got an exception in native frame, and need to bail out to interpreter
  1149. if (debugManager->stepController.IsActive())
  1150. {
  1151. // Native frame went away, and there will be interpreter frame on its place.
  1152. // Make sure that frameAddrWhenSet it less than current interpreter frame -- we use it to detect stack depth.
  1153. debugManager->stepController.SetFrameAddr(0);
  1154. }
  1155. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  1156. if (bailOutOffset != (uint)byteCodeOffsetAfterEx || !(bailOutKind & IR::BailOutIgnoreException))
  1157. {
  1158. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  1159. BAILOUT_KIND_TRACE(executeFunction, bailOutKind, _u("BailOut: changing due to ignore exception: function: %s (%s) offset: #%04x -> #%04x Opcode: %s Treating as: %S"), executeFunction->GetDisplayName(),
  1160. executeFunction->GetDebugNumberSet(debugStringBuffer), bailOutOffset, byteCodeOffsetAfterEx, Js::OpCodeUtil::GetOpCodeName(bailOutRecord->bailOutOpcode), ::GetBailOutKindName(IR::BailOutIgnoreException));
  1161. BAILOUT_TESTTRACE(executeFunction, bailOutKind, _u("BailOut: changing due to ignore exception: function %s, Opcode: %s, Treating as: %S"), executeFunction->GetDisplayName(),
  1162. Js::OpCodeUtil::GetOpCodeName(bailOutRecord->bailOutOpcode), ::GetBailOutKindName(IR::BailOutIgnoreException));
  1163. }
  1164. #endif
  1165. // Set the byte code offset to continue from next user statement.
  1166. bailOutOffset = byteCodeOffsetAfterEx;
  1167. // Reset current call count so that we don't do StartCall for inner calls. See WinBlue 272569.
  1168. // The idea is that next statement can never be set to the inner StartCall (another call as part of an ArgOut),
  1169. // it will be next statement in the function.
  1170. useStartCall = false;
  1171. }
  1172. else
  1173. {
  1174. needResetData = false;
  1175. }
  1176. }
  1177. if (needResetData)
  1178. {
  1179. // Reset/correct the flag as either we processed it or we need to correct wrong flag.
  1180. debuggingFlags->ResetByteCodeOffsetAndFuncAfterIgnoreException();
  1181. }
  1182. }
  1183. }
  1184. #endif
  1185. #if defined(DBG_DUMP) || defined(ENABLE_DEBUG_CONFIG_OPTIONS)
  1186. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  1187. #endif
  1188. BAILOUT_KIND_TRACE(executeFunction, bailOutKind, _u("BailOut: function: %s (%s) offset: #%04x Opcode: %s"), executeFunction->GetDisplayName(),
  1189. executeFunction->GetDebugNumberSet(debugStringBuffer), bailOutOffset, Js::OpCodeUtil::GetOpCodeName(bailOutRecord->bailOutOpcode));
  1190. BAILOUT_TESTTRACE(executeFunction, bailOutKind, _u("BailOut: function %s, Opcode: %s"), executeFunction->GetDisplayName(), Js::OpCodeUtil::GetOpCodeName(bailOutRecord->bailOutOpcode));
  1191. if (isInlinee && args.Info.Count != 0)
  1192. {
  1193. // Box arguments. Inlinee arguments may be allocated on the stack.
  1194. for(uint i = 0; i < args.Info.Count; ++i)
  1195. {
  1196. const Js::Var arg = args.Values[i];
  1197. BAILOUT_VERBOSE_TRACE(executeFunction, bailOutKind, _u("BailOut: Argument #%3u: value: 0x%p"), i, arg);
  1198. const Js::Var boxedArg = Js::JavascriptOperators::BoxStackInstance(arg, functionScriptContext, /* allowStackFunction */ true, /* deepCopy */ false);
  1199. if(boxedArg != arg)
  1200. {
  1201. args.Values[i] = boxedArg;
  1202. BAILOUT_VERBOSE_TRACE(executeFunction, bailOutKind, _u(" (Boxed: 0x%p)"), boxedArg);
  1203. }
  1204. BAILOUT_VERBOSE_TRACE(executeFunction, bailOutKind, _u("\n"));
  1205. }
  1206. }
  1207. bool fReleaseAlloc = false;
  1208. Js::InterpreterStackFrame* newInstance = nullptr;
  1209. Js::Var* allocation = nullptr;
  1210. if (executeFunction->IsCoroutine())
  1211. {
  1212. // If the FunctionBody is a generator then this call is being made by one of the three
  1213. // generator resuming methods: next(), throw(), or return(). They all pass the generator
  1214. // object as the first of two arguments. The real user arguments are obtained from the
  1215. // generator object. The second argument is the ResumeYieldData which is only needed
  1216. // when resuming a generator and not needed when yielding from a generator, as is occurring
  1217. // here.
  1218. AssertMsg(args.Info.Count == 2, "Generator ScriptFunctions should only be invoked by generator APIs with the pair of arguments they pass in -- the generator object and a ResumeYieldData pointer");
  1219. Js::JavascriptGenerator* generator = Js::JavascriptGenerator::FromVar(args[0]);
  1220. newInstance = generator->GetFrame();
  1221. if (newInstance != nullptr)
  1222. {
  1223. // BailOut will recompute OutArg pointers based on BailOutRecord. Reset them back
  1224. // to initial position before that happens so that OP_StartCall calls don't accumulate
  1225. // incorrectly over multiple yield bailouts.
  1226. newInstance->ResetOut();
  1227. // The debugger relies on comparing stack addresses of frames to decide when a step_out is complete so
  1228. // give the InterpreterStackFrame a legit enough stack address to make this comparison work.
  1229. newInstance->m_stackAddress = reinterpret_cast<DWORD_PTR>(&generator);
  1230. }
  1231. else
  1232. {
  1233. //
  1234. // Allocate a new InterpreterStackFrame instance on the recycler heap.
  1235. // It will live with the JavascriptGenerator object.
  1236. //
  1237. Js::Arguments generatorArgs = generator->GetArguments();
  1238. Js::InterpreterStackFrame::Setup setup(function, generatorArgs, true, isInlinee);
  1239. Assert(setup.GetStackAllocationVarCount() == 0);
  1240. size_t varAllocCount = setup.GetAllocationVarCount();
  1241. size_t varSizeInBytes = varAllocCount * sizeof(Js::Var);
  1242. DWORD_PTR stackAddr = reinterpret_cast<DWORD_PTR>(&generator); // as mentioned above, use any stack address from this frame to ensure correct debugging functionality
  1243. Js::LoopHeader* loopHeaderArray = executeFunction->GetHasAllocatedLoopHeaders() ? executeFunction->GetLoopHeaderArrayPtr() : nullptr;
  1244. allocation = RecyclerNewPlus(functionScriptContext->GetRecycler(), varSizeInBytes, Js::Var);
  1245. // Initialize the interpreter stack frame (constants) but not the param, the bailout record will restore the value
  1246. #if DBG
  1247. // Allocate invalidVar on GC instead of stack since this InterpreterStackFrame will out live the current real frame
  1248. Js::Var invalidVar = (Js::RecyclableObject*)RecyclerNewPlusLeaf(functionScriptContext->GetRecycler(), sizeof(Js::RecyclableObject), Js::Var);
  1249. memset(invalidVar, 0xFE, sizeof(Js::RecyclableObject));
  1250. #endif
  1251. newInstance = setup.InitializeAllocation(allocation, nullptr, false, false, loopHeaderArray, stackAddr
  1252. #if DBG
  1253. , invalidVar
  1254. #endif
  1255. );
  1256. newInstance->m_reader.Create(executeFunction);
  1257. generator->SetFrame(newInstance, varSizeInBytes);
  1258. }
  1259. }
  1260. else
  1261. {
  1262. Js::InterpreterStackFrame::Setup setup(function, args, true, isInlinee);
  1263. size_t varAllocCount = setup.GetAllocationVarCount();
  1264. size_t stackVarAllocCount = setup.GetStackAllocationVarCount();
  1265. size_t varSizeInBytes;
  1266. Js::Var *stackAllocation = nullptr;
  1267. // If the locals area exceeds a certain limit, allocate it from a private arena rather than
  1268. // this frame. The current limit is based on an old assert on the number of locals we would allow here.
  1269. if ((varAllocCount + stackVarAllocCount) > Js::InterpreterStackFrame::LocalsThreshold)
  1270. {
  1271. ArenaAllocator *tmpAlloc = nullptr;
  1272. fReleaseAlloc = functionScriptContext->EnsureInterpreterArena(&tmpAlloc);
  1273. varSizeInBytes = varAllocCount * sizeof(Js::Var);
  1274. allocation = (Js::Var*)tmpAlloc->Alloc(varSizeInBytes);
  1275. if (stackVarAllocCount != 0)
  1276. {
  1277. size_t stackVarSizeInBytes = stackVarAllocCount * sizeof(Js::Var);
  1278. PROBE_STACK_PARTIAL_INITIALIZED_BAILOUT_FRAME(functionScriptContext, Js::Constants::MinStackInterpreter + stackVarSizeInBytes, returnAddress);
  1279. stackAllocation = (Js::Var*)_alloca(stackVarSizeInBytes);
  1280. }
  1281. }
  1282. else
  1283. {
  1284. varSizeInBytes = (varAllocCount + stackVarAllocCount) * sizeof(Js::Var);
  1285. PROBE_STACK_PARTIAL_INITIALIZED_BAILOUT_FRAME(functionScriptContext, Js::Constants::MinStackInterpreter + varSizeInBytes, returnAddress);
  1286. allocation = (Js::Var*)_alloca(varSizeInBytes);
  1287. }
  1288. Js::LoopHeader* loopHeaderArray = nullptr;
  1289. if (executeFunction->GetHasAllocatedLoopHeaders())
  1290. {
  1291. // Loop header array is recycler allocated, so we push it on the stack
  1292. // When we scan the stack, we'll recognize it as a recycler allocated
  1293. // object, and mark it's contents and keep the individual loop header
  1294. // wrappers alive
  1295. loopHeaderArray = executeFunction->GetLoopHeaderArrayPtr();
  1296. }
  1297. // Set stack address for STEP_OUT/recursion detection for new frame.
  1298. // This frame is originally jitted frame for which we create a new interpreter frame on top of it on stack,
  1299. // set the stack address to some stack location that belong to the original jitted frame.
  1300. DWORD_PTR frameStackAddr = reinterpret_cast<DWORD_PTR>(layout->GetArgv());
  1301. // Initialize the interpreter stack frame (constants) but not the param, the bailout record will restore the value
  1302. #if DBG
  1303. Js::Var invalidStackVar = (Js::RecyclableObject*)_alloca(sizeof(Js::RecyclableObject));
  1304. memset(invalidStackVar, 0xFE, sizeof(Js::RecyclableObject));
  1305. #endif
  1306. newInstance = setup.InitializeAllocation(allocation, stackAllocation, false, false, loopHeaderArray, frameStackAddr
  1307. #if DBG
  1308. , invalidStackVar
  1309. #endif
  1310. );
  1311. newInstance->m_reader.Create(executeFunction);
  1312. }
  1313. int forInEnumeratorArrayRestoreOffset = bailOutRecord->globalBailOutRecordTable->forInEnumeratorArrayRestoreOffset;
  1314. if (forInEnumeratorArrayRestoreOffset != -1)
  1315. {
  1316. newInstance->forInObjectEnumerators = layout->GetForInObjectEnumeratorArrayAtOffset(forInEnumeratorArrayRestoreOffset);
  1317. }
  1318. newInstance->ehBailoutData = bailOutRecord->ehBailoutData;
  1319. newInstance->OrFlags(Js::InterpreterStackFrameFlags_FromBailOut);
  1320. if (bailOutKind == IR::BailOutOnArrayAccessHelperCall)
  1321. {
  1322. newInstance->OrFlags(Js::InterpreterStackFrameFlags_ProcessingBailOutOnArrayAccessHelperCall);
  1323. }
  1324. else if (bailOutKind == IR::BailOutOnNotNativeArray)
  1325. {
  1326. newInstance->OrFlags(Js::InterpreterStackFrameFlags_ProcessingBailOutOnArraySpecialization);
  1327. }
  1328. if (isInlinee)
  1329. {
  1330. newInstance->OrFlags(Js::InterpreterStackFrameFlags_FromBailOutInInlinee);
  1331. }
  1332. ThreadContext *threadContext = newInstance->GetScriptContext()->GetThreadContext();
  1333. // If this is a bailout on implicit calls, then it must have occurred at the current statement.
  1334. // Otherwise, assume that the bits are stale, so clear them before entering the interpreter.
  1335. if (!BailOutInfo::IsBailOutOnImplicitCalls(bailOutKind))
  1336. {
  1337. threadContext->ClearImplicitCallFlags();
  1338. }
  1339. Js::RegSlot varCount = function->GetFunctionBody()->GetVarCount();
  1340. if (varCount)
  1341. {
  1342. Js::RegSlot constantCount = function->GetFunctionBody()->GetConstantCount();
  1343. memset(newInstance->m_localSlots + constantCount, 0, varCount * sizeof(Js::Var));
  1344. }
  1345. Js::RegSlot localFrameDisplayReg = executeFunction->GetLocalFrameDisplayRegister();
  1346. Js::RegSlot localClosureReg = executeFunction->GetLocalClosureRegister();
  1347. Js::RegSlot paramClosureReg = executeFunction->GetParamClosureRegister();
  1348. if (!isInlinee)
  1349. {
  1350. // If byte code was generated to do stack closures, restore closure pointers before the normal RestoreValues.
  1351. // If code was jitted for stack closures, we have to restore the pointers from known stack locations.
  1352. // (RestoreValues won't do it.) If stack closures were disabled for this function before we jitted,
  1353. // then the values on the stack are garbage, but if we need them then RestoreValues will overwrite with
  1354. // the correct values.
  1355. if (localFrameDisplayReg != Js::Constants::NoRegister)
  1356. {
  1357. Js::FrameDisplay *localFrameDisplay;
  1358. uintptr_t frameDisplayIndex = (uintptr_t)(
  1359. #if _M_IX86 || _M_AMD64
  1360. executeFunction->GetInParamsCount() == 0 ?
  1361. Js::JavascriptFunctionArgIndex_StackFrameDisplayNoArg :
  1362. #endif
  1363. Js::JavascriptFunctionArgIndex_StackFrameDisplay) - 2;
  1364. localFrameDisplay = (Js::FrameDisplay*)layout->GetArgv()[frameDisplayIndex];
  1365. newInstance->SetLocalFrameDisplay(localFrameDisplay);
  1366. }
  1367. if (localClosureReg != Js::Constants::NoRegister)
  1368. {
  1369. Js::Var localClosure;
  1370. uintptr_t scopeSlotsIndex = (uintptr_t)(
  1371. #if _M_IX86 || _M_AMD64
  1372. executeFunction->GetInParamsCount() == 0 ?
  1373. Js::JavascriptFunctionArgIndex_StackScopeSlotsNoArg :
  1374. #endif
  1375. Js::JavascriptFunctionArgIndex_StackScopeSlots) - 2;
  1376. localClosure = layout->GetArgv()[scopeSlotsIndex];
  1377. newInstance->SetLocalClosure(localClosure);
  1378. }
  1379. }
  1380. // Restore bailout values
  1381. bailOutRecord->RestoreValues(bailOutKind, layout, newInstance, functionScriptContext, false, registerSaves, bailOutReturnValue, pArgumentsObject, branchValue, returnAddress, useStartCall, argoutRestoreAddress);
  1382. // For functions that don't get the scope slot and frame display pointers back from the known stack locations
  1383. // (see above), get them back from the designated registers.
  1384. // In either case, clear the values from those registers, because the interpreter should not be able to access
  1385. // those values through the registers (only through its private fields).
  1386. if (localFrameDisplayReg != Js::Constants::NoRegister)
  1387. {
  1388. Js::FrameDisplay *frameDisplay = (Js::FrameDisplay*)newInstance->GetNonVarReg(localFrameDisplayReg);
  1389. if (frameDisplay)
  1390. {
  1391. newInstance->SetLocalFrameDisplay(frameDisplay);
  1392. newInstance->SetNonVarReg(localFrameDisplayReg, nullptr);
  1393. }
  1394. }
  1395. if (localClosureReg != Js::Constants::NoRegister)
  1396. {
  1397. Js::Var closure = newInstance->GetNonVarReg(localClosureReg);
  1398. if (closure)
  1399. {
  1400. bailOutRecord->globalBailOutRecordTable->isScopeObjRestored = true;
  1401. newInstance->SetLocalClosure(closure);
  1402. newInstance->SetNonVarReg(localClosureReg, nullptr);
  1403. }
  1404. }
  1405. if (paramClosureReg != Js::Constants::NoRegister)
  1406. {
  1407. Js::Var closure = newInstance->GetNonVarReg(paramClosureReg);
  1408. if (closure)
  1409. {
  1410. newInstance->SetParamClosure(closure);
  1411. newInstance->SetNonVarReg(paramClosureReg, nullptr);
  1412. }
  1413. }
  1414. if (bailOutRecord->globalBailOutRecordTable->hasStackArgOpt)
  1415. {
  1416. newInstance->TrySetFrameObjectInHeapArgObj(functionScriptContext, bailOutRecord->globalBailOutRecordTable->hasNonSimpleParams,
  1417. bailOutRecord->globalBailOutRecordTable->isScopeObjRestored);
  1418. }
  1419. //Reset the value for tracking the restoration during next bail out.
  1420. bailOutRecord->globalBailOutRecordTable->isScopeObjRestored = false;
  1421. uint32 innerScopeCount = executeFunction->GetInnerScopeCount();
  1422. for (uint32 i = 0; i < innerScopeCount; i++)
  1423. {
  1424. Js::RegSlot reg = executeFunction->GetFirstInnerScopeRegister() + i;
  1425. newInstance->SetInnerScopeFromIndex(i, newInstance->GetNonVarReg(reg));
  1426. newInstance->SetNonVarReg(reg, nullptr);
  1427. }
  1428. newInstance->SetClosureInitDone(bailOutOffset != 0 || !(bailOutKind & IR::BailOutForDebuggerBits));
  1429. // RestoreValues may call EnsureArguments and cause functions to be boxed.
  1430. // Since the interpreter frame that hasn't started yet, StackScriptFunction::Box would not have replaced the function object
  1431. // in the restoring interpreter frame. Let's make sure the current interpreter frame has the unboxed version.
  1432. // Note: Only use the unboxed version if we have replaced the function argument on the stack via boxing
  1433. // so that the interpreter frame we are bailing out to matches the one in the function argument list
  1434. // (which is used by the stack walker to match up stack frame and the interpreter frame).
  1435. // Some function are boxed but we continue to use the stack version to call the function - those that only live in register
  1436. // and are not captured in frame displays.
  1437. // Those uses are fine, but that means the function argument list will have the stack function object that is passed it and
  1438. // not be replaced with a just boxed one.
  1439. Js::ScriptFunction * currentFunctionObject = *functionRef;
  1440. if (function != currentFunctionObject)
  1441. {
  1442. Assert(currentFunctionObject == Js::StackScriptFunction::GetCurrentFunctionObject(function));
  1443. newInstance->SetExecutingStackFunction(currentFunctionObject);
  1444. }
  1445. UpdatePolymorphicFieldAccess(function, bailOutRecord);
  1446. BAILOUT_FLUSH(executeFunction);
  1447. executeFunction->BeginExecution();
  1448. // Restart at the bailout byte code offset.
  1449. newInstance->m_reader.SetCurrentOffset(bailOutOffset);
  1450. Js::Var aReturn = nullptr;
  1451. {
  1452. // Following _AddressOfReturnAddress <= real address of "returnAddress". Suffices for RemoteStackWalker to test partially initialized interpreter frame.
  1453. Js::InterpreterStackFrame::PushPopFrameHelper pushPopFrameHelper(newInstance, returnAddress, _AddressOfReturnAddress());
  1454. #ifdef ENABLE_SCRIPT_DEBUGGING
  1455. aReturn = isInDebugMode ? newInstance->DebugProcess() : newInstance->Process();
  1456. #else
  1457. aReturn = newInstance->Process();
  1458. #endif
  1459. // Note: in debug mode we always have to bailout to debug thunk,
  1460. // as normal interpreter thunk expects byte code compiled w/o debugging.
  1461. }
  1462. executeFunction->EndExecution();
  1463. if (executeFunction->HasDynamicProfileInfo())
  1464. {
  1465. Js::DynamicProfileInfo *dynamicProfileInfo = executeFunction->GetAnyDynamicProfileInfo();
  1466. dynamicProfileInfo->RecordImplicitCallFlags(threadContext->GetImplicitCallFlags());
  1467. }
  1468. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, _u("BailOut: Return Value: 0x%p"), aReturn);
  1469. if (bailOutRecord->globalBailOutRecordTable->isInlinedConstructor)
  1470. {
  1471. AssertMsg(!executeFunction->IsGenerator(), "Generator functions are not expected to be inlined. If this changes then need to use the real user args here from the generator object");
  1472. Assert(args.Info.Count != 0);
  1473. aReturn = Js::JavascriptFunction::FinishConstructor(aReturn, args.Values[0], function);
  1474. Js::Var oldValue = aReturn;
  1475. aReturn = Js::JavascriptOperators::BoxStackInstance(oldValue, functionScriptContext, /* allowStackFunction */ true, /* deepCopy */ false);
  1476. #if ENABLE_DEBUG_CONFIG_OPTIONS
  1477. if (oldValue != aReturn)
  1478. {
  1479. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, _u(" (Boxed: 0x%p)"), aReturn);
  1480. }
  1481. #endif
  1482. }
  1483. BAILOUT_VERBOSE_TRACE(newInstance->function->GetFunctionBody(), bailOutKind, _u("\n"));
  1484. return aReturn;
  1485. }
  1486. // Note on rejit states
  1487. //
  1488. // To avoid always incurring the cost of collecting runtime stats (function calls count and valid bailOutKind),
  1489. // the initial codegen'd version of a function does not collect them. After a second bailout we rejit the function
  1490. // with runtime stats collection. On subsequent bailouts we can evaluate our heuristics and decide whether to rejit.
  1491. //
  1492. // Function bodies always use the least optimized version of the code as default. At the same time, there can be
  1493. // function objects with some older, more optimized, version of the code active. When a bailout occurs out of such
  1494. // code we avoid a rejit by checking if the offending optimization has been disabled in the default code and if so
  1495. // we "rethunk" the bailing out function rather that incurring a rejit.
  1496. // actualBailOutOffset - bail out offset in the function, inlinee or otherwise, that had the bailout.
  1497. void BailOutRecord::ScheduleFunctionCodeGen(Js::ScriptFunction * function, Js::ScriptFunction * innerMostInlinee,
  1498. BailOutRecord const * bailOutRecord, IR::BailOutKind bailOutKind, uint32 actualBailOutOffset, Js::ImplicitCallFlags savedImplicitCallFlags, void * returnAddress)
  1499. {
  1500. if (bailOutKind == IR::BailOnSimpleJitToFullJitLoopBody ||
  1501. bailOutKind == IR::BailOutForGeneratorYield ||
  1502. bailOutKind == IR::LazyBailOut)
  1503. {
  1504. return;
  1505. }
  1506. Js::FunctionBody * executeFunction = function->GetFunctionBody();
  1507. if (PHASE_OFF(Js::ReJITPhase, executeFunction))
  1508. {
  1509. return;
  1510. }
  1511. Js::AutoPushReturnAddressForStackWalker saveReturnAddress(executeFunction->GetScriptContext(), returnAddress);
  1512. BailOutRecord * bailOutRecordNotConst = (BailOutRecord *)(void *)bailOutRecord;
  1513. bailOutRecordNotConst->bailOutCount++;
  1514. Js::FunctionEntryPointInfo *entryPointInfo = bailOutRecord->GetFunctionEntryPointInfo();
  1515. #if DBG
  1516. // BailOutRecord is not recycler-allocated, so make sure something the recycler can see was keeping the entry point info alive.
  1517. // We expect the entry point to be kept alive as follows:
  1518. // 1. The function's current type might still have the same entry point info as when we entered the function (easy case)
  1519. // 2. The function might have moved to a successor path type, which still keeps the previous type and its entry point info alive
  1520. // 3. The entry point info might be held by the ThreadContext (QueueFreeOldEntryPointInfoIfInScript):
  1521. // a. If the entry point info was replaced on the type that used to hold it (ScriptFunction::ChangeEntryPoint)
  1522. // b. If the function's last-added property was deleted and it moved to a previous type (ScriptFunction::ReplaceTypeWithPredecessorType)
  1523. // c. If the function's path type got replaced with a dictionary, then all previous entry point infos in that path are queued on the ThreadContext (ScriptFunction::PrepareForConversionToNonPathType)
  1524. bool foundEntryPoint = false;
  1525. executeFunction->MapEntryPointsUntil([&](int index, Js::FunctionEntryPointInfo* info)
  1526. {
  1527. foundEntryPoint = info == entryPointInfo;
  1528. return foundEntryPoint;
  1529. });
  1530. foundEntryPoint = foundEntryPoint || function->GetScriptContext()->GetThreadContext()->IsOldEntryPointInfo(entryPointInfo);
  1531. Assert(foundEntryPoint);
  1532. #endif
  1533. uint8 callsCount = entryPointInfo->callsCount > 255 ? 255 : static_cast<uint8>(entryPointInfo->callsCount);
  1534. RejitReason rejitReason = RejitReason::None;
  1535. bool reThunk = false;
  1536. callsCount = callsCount <= Js::FunctionEntryPointInfo::GetDecrCallCountPerBailout() ? 0 : callsCount - Js::FunctionEntryPointInfo::GetDecrCallCountPerBailout() ;
  1537. CheckPreemptiveRejit(executeFunction, bailOutKind, bailOutRecordNotConst, callsCount, -1);
  1538. entryPointInfo->callsCount = callsCount;
  1539. Assert(bailOutKind != IR::BailOutInvalid);
  1540. Js::DynamicProfileInfo * profileInfo = executeFunction->HasDynamicProfileInfo() ? executeFunction->GetAnyDynamicProfileInfo() : nullptr;
  1541. if ((profileInfo && callsCount == 0) ||
  1542. PHASE_FORCE(Js::ReJITPhase, executeFunction))
  1543. {
  1544. if ((bailOutKind & (IR::BailOutOnResultConditions | IR::BailOutOnDivSrcConditions)) || bailOutKind == IR::BailOutIntOnly || bailOutKind == IR::BailOnIntMin || bailOutKind == IR::BailOnDivResultNotInt)
  1545. {
  1546. // Note WRT BailOnIntMin: it wouldn't make sense to re-jit without changing anything here, as interpreter will not change the (int) type,
  1547. // so the options are: (1) rejit with disabling int type spec, (2) don't rejit, always bailout.
  1548. // It seems to be better to rejit.
  1549. if (bailOutKind & IR::BailOutOnMulOverflow)
  1550. {
  1551. if (profileInfo->IsAggressiveMulIntTypeSpecDisabled(false))
  1552. {
  1553. reThunk = true;
  1554. }
  1555. else
  1556. {
  1557. profileInfo->DisableAggressiveMulIntTypeSpec(false);
  1558. rejitReason = RejitReason::AggressiveMulIntTypeSpecDisabled;
  1559. }
  1560. }
  1561. else if ((bailOutKind & (IR::BailOutOnDivByZero | IR::BailOutOnDivOfMinInt)) || bailOutKind == IR::BailOnDivResultNotInt)
  1562. {
  1563. if (profileInfo->IsDivIntTypeSpecDisabled(false))
  1564. {
  1565. reThunk = true;
  1566. }
  1567. else
  1568. {
  1569. profileInfo->DisableDivIntTypeSpec(false);
  1570. rejitReason = RejitReason::DivIntTypeSpecDisabled;
  1571. }
  1572. }
  1573. else
  1574. {
  1575. if (profileInfo->IsAggressiveIntTypeSpecDisabled(false))
  1576. {
  1577. reThunk = true;
  1578. }
  1579. else
  1580. {
  1581. profileInfo->DisableAggressiveIntTypeSpec(false);
  1582. rejitReason = RejitReason::AggressiveIntTypeSpecDisabled;
  1583. }
  1584. }
  1585. }
  1586. else if (bailOutKind & IR::BailOutForDebuggerBits)
  1587. {
  1588. // Do not rejit, do not rethunk, just ignore the bailout.
  1589. }
  1590. else switch(bailOutKind)
  1591. {
  1592. case IR::BailOutOnNotPrimitive:
  1593. if (profileInfo->IsLossyIntTypeSpecDisabled())
  1594. {
  1595. reThunk = true;
  1596. }
  1597. else
  1598. {
  1599. profileInfo->DisableLossyIntTypeSpec();
  1600. rejitReason = RejitReason::LossyIntTypeSpecDisabled;
  1601. }
  1602. break;
  1603. case IR::BailOutOnMemOpError:
  1604. if (profileInfo->IsMemOpDisabled())
  1605. {
  1606. reThunk = true;
  1607. }
  1608. else
  1609. {
  1610. profileInfo->DisableMemOp();
  1611. rejitReason = RejitReason::MemOpDisabled;
  1612. }
  1613. break;
  1614. case IR::BailOutPrimitiveButString:
  1615. case IR::BailOutNumberOnly:
  1616. if (profileInfo->IsFloatTypeSpecDisabled())
  1617. {
  1618. reThunk = true;
  1619. }
  1620. else
  1621. {
  1622. profileInfo->DisableFloatTypeSpec();
  1623. rejitReason = RejitReason::FloatTypeSpecDisabled;
  1624. }
  1625. break;
  1626. case IR::BailOutOnImplicitCalls:
  1627. case IR::BailOutOnImplicitCallsPreOp:
  1628. // Check if the implicit call flags in the profile have changed since we last JITed this
  1629. // function body. If so, and they indicate an implicit call of some sort occurred
  1630. // then we need to reJIT.
  1631. if ((executeFunction->GetSavedImplicitCallsFlags() & savedImplicitCallFlags) == Js::ImplicitCall_None)
  1632. {
  1633. profileInfo->RecordImplicitCallFlags(savedImplicitCallFlags);
  1634. profileInfo->DisableLoopImplicitCallInfo();
  1635. rejitReason = RejitReason::ImplicitCallFlagsChanged;
  1636. }
  1637. else
  1638. {
  1639. reThunk = true;
  1640. }
  1641. break;
  1642. case IR::BailOnModByPowerOf2:
  1643. rejitReason = RejitReason::ModByPowerOf2;
  1644. break;
  1645. case IR::BailOutOnNotArray:
  1646. if(profileInfo->IsArrayCheckHoistDisabled(false))
  1647. {
  1648. reThunk = true;
  1649. }
  1650. else
  1651. {
  1652. profileInfo->DisableArrayCheckHoist(false);
  1653. rejitReason = RejitReason::ArrayCheckHoistDisabled;
  1654. }
  1655. break;
  1656. case IR::BailOutOnNotNativeArray:
  1657. // REVIEW: We have an issue with array profile info. The info on the type of array we have won't
  1658. // get fixed by rejitting. For now, just give up after 50 rejits.
  1659. if (profileInfo->GetRejitCount() >= 50)
  1660. {
  1661. reThunk = true;
  1662. }
  1663. else
  1664. {
  1665. rejitReason = RejitReason::ExpectingNativeArray;
  1666. }
  1667. break;
  1668. case IR::BailOutConvertedNativeArray:
  1669. rejitReason = RejitReason::ConvertedNativeArray;
  1670. break;
  1671. case IR::BailOutConventionalTypedArrayAccessOnly:
  1672. if(profileInfo->IsTypedArrayTypeSpecDisabled(false))
  1673. {
  1674. reThunk = true;
  1675. }
  1676. else
  1677. {
  1678. profileInfo->DisableTypedArrayTypeSpec(false);
  1679. rejitReason = RejitReason::TypedArrayTypeSpecDisabled;
  1680. }
  1681. break;
  1682. case IR::BailOutConventionalNativeArrayAccessOnly:
  1683. rejitReason = RejitReason::ExpectingConventionalNativeArrayAccess;
  1684. break;
  1685. case IR::BailOutOnMissingValue:
  1686. if(profileInfo->IsArrayMissingValueCheckHoistDisabled(false))
  1687. {
  1688. reThunk = true;
  1689. }
  1690. else
  1691. {
  1692. profileInfo->DisableArrayMissingValueCheckHoist(false);
  1693. rejitReason = RejitReason::ArrayMissingValueCheckHoistDisabled;
  1694. }
  1695. break;
  1696. case IR::BailOutOnArrayAccessHelperCall:
  1697. // This is a pre-op bailout, so the interpreter will update the profile data for this byte-code instruction to
  1698. // prevent excessive bailouts here in the future
  1699. rejitReason = RejitReason::ArrayAccessNeededHelperCall;
  1700. break;
  1701. case IR::BailOutOnInvalidatedArrayHeadSegment:
  1702. if(profileInfo->IsJsArraySegmentHoistDisabled(false))
  1703. {
  1704. reThunk = true;
  1705. }
  1706. else
  1707. {
  1708. profileInfo->DisableJsArraySegmentHoist(false);
  1709. rejitReason = RejitReason::JsArraySegmentHoistDisabled;
  1710. }
  1711. break;
  1712. case IR::BailOutOnIrregularLength:
  1713. if(profileInfo->IsLdLenIntSpecDisabled())
  1714. {
  1715. reThunk = true;
  1716. }
  1717. else
  1718. {
  1719. profileInfo->DisableLdLenIntSpec();
  1720. rejitReason = RejitReason::LdLenIntSpecDisabled;
  1721. }
  1722. break;
  1723. case IR::BailOutOnFailedHoistedBoundCheck:
  1724. if(profileInfo->IsBoundCheckHoistDisabled(false))
  1725. {
  1726. reThunk = true;
  1727. }
  1728. else
  1729. {
  1730. profileInfo->DisableBoundCheckHoist(false);
  1731. rejitReason = RejitReason::BoundCheckHoistDisabled;
  1732. }
  1733. break;
  1734. case IR::BailOutOnFailedHoistedLoopCountBasedBoundCheck:
  1735. if(profileInfo->IsLoopCountBasedBoundCheckHoistDisabled(false))
  1736. {
  1737. reThunk = true;
  1738. }
  1739. else
  1740. {
  1741. profileInfo->DisableLoopCountBasedBoundCheckHoist(false);
  1742. rejitReason = RejitReason::LoopCountBasedBoundCheckHoistDisabled;
  1743. }
  1744. break;
  1745. case IR::BailOutExpectingInteger:
  1746. if (profileInfo->IsSwitchOptDisabled())
  1747. {
  1748. reThunk = true;
  1749. }
  1750. else
  1751. {
  1752. profileInfo->DisableSwitchOpt();
  1753. rejitReason = RejitReason::DisableSwitchOptExpectingInteger;
  1754. }
  1755. break;
  1756. case IR::BailOutExpectingString:
  1757. if (profileInfo->IsSwitchOptDisabled())
  1758. {
  1759. reThunk = true;
  1760. }
  1761. else
  1762. {
  1763. profileInfo->DisableSwitchOpt();
  1764. rejitReason = RejitReason::DisableSwitchOptExpectingString;
  1765. }
  1766. break;
  1767. case IR::BailOutOnFailedPolymorphicInlineTypeCheck:
  1768. rejitReason = RejitReason::FailedPolymorphicInlineeTypeCheck;
  1769. break;
  1770. case IR::BailOnStackArgsOutOfActualsRange:
  1771. if (profileInfo->IsStackArgOptDisabled())
  1772. {
  1773. reThunk = true;
  1774. }
  1775. else
  1776. {
  1777. profileInfo->DisableStackArgOpt();
  1778. rejitReason = RejitReason::DisableStackArgOpt;
  1779. }
  1780. break;
  1781. case IR::BailOutOnPolymorphicInlineFunction:
  1782. case IR::BailOutFailedInlineTypeCheck:
  1783. case IR::BailOutOnInlineFunction:
  1784. // Check if the inliner state has changed since we last JITed this function body. If so
  1785. // then we need to reJIT.
  1786. if (innerMostInlinee)
  1787. {
  1788. // There is no way now to check if the inlinee version has changed. Just rejit.
  1789. // This should be changed to getting the inliner version corresponding to inlinee.
  1790. rejitReason = RejitReason::InlineeChanged;
  1791. }
  1792. else
  1793. {
  1794. if (executeFunction->GetSavedInlinerVersion() == profileInfo->GetInlinerVersion())
  1795. {
  1796. reThunk = true;
  1797. }
  1798. else
  1799. {
  1800. rejitReason = RejitReason::InlineeChanged;
  1801. }
  1802. }
  1803. break;
  1804. case IR::BailOutOnNoProfile:
  1805. if (profileInfo->IsNoProfileBailoutsDisabled())
  1806. {
  1807. reThunk = true;
  1808. }
  1809. else if (executeFunction->IncrementBailOnMisingProfileRejitCount() > (uint)CONFIG_FLAG(BailOnNoProfileRejitLimit))
  1810. {
  1811. profileInfo->DisableNoProfileBailouts();
  1812. rejitReason = RejitReason::NoProfile;
  1813. }
  1814. else
  1815. {
  1816. executeFunction->ResetBailOnMisingProfileCount();
  1817. rejitReason = RejitReason::NoProfile;
  1818. }
  1819. break;
  1820. case IR::BailOutCheckThis:
  1821. // Presumably we've started passing a different "this" pointer to callees.
  1822. if (profileInfo->IsCheckThisDisabled())
  1823. {
  1824. reThunk = true;
  1825. }
  1826. else
  1827. {
  1828. profileInfo->DisableCheckThis();
  1829. rejitReason = RejitReason::CheckThisDisabled;
  1830. }
  1831. break;
  1832. case IR::BailOutOnTaggedValue:
  1833. if (profileInfo->IsTagCheckDisabled())
  1834. {
  1835. reThunk = true;
  1836. }
  1837. else
  1838. {
  1839. profileInfo->DisableTagCheck();
  1840. rejitReason = RejitReason::FailedTagCheck;
  1841. }
  1842. break;
  1843. case IR::BailOutFailedTypeCheck:
  1844. case IR::BailOutFailedFixedFieldTypeCheck:
  1845. {
  1846. // An inline cache must have gone from monomorphic to polymorphic.
  1847. // This is already noted in the profile data, so optimization of the given ld/st will
  1848. // be inhibited on re-jit.
  1849. // Consider disabling the optimization across the function after n failed type checks.
  1850. if (innerMostInlinee)
  1851. {
  1852. rejitReason = bailOutKind == IR::BailOutFailedTypeCheck ? RejitReason::FailedTypeCheck : RejitReason::FailedFixedFieldTypeCheck;
  1853. }
  1854. else
  1855. {
  1856. uint32 state;
  1857. state = profileInfo->GetPolymorphicCacheState();
  1858. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  1859. if (PHASE_TRACE(Js::ObjTypeSpecPhase, executeFunction))
  1860. {
  1861. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  1862. Output::Print(
  1863. _u("Objtypespec (%s): States on bailout: Saved cache: %d, Live cache: %d\n"),
  1864. executeFunction->GetDebugNumberSet(debugStringBuffer), executeFunction->GetSavedPolymorphicCacheState(), state);
  1865. Output::Flush();
  1866. }
  1867. #endif
  1868. if (state <= executeFunction->GetSavedPolymorphicCacheState())
  1869. {
  1870. reThunk = true;
  1871. }
  1872. else
  1873. {
  1874. rejitReason = bailOutKind == IR::BailOutFailedTypeCheck ?
  1875. RejitReason::FailedTypeCheck : RejitReason::FailedFixedFieldTypeCheck;
  1876. }
  1877. }
  1878. break;
  1879. }
  1880. case IR::BailOutFailedEquivalentTypeCheck:
  1881. case IR::BailOutFailedEquivalentFixedFieldTypeCheck:
  1882. if (profileInfo->IsEquivalentObjTypeSpecDisabled())
  1883. {
  1884. reThunk = true;
  1885. }
  1886. else
  1887. {
  1888. rejitReason = bailOutKind == IR::BailOutFailedEquivalentTypeCheck ?
  1889. RejitReason::FailedEquivalentTypeCheck : RejitReason::FailedEquivalentFixedFieldTypeCheck;
  1890. }
  1891. break;
  1892. case IR::BailOutFailedFixedFieldCheck:
  1893. rejitReason = RejitReason::FailedFixedFieldCheck;
  1894. break;
  1895. case IR::BailOutFailedCtorGuardCheck:
  1896. // (ObjTypeSpec): Consider scheduling re-JIT right after the first bailout. We will never successfully execute the
  1897. // function from which we just bailed out, unless we take a different code path through it.
  1898. // A constructor cache guard may be invalidated for one of two reasons:
  1899. // a) the constructor's prototype property has changed, or
  1900. // b) one of the properties protected by the guard (this constructor cache served as) has changed in some way (e.g. became read-only).
  1901. // In the former case, the cache itself will be marked as polymorphic and on re-JIT we won't do the optimization.
  1902. // In the latter case, the inline cache for the offending property will be cleared and on re-JIT the guard will not be enlisted
  1903. // to protect that property operation.
  1904. rejitReason = RejitReason::CtorGuardInvalidated;
  1905. break;
  1906. case IR::BailOutOnFloor:
  1907. {
  1908. if (profileInfo->IsFloorInliningDisabled())
  1909. {
  1910. reThunk = true;
  1911. }
  1912. else
  1913. {
  1914. profileInfo->DisableFloorInlining();
  1915. rejitReason = RejitReason::FloorInliningDisabled;
  1916. }
  1917. break;
  1918. }
  1919. case IR::BailOutOnPowIntIntOverflow:
  1920. {
  1921. if (profileInfo->IsPowIntIntTypeSpecDisabled())
  1922. {
  1923. reThunk = true;
  1924. }
  1925. else
  1926. {
  1927. profileInfo->DisablePowIntIntTypeSpec();
  1928. rejitReason = RejitReason::PowIntIntTypeSpecDisabled;
  1929. }
  1930. break;
  1931. }
  1932. case IR::BailOutOnEarlyExit:
  1933. {
  1934. if (profileInfo->IsOptimizeTryFinallyDisabled())
  1935. {
  1936. reThunk = true;
  1937. }
  1938. else
  1939. {
  1940. profileInfo->DisableOptimizeTryFinally();
  1941. rejitReason = RejitReason::OptimizeTryFinallyDisabled;
  1942. }
  1943. break;
  1944. }
  1945. }
  1946. Assert(!(rejitReason != RejitReason::None && reThunk));
  1947. }
  1948. if(PHASE_FORCE(Js::ReJITPhase, executeFunction) && rejitReason == RejitReason::None)
  1949. {
  1950. rejitReason = RejitReason::Forced;
  1951. }
  1952. if (!reThunk && rejitReason != RejitReason::None)
  1953. {
  1954. // REVIEW: Temporary fix for RS1. Disable Rejiting if it looks like it is not fixing the problem.
  1955. // For RS2, turn the rejitCount check into an assert and let's fix all these issues.
  1956. if (profileInfo->GetRejitCount() >= 100 ||
  1957. (profileInfo->GetBailOutOffsetForLastRejit() == actualBailOutOffset && function->IsNewEntryPointAvailable()))
  1958. {
  1959. #ifdef REJIT_STATS
  1960. Js::ScriptContext* scriptContext = executeFunction->GetScriptContext();
  1961. if (scriptContext->rejitReasonCountsCap != nullptr)
  1962. {
  1963. scriptContext->rejitReasonCountsCap[static_cast<byte>(rejitReason)]++;
  1964. }
  1965. #endif
  1966. reThunk = true;
  1967. rejitReason = RejitReason::None;
  1968. }
  1969. else
  1970. {
  1971. profileInfo->IncRejitCount();
  1972. profileInfo->SetBailOutOffsetForLastRejit(actualBailOutOffset);
  1973. }
  1974. }
  1975. REJIT_KIND_TESTTRACE(bailOutKind, _u("Bailout from function: function: %s, bailOutKindName: (%S), bailOutCount: %d, callCount: %d, reJitReason: %S, reThunk: %s\r\n"),
  1976. function->GetFunctionBody()->GetDisplayName(), ::GetBailOutKindName(bailOutKind), bailOutRecord->bailOutCount, callsCount,
  1977. GetRejitReasonName(rejitReason), reThunk ? trueString : falseString);
  1978. JS_ETW(EventWriteJSCRIPT_BACKEND_BAILOUT(function->GetFunctionBody()->GetLocalFunctionId(),
  1979. function->GetFunctionBody()->GetSourceContextId(), function->GetFunctionBody()->GetDisplayName(), bailOutKind, bailOutRecord->bailOutCount, callsCount,
  1980. GetRejitReasonName(rejitReason), reThunk));
  1981. #ifdef REJIT_STATS
  1982. executeFunction->GetScriptContext()->LogBailout(executeFunction, bailOutKind);
  1983. if (bailOutRecord->bailOutCount > 500)
  1984. {
  1985. Js::ScriptContext* scriptContext = executeFunction->GetScriptContext();
  1986. auto bailoutReasonCountsCap = scriptContext->bailoutReasonCountsCap;
  1987. if (bailoutReasonCountsCap != nullptr)
  1988. {
  1989. if (!bailoutReasonCountsCap->ContainsKey(bailOutKind))
  1990. {
  1991. bailoutReasonCountsCap->Item(bailOutKind, 1);
  1992. }
  1993. else
  1994. {
  1995. uint val = bailoutReasonCountsCap->Item(bailOutKind);
  1996. ++val;
  1997. bailoutReasonCountsCap->Item(bailOutKind, val);
  1998. }
  1999. }
  2000. }
  2001. #endif
  2002. if (reThunk && executeFunction->DontRethunkAfterBailout())
  2003. {
  2004. // This function is marked for rethunking, but the last ReJIT we've done was for a JIT loop body
  2005. // So the latest rejitted version of this function may not have the right optimization disabled.
  2006. // Rejit just to be safe.
  2007. reThunk = false;
  2008. rejitReason = RejitReason::AfterLoopBodyRejit;
  2009. }
  2010. if (reThunk)
  2011. {
  2012. Js::FunctionEntryPointInfo *const defaultEntryPointInfo = executeFunction->GetDefaultFunctionEntryPointInfo();
  2013. function->UpdateThunkEntryPoint(defaultEntryPointInfo, executeFunction->GetDirectEntryPoint(defaultEntryPointInfo));
  2014. }
  2015. else if (rejitReason != RejitReason::None)
  2016. {
  2017. if (bailOutRecord->IsForLoopTop() && IR::IsTypeCheckBailOutKind(bailOutRecord->bailOutKind))
  2018. {
  2019. // Disable FieldPRE if we're triggering a type check rejit due to a bailout at the loop top.
  2020. // Most likely this was caused by a CheckFixedFld that was hoisted from a branch block where
  2021. // only certain types flowed, to the loop top, where more types (different or non-equivalent)
  2022. // were flowing in.
  2023. profileInfo->DisableFieldPRE();
  2024. }
  2025. #ifdef REJIT_STATS
  2026. executeFunction->GetScriptContext()->LogRejit(executeFunction, rejitReason);
  2027. #endif
  2028. executeFunction->ClearDontRethunkAfterBailout();
  2029. GenerateFunction(executeFunction->GetScriptContext()->GetNativeCodeGenerator(), executeFunction, function);
  2030. if(executeFunction->GetExecutionMode() != ExecutionMode::FullJit)
  2031. {
  2032. // With expiry, it's possible that the execution mode is currently interpreter or simple JIT. Transition to full JIT
  2033. // after successfully scheduling the rejit work item (in case of OOM).
  2034. executeFunction->TraceExecutionMode("Rejit (before)");
  2035. executeFunction->TransitionToFullJitExecutionMode();
  2036. executeFunction->TraceExecutionMode("Rejit");
  2037. }
  2038. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2039. if(PHASE_TRACE(Js::ReJITPhase, executeFunction))
  2040. {
  2041. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2042. Output::Print(
  2043. _u("Rejit: function: %s (%s), bailOutCount: %hu"),
  2044. executeFunction->GetDisplayName(),
  2045. executeFunction->GetDebugNumberSet(debugStringBuffer),
  2046. bailOutRecord->bailOutCount);
  2047. Output::Print(_u(" callCount: %u"), callsCount);
  2048. Output::Print(_u(" reason: %S"), GetRejitReasonName(rejitReason));
  2049. if(bailOutKind != IR::BailOutInvalid)
  2050. {
  2051. Output::Print(_u(" (%S)"), ::GetBailOutKindName(bailOutKind));
  2052. }
  2053. Output::Print(_u("\n"));
  2054. Output::Flush();
  2055. }
  2056. #endif
  2057. }
  2058. }
  2059. // To avoid always incurring the cost of collecting runtime stats (valid bailOutKind),
  2060. // the initial codegen'd version of a loop body does not collect them. After a second bailout we rejit the body
  2061. // with runtime stats collection. On subsequent bailouts we can evaluate our heuristics.
  2062. void BailOutRecord::ScheduleLoopBodyCodeGen(Js::ScriptFunction * function, Js::ScriptFunction * innerMostInlinee, BailOutRecord const * bailOutRecord, IR::BailOutKind bailOutKind)
  2063. {
  2064. Assert(bailOutKind != IR::LazyBailOut);
  2065. Js::FunctionBody * executeFunction = function->GetFunctionBody();
  2066. if (PHASE_OFF(Js::ReJITPhase, executeFunction))
  2067. {
  2068. return;
  2069. }
  2070. Js::LoopHeader * loopHeader = nullptr;
  2071. Js::InterpreterStackFrame * interpreterFrame = executeFunction->GetScriptContext()->GetThreadContext()->GetLeafInterpreterFrame();
  2072. loopHeader = executeFunction->GetLoopHeader(interpreterFrame->GetCurrentLoopNum());
  2073. Assert(loopHeader != nullptr);
  2074. BailOutRecord * bailOutRecordNotConst = (BailOutRecord *)(void *)bailOutRecord;
  2075. bailOutRecordNotConst->bailOutCount++;
  2076. RejitReason rejitReason = RejitReason::None;
  2077. Assert(bailOutKind != IR::BailOutInvalid);
  2078. Js::LoopEntryPointInfo* entryPointInfo = loopHeader->GetCurrentEntryPointInfo();
  2079. entryPointInfo->totalJittedLoopIterations += entryPointInfo->jittedLoopIterationsSinceLastBailout;
  2080. entryPointInfo->jittedLoopIterationsSinceLastBailout = 0;
  2081. uint8 totalJittedLoopIterations = entryPointInfo->totalJittedLoopIterations > 255 ? 255 : static_cast<uint8>(entryPointInfo->totalJittedLoopIterations);
  2082. totalJittedLoopIterations = totalJittedLoopIterations <= Js::LoopEntryPointInfo::GetDecrLoopCountPerBailout() ? 0 : totalJittedLoopIterations - Js::LoopEntryPointInfo::GetDecrLoopCountPerBailout();
  2083. CheckPreemptiveRejit(executeFunction, bailOutKind, bailOutRecordNotConst, totalJittedLoopIterations, interpreterFrame->GetCurrentLoopNum());
  2084. entryPointInfo->totalJittedLoopIterations = totalJittedLoopIterations;
  2085. if ((executeFunction->HasDynamicProfileInfo() && totalJittedLoopIterations == 0) ||
  2086. PHASE_FORCE(Js::ReJITPhase, executeFunction))
  2087. {
  2088. Js::DynamicProfileInfo * profileInfo = executeFunction->GetAnyDynamicProfileInfo();
  2089. if ((bailOutKind & (IR::BailOutOnResultConditions | IR::BailOutOnDivSrcConditions)) || bailOutKind == IR::BailOutIntOnly || bailOutKind == IR::BailOnIntMin)
  2090. {
  2091. if (bailOutKind & IR::BailOutOnMulOverflow)
  2092. {
  2093. profileInfo->DisableAggressiveMulIntTypeSpec(true);
  2094. rejitReason = RejitReason::AggressiveMulIntTypeSpecDisabled;
  2095. }
  2096. else if ((bailOutKind & (IR::BailOutOnDivByZero | IR::BailOutOnDivOfMinInt)) || bailOutKind == IR::BailOnDivResultNotInt)
  2097. {
  2098. profileInfo->DisableDivIntTypeSpec(true);
  2099. rejitReason = RejitReason::DivIntTypeSpecDisabled;
  2100. }
  2101. else
  2102. {
  2103. profileInfo->DisableAggressiveIntTypeSpec(true);
  2104. rejitReason = RejitReason::AggressiveIntTypeSpecDisabled;
  2105. }
  2106. executeFunction->SetDontRethunkAfterBailout();
  2107. }
  2108. else switch(bailOutKind)
  2109. {
  2110. case IR::BailOutOnNotPrimitive:
  2111. profileInfo->DisableLossyIntTypeSpec();
  2112. executeFunction->SetDontRethunkAfterBailout();
  2113. rejitReason = RejitReason::LossyIntTypeSpecDisabled;
  2114. break;
  2115. case IR::BailOutOnMemOpError:
  2116. profileInfo->DisableMemOp();
  2117. executeFunction->SetDontRethunkAfterBailout();
  2118. rejitReason = RejitReason::MemOpDisabled;
  2119. break;
  2120. case IR::BailOutPrimitiveButString:
  2121. case IR::BailOutNumberOnly:
  2122. profileInfo->DisableFloatTypeSpec();
  2123. executeFunction->SetDontRethunkAfterBailout();
  2124. rejitReason = RejitReason::FloatTypeSpecDisabled;
  2125. break;
  2126. case IR::BailOutOnImplicitCalls:
  2127. case IR::BailOutOnImplicitCallsPreOp:
  2128. rejitReason = RejitReason::ImplicitCallFlagsChanged;
  2129. break;
  2130. case IR::BailOutExpectingInteger:
  2131. profileInfo->DisableSwitchOpt();
  2132. executeFunction->SetDontRethunkAfterBailout();
  2133. rejitReason = RejitReason::DisableSwitchOptExpectingInteger;
  2134. break;
  2135. case IR::BailOutExpectingString:
  2136. profileInfo->DisableSwitchOpt();
  2137. executeFunction->SetDontRethunkAfterBailout();
  2138. rejitReason = RejitReason::DisableSwitchOptExpectingString;
  2139. break;
  2140. case IR::BailOnStackArgsOutOfActualsRange:
  2141. AssertMsg(false, "How did we reach here ? Stack args opt is currently disabled in loop body gen.");
  2142. break;
  2143. case IR::BailOnModByPowerOf2:
  2144. rejitReason = RejitReason::ModByPowerOf2;
  2145. break;
  2146. case IR::BailOutOnNotArray:
  2147. profileInfo->DisableArrayCheckHoist(true);
  2148. executeFunction->SetDontRethunkAfterBailout();
  2149. rejitReason = RejitReason::ArrayCheckHoistDisabled;
  2150. break;
  2151. case IR::BailOutOnNotNativeArray:
  2152. // REVIEW: We have an issue with array profile info. The info on the type of array we have won't
  2153. // get fixed by rejitting. For now, just give up after 50 rejits.
  2154. if (loopHeader->GetRejitCount() >= 50)
  2155. {
  2156. rejitReason = RejitReason::None;
  2157. }
  2158. else
  2159. {
  2160. rejitReason = RejitReason::ExpectingNativeArray;
  2161. }
  2162. break;
  2163. case IR::BailOutConvertedNativeArray:
  2164. rejitReason = RejitReason::ConvertedNativeArray;
  2165. break;
  2166. case IR::BailOutConventionalTypedArrayAccessOnly:
  2167. profileInfo->DisableTypedArrayTypeSpec(true);
  2168. executeFunction->SetDontRethunkAfterBailout();
  2169. rejitReason = RejitReason::TypedArrayTypeSpecDisabled;
  2170. break;
  2171. case IR::BailOutConventionalNativeArrayAccessOnly:
  2172. rejitReason = RejitReason::ExpectingConventionalNativeArrayAccess;
  2173. break;
  2174. case IR::BailOutOnMissingValue:
  2175. profileInfo->DisableArrayMissingValueCheckHoist(true);
  2176. rejitReason = RejitReason::ArrayMissingValueCheckHoistDisabled;
  2177. break;
  2178. case IR::BailOutOnArrayAccessHelperCall:
  2179. // This is a pre-op bailout, so the interpreter will update the profile data for this byte-code instruction to
  2180. // prevent excessive bailouts here in the future
  2181. rejitReason = RejitReason::ArrayAccessNeededHelperCall;
  2182. break;
  2183. case IR::BailOutOnInvalidatedArrayHeadSegment:
  2184. profileInfo->DisableJsArraySegmentHoist(true);
  2185. executeFunction->SetDontRethunkAfterBailout();
  2186. rejitReason = RejitReason::JsArraySegmentHoistDisabled;
  2187. break;
  2188. case IR::BailOutOnIrregularLength:
  2189. profileInfo->DisableLdLenIntSpec();
  2190. executeFunction->SetDontRethunkAfterBailout();
  2191. rejitReason = RejitReason::LdLenIntSpecDisabled;
  2192. break;
  2193. case IR::BailOutOnFailedHoistedBoundCheck:
  2194. profileInfo->DisableBoundCheckHoist(true);
  2195. executeFunction->SetDontRethunkAfterBailout();
  2196. rejitReason = RejitReason::BoundCheckHoistDisabled;
  2197. break;
  2198. case IR::BailOutOnFailedHoistedLoopCountBasedBoundCheck:
  2199. profileInfo->DisableLoopCountBasedBoundCheckHoist(true);
  2200. executeFunction->SetDontRethunkAfterBailout();
  2201. rejitReason = RejitReason::LoopCountBasedBoundCheckHoistDisabled;
  2202. break;
  2203. case IR::BailOutOnInlineFunction:
  2204. case IR::BailOutOnPolymorphicInlineFunction:
  2205. case IR::BailOutOnFailedPolymorphicInlineTypeCheck:
  2206. rejitReason = RejitReason::InlineeChanged;
  2207. break;
  2208. case IR::BailOutOnNoProfile:
  2209. rejitReason = RejitReason::NoProfile;
  2210. executeFunction->ResetBailOnMisingProfileCount();
  2211. break;
  2212. case IR::BailOutCheckThis:
  2213. profileInfo->DisableCheckThis();
  2214. executeFunction->SetDontRethunkAfterBailout();
  2215. rejitReason = RejitReason::CheckThisDisabled;
  2216. break;
  2217. case IR::BailOutFailedTypeCheck:
  2218. // An inline cache must have gone from monomorphic to polymorphic.
  2219. // This is already noted in the profile data, so optimization of the given ld/st will
  2220. // be inhibited on re-jit.
  2221. // Consider disabling the optimization across the function after n failed type checks.
  2222. // Disable ObjTypeSpec in a large loop body after the first rejit itself.
  2223. // Rejitting a large loop body takes more time and the fact that loop bodies are prioritized ahead of functions to be jitted only augments the problem.
  2224. if(executeFunction->GetByteCodeInLoopCount() > (uint)CONFIG_FLAG(LoopBodySizeThresholdToDisableOpts))
  2225. {
  2226. profileInfo->DisableObjTypeSpecInJitLoopBody();
  2227. if(PHASE_TRACE1(Js::DisabledObjTypeSpecPhase))
  2228. {
  2229. Output::Print(_u("Disabled obj type spec in jit loop body for loop %d in %s (%d)\n"),
  2230. executeFunction->GetLoopNumber(loopHeader), executeFunction->GetDisplayName(), executeFunction->GetFunctionNumber());
  2231. Output::Flush();
  2232. }
  2233. }
  2234. rejitReason = RejitReason::FailedTypeCheck;
  2235. break;
  2236. case IR::BailOutFailedFixedFieldTypeCheck:
  2237. // An inline cache must have gone from monomorphic to polymorphic or some fixed field
  2238. // became non-fixed. Either one is already noted in the profile data and type system,
  2239. // so optimization of the given instruction will be inhibited on re-jit.
  2240. // Consider disabling the optimization across the function after n failed type checks.
  2241. rejitReason = RejitReason::FailedFixedFieldTypeCheck;
  2242. break;
  2243. case IR::BailOutFailedEquivalentTypeCheck:
  2244. case IR::BailOutFailedEquivalentFixedFieldTypeCheck:
  2245. rejitReason = bailOutKind == IR::BailOutFailedEquivalentTypeCheck ?
  2246. RejitReason::FailedEquivalentTypeCheck : RejitReason::FailedEquivalentFixedFieldTypeCheck;
  2247. break;
  2248. case IR::BailOutFailedCtorGuardCheck:
  2249. // (ObjTypeSpec): Consider scheduling re-JIT right after the first bailout. We will never successfully execute the
  2250. // function from which we just bailed out, unless we take a different code path through it.
  2251. // A constructor cache guard may be invalidated for one of two reasons:
  2252. // a) the constructor's prototype property has changed, or
  2253. // b) one of the properties protected by the guard (this constructor cache served as) has changed in some way (e.g. became
  2254. // read-only).
  2255. // In the former case, the cache itself will be marked as polymorphic and on re-JIT we won't do the optimization.
  2256. // In the latter case, the inline cache for the offending property will be cleared and on re-JIT the guard will not be enlisted
  2257. // to protect that property operation.
  2258. rejitReason = RejitReason::CtorGuardInvalidated;
  2259. break;
  2260. case IR::BailOutOnFloor:
  2261. {
  2262. profileInfo->DisableFloorInlining();
  2263. rejitReason = RejitReason::FloorInliningDisabled;
  2264. break;
  2265. }
  2266. case IR::BailOutFailedFixedFieldCheck:
  2267. rejitReason = RejitReason::FailedFixedFieldCheck;
  2268. break;
  2269. case IR::BailOutOnTaggedValue:
  2270. profileInfo->DisableTagCheck();
  2271. executeFunction->SetDontRethunkAfterBailout();
  2272. rejitReason = RejitReason::FailedTagCheck;
  2273. break;
  2274. case IR::BailOutOnPowIntIntOverflow:
  2275. profileInfo->DisablePowIntIntTypeSpec();
  2276. executeFunction->SetDontRethunkAfterBailout();
  2277. rejitReason = RejitReason::PowIntIntTypeSpecDisabled;
  2278. break;
  2279. }
  2280. if(PHASE_FORCE(Js::ReJITPhase, executeFunction) && rejitReason == RejitReason::None)
  2281. {
  2282. rejitReason = RejitReason::Forced;
  2283. }
  2284. }
  2285. if (PHASE_FORCE(Js::ReJITPhase, executeFunction) && rejitReason == RejitReason::None)
  2286. {
  2287. rejitReason = RejitReason::Forced;
  2288. }
  2289. REJIT_KIND_TESTTRACE(bailOutKind, _u("Bailout from loop: function: %s, loopNumber: %d, bailOutKindName: (%S), reJitReason: %S\r\n"),
  2290. function->GetFunctionBody()->GetDisplayName(), executeFunction->GetLoopNumber(loopHeader),
  2291. ::GetBailOutKindName(bailOutKind), GetRejitReasonName(rejitReason));
  2292. JS_ETW(EventWriteJSCRIPT_BACKEND_BAILOUT_FROM_LOOP_BODY(
  2293. function->GetFunctionBody()->GetLocalFunctionId(), function->GetFunctionBody()->GetSourceContextId(),
  2294. function->GetFunctionBody()->GetDisplayName(), executeFunction->GetLoopNumber(loopHeader),
  2295. bailOutKind, GetRejitReasonName(rejitReason)));
  2296. #ifdef REJIT_STATS
  2297. executeFunction->GetScriptContext()->LogBailout(executeFunction, bailOutKind);
  2298. #endif
  2299. if (rejitReason != RejitReason::None)
  2300. {
  2301. #ifdef REJIT_STATS
  2302. executeFunction->GetScriptContext()->LogRejit(executeFunction, rejitReason);
  2303. #endif
  2304. // Single bailout triggers re-JIT of loop body. the actual codegen scheduling of the new
  2305. // loop body happens in the interpreter
  2306. loopHeader->interpretCount = executeFunction->GetLoopInterpretCount(loopHeader) - 2;
  2307. loopHeader->CreateEntryPoint();
  2308. loopHeader->IncRejitCount();
  2309. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2310. if(PHASE_TRACE(Js::ReJITPhase, executeFunction))
  2311. {
  2312. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2313. Output::Print(
  2314. _u("Rejit(loop): function: %s (%s) loop: %u bailOutCount: %hu reason: %S"),
  2315. executeFunction->GetDisplayName(),
  2316. executeFunction->GetDebugNumberSet(debugStringBuffer),
  2317. executeFunction->GetLoopNumber(loopHeader),
  2318. bailOutRecord->bailOutCount,
  2319. GetRejitReasonName(rejitReason));
  2320. if(bailOutKind != IR::BailOutInvalid)
  2321. {
  2322. Output::Print(_u(" (%S)"), ::GetBailOutKindName(bailOutKind));
  2323. }
  2324. Output::Print(_u("\n"));
  2325. Output::Flush();
  2326. }
  2327. #endif
  2328. }
  2329. }
  2330. void BailOutRecord::CheckPreemptiveRejit(Js::FunctionBody* executeFunction, IR::BailOutKind bailOutKind, BailOutRecord* bailoutRecord, uint8& callsOrIterationsCount, int loopNumber)
  2331. {
  2332. if (bailOutKind == IR::BailOutOnNoProfile && executeFunction->IncrementBailOnMisingProfileCount() > CONFIG_FLAG(BailOnNoProfileLimit))
  2333. {
  2334. // A rejit here should improve code quality, so lets avoid too many unnecessary bailouts.
  2335. executeFunction->ResetBailOnMisingProfileCount();
  2336. bailoutRecord->bailOutCount = 0;
  2337. callsOrIterationsCount = 0;
  2338. }
  2339. else if (bailoutRecord->bailOutCount > CONFIG_FLAG(RejitMaxBailOutCount))
  2340. {
  2341. switch (bailOutKind)
  2342. {
  2343. case IR::BailOutOnPolymorphicInlineFunction:
  2344. case IR::BailOutOnFailedPolymorphicInlineTypeCheck:
  2345. case IR::BailOutFailedInlineTypeCheck:
  2346. case IR::BailOutOnInlineFunction:
  2347. case IR::BailOutFailedTypeCheck:
  2348. case IR::BailOutFailedFixedFieldTypeCheck:
  2349. case IR::BailOutFailedCtorGuardCheck:
  2350. case IR::BailOutFailedFixedFieldCheck:
  2351. case IR::BailOutFailedEquivalentTypeCheck:
  2352. case IR::BailOutFailedEquivalentFixedFieldTypeCheck:
  2353. {
  2354. // If we consistently see RejitMaxBailOutCount bailouts for these kinds, then likely we have stale profile data and it is beneficial to rejit.
  2355. // Note you need to include only bailout kinds which don't disable the entire optimizations.
  2356. if (loopNumber == -1)
  2357. {
  2358. REJIT_KIND_TESTTRACE(bailOutKind, _u("Force rejit as RejitMaxBailoOutCount reached for a bailout record: function: %s, bailOutKindName: (%S), bailOutCount: %d, callCount: %d RejitMaxBailoutCount: %d\r\n"),
  2359. executeFunction->GetDisplayName(), ::GetBailOutKindName(bailOutKind), bailoutRecord->bailOutCount, callsOrIterationsCount, CONFIG_FLAG(RejitMaxBailOutCount));
  2360. }
  2361. else
  2362. {
  2363. REJIT_KIND_TESTTRACE(bailOutKind, _u("Force rejit as RejitMaxBailoOutCount reached for a bailout record: function: %s, loopNumber: %d, bailOutKindName: (%S), bailOutCount: %d, callCount: %d RejitMaxBailoutCount: %d\r\n"),
  2364. executeFunction->GetDisplayName(), loopNumber, ::GetBailOutKindName(bailOutKind), bailoutRecord->bailOutCount, callsOrIterationsCount, CONFIG_FLAG(RejitMaxBailOutCount));
  2365. }
  2366. bailoutRecord->bailOutCount = 0;
  2367. callsOrIterationsCount = 0;
  2368. break;
  2369. }
  2370. default: break;
  2371. }
  2372. }
  2373. }
  2374. Js::Var BailOutRecord::BailOutForElidedYield(void * framePointer)
  2375. {
  2376. JIT_HELPER_REENTRANT_HEADER(NoSaveRegistersBailOutForElidedYield);
  2377. Js::JavascriptCallStackLayout * const layout = Js::JavascriptCallStackLayout::FromFramePointer(framePointer);
  2378. Js::ScriptFunction ** functionRef = (Js::ScriptFunction **)&layout->functionObject;
  2379. Js::ScriptFunction * function = *functionRef;
  2380. Js::FunctionBody * executeFunction = function->GetFunctionBody();
  2381. #ifdef ENABLE_SCRIPT_DEBUGGING
  2382. bool isInDebugMode = executeFunction->IsInDebugMode();
  2383. #endif
  2384. Js::JavascriptGenerator* generator = static_cast<Js::JavascriptGenerator*>(layout->args[0]);
  2385. Js::InterpreterStackFrame* frame = generator->GetFrame();
  2386. ThreadContext *threadContext = frame->GetScriptContext()->GetThreadContext();
  2387. Js::ResumeYieldData* resumeYieldData = static_cast<Js::ResumeYieldData*>(layout->args[1]);
  2388. frame->SetNonVarReg(executeFunction->GetYieldRegister(), resumeYieldData);
  2389. // The debugger relies on comparing stack addresses of frames to decide when a step_out is complete so
  2390. // give the InterpreterStackFrame a legit enough stack address to make this comparison work.
  2391. frame->m_stackAddress = reinterpret_cast<DWORD_PTR>(&generator);
  2392. executeFunction->BeginExecution();
  2393. Js::Var aReturn = nullptr;
  2394. {
  2395. // Following _AddressOfReturnAddress <= real address of "returnAddress". Suffices for RemoteStackWalker to test partially initialized interpreter frame.
  2396. Js::InterpreterStackFrame::PushPopFrameHelper pushPopFrameHelper(frame, _ReturnAddress(), _AddressOfReturnAddress());
  2397. #ifdef ENABLE_SCRIPT_DEBUGGING
  2398. aReturn = isInDebugMode ? frame->DebugProcess() : frame->Process();
  2399. #else
  2400. aReturn = frame->Process();
  2401. #endif
  2402. // Note: in debug mode we always have to bailout to debug thunk,
  2403. // as normal interpreter thunk expects byte code compiled w/o debugging.
  2404. }
  2405. executeFunction->EndExecution();
  2406. if (executeFunction->HasDynamicProfileInfo())
  2407. {
  2408. Js::DynamicProfileInfo *dynamicProfileInfo = executeFunction->GetAnyDynamicProfileInfo();
  2409. dynamicProfileInfo->RecordImplicitCallFlags(threadContext->GetImplicitCallFlags());
  2410. }
  2411. return aReturn;
  2412. JIT_HELPER_END(NoSaveRegistersBailOutForElidedYield);
  2413. }
  2414. BranchBailOutRecord::BranchBailOutRecord(uint32 trueBailOutOffset, uint32 falseBailOutOffset, Js::RegSlot resultByteCodeReg, IR::BailOutKind kind, Func * bailOutFunc)
  2415. : BailOutRecord(trueBailOutOffset, (uint)-1, kind, bailOutFunc), falseBailOutOffset(falseBailOutOffset)
  2416. {
  2417. branchValueRegSlot = resultByteCodeReg;
  2418. type = BailoutRecordType::Branch;
  2419. };
  2420. Js::Var BranchBailOutRecord::BailOut(BranchBailOutRecord const * bailOutRecord, BOOL cond)
  2421. {
  2422. Assert(bailOutRecord);
  2423. void * argoutRestoreAddr = nullptr;
  2424. #ifdef _M_IX86
  2425. void * addressOfRetAddress = _AddressOfReturnAddress();
  2426. if (bailOutRecord->ehBailoutData && (bailOutRecord->ehBailoutData->catchOffset != 0 || bailOutRecord->ehBailoutData->finallyOffset != 0 || bailOutRecord->ehBailoutData->ht == Js::HandlerType::HT_Finally))
  2427. {
  2428. argoutRestoreAddr = (void *)((char*)addressOfRetAddress + ((2 + 1) * MachPtr)); // Account for the parameters and return address of this function
  2429. }
  2430. #endif
  2431. Js::JavascriptCallStackLayout *const layout = bailOutRecord->GetStackLayout();
  2432. Js::ScriptFunction * function = (Js::ScriptFunction *)layout->functionObject;
  2433. if (bailOutRecord->bailOutKind == IR::BailOutOnImplicitCalls)
  2434. {
  2435. function->GetScriptContext()->GetThreadContext()->CheckAndResetImplicitCallAccessorFlag();
  2436. }
  2437. Js::ImplicitCallFlags savedImplicitCallFlags = function->GetScriptContext()->GetThreadContext()->GetImplicitCallFlags();
  2438. if(bailOutRecord->globalBailOutRecordTable->isLoopBody)
  2439. {
  2440. if (bailOutRecord->globalBailOutRecordTable->isInlinedFunction)
  2441. {
  2442. return reinterpret_cast<Js::Var>(BailOutFromLoopBodyInlined(layout, bailOutRecord, cond, _ReturnAddress()));
  2443. }
  2444. return reinterpret_cast<Js::Var>(BailOutFromLoopBody(layout, bailOutRecord, cond));
  2445. }
  2446. if(bailOutRecord->globalBailOutRecordTable->isInlinedFunction)
  2447. {
  2448. return BailOutInlined(layout, bailOutRecord, cond, _ReturnAddress(), savedImplicitCallFlags);
  2449. }
  2450. return BailOutFromFunction(layout, bailOutRecord, cond, _ReturnAddress(), argoutRestoreAddr, savedImplicitCallFlags);
  2451. }
  2452. Js::Var
  2453. BranchBailOutRecord::BailOutFromFunction(Js::JavascriptCallStackLayout * layout, BranchBailOutRecord const * bailOutRecord, BOOL cond, void * returnAddress, void * argoutRestoreAddress, Js::ImplicitCallFlags savedImplicitCallFlags)
  2454. {
  2455. Assert(bailOutRecord->parent == nullptr);
  2456. uint32 bailOutOffset = cond? bailOutRecord->bailOutOffset : bailOutRecord->falseBailOutOffset;
  2457. Js::Var branchValue = nullptr;
  2458. if (bailOutRecord->branchValueRegSlot != Js::Constants::NoRegister)
  2459. {
  2460. Js::ScriptContext *scriptContext = layout->functionObject->GetScriptContext();
  2461. branchValue = (cond ? scriptContext->GetLibrary()->GetTrue() : scriptContext->GetLibrary()->GetFalse());
  2462. }
  2463. return __super::BailOutCommon(layout, bailOutRecord, bailOutOffset, returnAddress, bailOutRecord->bailOutKind, savedImplicitCallFlags, branchValue, nullptr, argoutRestoreAddress);
  2464. }
  2465. uint32
  2466. BranchBailOutRecord::BailOutFromLoopBody(Js::JavascriptCallStackLayout * layout, BranchBailOutRecord const * bailOutRecord, BOOL cond)
  2467. {
  2468. Assert(bailOutRecord->parent == nullptr);
  2469. uint32 bailOutOffset = cond? bailOutRecord->bailOutOffset : bailOutRecord->falseBailOutOffset;
  2470. Js::Var branchValue = nullptr;
  2471. if (bailOutRecord->branchValueRegSlot != Js::Constants::NoRegister)
  2472. {
  2473. Js::ScriptContext *scriptContext = layout->functionObject->GetScriptContext();
  2474. branchValue = (cond ? scriptContext->GetLibrary()->GetTrue() : scriptContext->GetLibrary()->GetFalse());
  2475. }
  2476. return __super::BailOutFromLoopBodyCommon(layout, bailOutRecord, bailOutOffset, bailOutRecord->bailOutKind, branchValue);
  2477. }
  2478. Js::Var
  2479. BranchBailOutRecord::BailOutInlined(Js::JavascriptCallStackLayout * layout, BranchBailOutRecord const * bailOutRecord, BOOL cond, void * returnAddress, Js::ImplicitCallFlags savedImplicitCallFlags)
  2480. {
  2481. Assert(bailOutRecord->parent != nullptr);
  2482. uint32 bailOutOffset = cond? bailOutRecord->bailOutOffset : bailOutRecord->falseBailOutOffset;
  2483. Js::Var branchValue = nullptr;
  2484. if (bailOutRecord->branchValueRegSlot != Js::Constants::NoRegister)
  2485. {
  2486. Js::ScriptContext *scriptContext = layout->functionObject->GetScriptContext();
  2487. branchValue = (cond ? scriptContext->GetLibrary()->GetTrue() : scriptContext->GetLibrary()->GetFalse());
  2488. }
  2489. return __super::BailOutInlinedCommon(layout, bailOutRecord, bailOutOffset, returnAddress, bailOutRecord->bailOutKind, savedImplicitCallFlags, branchValue);
  2490. }
  2491. uint32
  2492. BranchBailOutRecord::BailOutFromLoopBodyInlined(Js::JavascriptCallStackLayout * layout, BranchBailOutRecord const * bailOutRecord, BOOL cond, void * returnAddress)
  2493. {
  2494. Assert(bailOutRecord->parent != nullptr);
  2495. uint32 bailOutOffset = cond? bailOutRecord->bailOutOffset : bailOutRecord->falseBailOutOffset;
  2496. Js::Var branchValue = nullptr;
  2497. if (bailOutRecord->branchValueRegSlot != Js::Constants::NoRegister)
  2498. {
  2499. Js::ScriptContext *scriptContext = layout->functionObject->GetScriptContext();
  2500. branchValue = (cond ? scriptContext->GetLibrary()->GetTrue() : scriptContext->GetLibrary()->GetFalse());
  2501. }
  2502. return __super::BailOutFromLoopBodyInlinedCommon(layout, bailOutRecord, bailOutOffset, returnAddress, bailOutRecord->bailOutKind, branchValue);
  2503. }
  2504. SharedBailOutRecord::SharedBailOutRecord(uint32 bailOutOffset, uint bailOutCacheIndex, IR::BailOutKind kind, Func *bailOutFunc)
  2505. : BailOutRecord(bailOutOffset, bailOutCacheIndex, kind, bailOutFunc)
  2506. {
  2507. this->functionBody = nullptr;
  2508. this->type = BailoutRecordType::Shared;
  2509. }
  2510. void LazyBailOutRecord::SetBailOutKind()
  2511. {
  2512. this->bailoutRecord->SetBailOutKind(IR::BailOutKind::LazyBailOut);
  2513. }
  2514. #if DBG
  2515. void LazyBailOutRecord::Dump(Js::FunctionBody* functionBody)
  2516. {
  2517. OUTPUT_PRINT(functionBody);
  2518. Output::Print(_u("Bytecode Offset: #%04x opcode: %s"), this->bailoutRecord->GetBailOutOffset(), Js::OpCodeUtil::GetOpCodeName(this->bailoutRecord->GetBailOutOpCode()));
  2519. }
  2520. #endif
  2521. void GlobalBailOutRecordDataTable::Finalize(NativeCodeData::Allocator *allocator, JitArenaAllocator *tempAlloc)
  2522. {
  2523. GlobalBailOutRecordDataRow *newRows = NativeCodeDataNewArrayZNoFixup(allocator, GlobalBailOutRecordDataRow, length);
  2524. memcpy(newRows, globalBailOutRecordDataRows, sizeof(GlobalBailOutRecordDataRow) * length);
  2525. JitAdeleteArray(tempAlloc, length, globalBailOutRecordDataRows);
  2526. globalBailOutRecordDataRows = newRows;
  2527. size = length;
  2528. #if DBG
  2529. if (length > 0)
  2530. {
  2531. uint32 currStart = globalBailOutRecordDataRows[0].start;
  2532. for (uint32 i = 1; i < length; i++)
  2533. {
  2534. AssertMsg(currStart <= globalBailOutRecordDataRows[i].start,
  2535. "Rows in the table must be in order by start ID");
  2536. currStart = globalBailOutRecordDataRows[i].start;
  2537. }
  2538. }
  2539. #endif
  2540. }
  2541. void GlobalBailOutRecordDataTable::AddOrUpdateRow(JitArenaAllocator *allocator, uint32 bailOutRecordId, uint32 regSlot, bool isFloat, bool isInt, int32 offset, uint *lastUpdatedRowIndex)
  2542. {
  2543. Assert(offset != 0);
  2544. const int INITIAL_TABLE_SIZE = 64;
  2545. if (size == 0)
  2546. {
  2547. Assert(length == 0);
  2548. size = INITIAL_TABLE_SIZE;
  2549. globalBailOutRecordDataRows = JitAnewArrayZ(allocator, GlobalBailOutRecordDataRow, size);
  2550. }
  2551. Assert(lastUpdatedRowIndex != nullptr);
  2552. if ((*lastUpdatedRowIndex) != -1)
  2553. {
  2554. GlobalBailOutRecordDataRow *rowToUpdate = &globalBailOutRecordDataRows[(*lastUpdatedRowIndex)];
  2555. if(rowToUpdate->offset == offset &&
  2556. rowToUpdate->isInt == (unsigned)isInt &&
  2557. rowToUpdate->isFloat == (unsigned)isFloat &&
  2558. rowToUpdate->end + 1 == bailOutRecordId)
  2559. {
  2560. Assert(rowToUpdate->regSlot == regSlot);
  2561. rowToUpdate->end = bailOutRecordId;
  2562. return;
  2563. }
  2564. }
  2565. if (length == size)
  2566. {
  2567. size = length << 1;
  2568. globalBailOutRecordDataRows = (GlobalBailOutRecordDataRow *)allocator->Realloc(globalBailOutRecordDataRows, length * sizeof(GlobalBailOutRecordDataRow), size * sizeof(GlobalBailOutRecordDataRow));
  2569. }
  2570. GlobalBailOutRecordDataRow *rowToInsert = &globalBailOutRecordDataRows[length];
  2571. rowToInsert->start = bailOutRecordId;
  2572. rowToInsert->end = bailOutRecordId;
  2573. rowToInsert->offset = offset;
  2574. rowToInsert->isFloat = isFloat;
  2575. rowToInsert->isInt = isInt;
  2576. rowToInsert->regSlot = regSlot;
  2577. *lastUpdatedRowIndex = length++;
  2578. }