Func.cpp 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "Backend.h"
  6. #include "Base/EtwTrace.h"
  7. #include "Base/ScriptContextProfiler.h"
  8. #ifdef VTUNE_PROFILING
  9. #include "Base/VTuneChakraProfile.h"
  10. #endif
  11. #include "Library/ForInObjectEnumerator.h"
  12. Func::Func(JitArenaAllocator *alloc, JITTimeWorkItem * workItem,
  13. ThreadContextInfo * threadContextInfo,
  14. ScriptContextInfo * scriptContextInfo,
  15. JITOutputIDL * outputData,
  16. Js::EntryPointInfo* epInfo,
  17. const FunctionJITRuntimeInfo *const runtimeInfo,
  18. JITTimePolymorphicInlineCacheInfo * const polymorphicInlineCacheInfo, void * const codeGenAllocators,
  19. #if !FLOATVAR
  20. CodeGenNumberAllocator * numberAllocator,
  21. #endif
  22. Js::ScriptContextProfiler *const codeGenProfiler, const bool isBackgroundJIT, Func * parentFunc,
  23. uint postCallByteCodeOffset, Js::RegSlot returnValueRegSlot, const bool isInlinedConstructor,
  24. Js::ProfileId callSiteIdInParentFunc, bool isGetterSetter) :
  25. m_alloc(alloc),
  26. m_workItem(workItem),
  27. m_output(outputData),
  28. m_entryPointInfo(epInfo),
  29. m_threadContextInfo(threadContextInfo),
  30. m_scriptContextInfo(scriptContextInfo),
  31. m_runtimeInfo(runtimeInfo),
  32. m_polymorphicInlineCacheInfo(polymorphicInlineCacheInfo),
  33. m_codeGenAllocators(codeGenAllocators),
  34. m_inlineeId(0),
  35. pinnedTypeRefs(nullptr),
  36. singleTypeGuards(nullptr),
  37. equivalentTypeGuards(nullptr),
  38. propertyGuardsByPropertyId(nullptr),
  39. ctorCachesByPropertyId(nullptr),
  40. callSiteToArgumentsOffsetFixupMap(nullptr),
  41. indexedPropertyGuardCount(0),
  42. propertiesWrittenTo(nullptr),
  43. lazyBailoutProperties(alloc),
  44. anyPropertyMayBeWrittenTo(false),
  45. #ifdef PROFILE_EXEC
  46. m_codeGenProfiler(codeGenProfiler),
  47. #endif
  48. m_isBackgroundJIT(isBackgroundJIT),
  49. m_cloner(nullptr),
  50. m_cloneMap(nullptr),
  51. m_loopParamSym(nullptr),
  52. m_funcObjSym(nullptr),
  53. m_localClosureSym(nullptr),
  54. m_paramClosureSym(nullptr),
  55. m_localFrameDisplaySym(nullptr),
  56. m_bailoutReturnValueSym(nullptr),
  57. m_hasBailedOutSym(nullptr),
  58. m_inlineeFrameStartSym(nullptr),
  59. m_regsUsed(0),
  60. m_fg(nullptr),
  61. m_labelCount(0),
  62. m_argSlotsForFunctionsCalled(0),
  63. m_hasCalls(false),
  64. m_hasInlineArgsOpt(false),
  65. m_canDoInlineArgsOpt(true),
  66. m_doFastPaths(false),
  67. hasBailout(false),
  68. firstIRTemp(0),
  69. hasBailoutInEHRegion(false),
  70. hasInstrNumber(false),
  71. maintainByteCodeOffset(true),
  72. frameSize(0),
  73. parentFunc(parentFunc),
  74. argObjSyms(nullptr),
  75. m_nonTempLocalVars(nullptr),
  76. hasAnyStackNestedFunc(false),
  77. hasMarkTempObjects(false),
  78. postCallByteCodeOffset(postCallByteCodeOffset),
  79. maxInlineeArgOutSize(0),
  80. returnValueRegSlot(returnValueRegSlot),
  81. firstActualStackOffset(-1),
  82. m_localVarSlotsOffset(Js::Constants::InvalidOffset),
  83. m_hasLocalVarChangedOffset(Js::Constants::InvalidOffset),
  84. actualCount((Js::ArgSlot) - 1),
  85. tryCatchNestingLevel(0),
  86. m_localStackHeight(0),
  87. tempSymDouble(nullptr),
  88. tempSymBool(nullptr),
  89. hasInlinee(false),
  90. thisOrParentInlinerHasArguments(false),
  91. hasStackArgs(false),
  92. hasImplicitParamLoad(false),
  93. hasThrow(false),
  94. hasNonSimpleParams(false),
  95. hasUnoptimizedArgumentsAccess(false),
  96. applyTargetInliningRemovedArgumentsAccess(false),
  97. hasImplicitCalls(false),
  98. hasTempObjectProducingInstr(false),
  99. isInlinedConstructor(isInlinedConstructor),
  100. #if !FLOATVAR
  101. numberAllocator(numberAllocator),
  102. #endif
  103. loopCount(0),
  104. callSiteIdInParentFunc(callSiteIdInParentFunc),
  105. isGetterSetter(isGetterSetter),
  106. frameInfo(nullptr),
  107. isTJLoopBody(false),
  108. m_nativeCodeDataSym(nullptr),
  109. isFlowGraphValid(false),
  110. #if DBG
  111. m_callSiteCount(0),
  112. #endif
  113. stackNestedFunc(false),
  114. stackClosure(false)
  115. #if defined(_M_ARM32_OR_ARM64)
  116. , m_ArgumentsOffset(0)
  117. , m_epilogLabel(nullptr)
  118. #endif
  119. , m_funcStartLabel(nullptr)
  120. , m_funcEndLabel(nullptr)
  121. #if DBG
  122. , hasCalledSetDoFastPaths(false)
  123. , allowRemoveBailOutArgInstr(false)
  124. , currentPhases(alloc)
  125. , isPostLower(false)
  126. , isPostRegAlloc(false)
  127. , isPostPeeps(false)
  128. , isPostLayout(false)
  129. , isPostFinalLower(false)
  130. , vtableMap(nullptr)
  131. #endif
  132. , m_yieldOffsetResumeLabelList(nullptr)
  133. , m_bailOutNoSaveLabel(nullptr)
  134. , constantAddressRegOpnd(alloc)
  135. , lastConstantAddressRegLoadInstr(nullptr)
  136. , m_totalJumpTableSizeInBytesForSwitchStatements(0)
  137. , slotArrayCheckTable(nullptr)
  138. , frameDisplayCheckTable(nullptr)
  139. , stackArgWithFormalsTracker(nullptr)
  140. , m_forInLoopBaseDepth(0)
  141. , m_forInEnumeratorArrayOffset(-1)
  142. , argInsCount(0)
  143. , m_globalObjTypeSpecFldInfoArray(nullptr)
  144. #if LOWER_SPLIT_INT64
  145. , m_int64SymPairMap(nullptr)
  146. #endif
  147. #ifdef RECYCLER_WRITE_BARRIER_JIT
  148. , m_lowerer(nullptr)
  149. #endif
  150. {
  151. Assert(this->IsInlined() == !!runtimeInfo);
  152. AssertOrFailFast(!HasProfileInfo() || GetReadOnlyProfileInfo()->GetLoopCount() == GetJITFunctionBody()->GetLoopCount());
  153. Js::RegSlot tmpResult;
  154. AssertOrFailFast(!UInt32Math::Add(GetJITFunctionBody()->GetConstCount(), GetJITFunctionBody()->GetVarCount(), &tmpResult));
  155. AssertOrFailFast(GetJITFunctionBody()->IsAsmJsMode() || GetJITFunctionBody()->GetFirstTmpReg() <= GetJITFunctionBody()->GetLocalsCount());
  156. AssertOrFailFast(!IsLoopBody() || m_workItem->GetLoopNumber() < GetJITFunctionBody()->GetLoopCount());
  157. AssertOrFailFast(CONFIG_FLAG(Prejit) || CONFIG_ISENABLED(Js::ForceNativeFlag) || GetJITFunctionBody()->GetByteCodeLength() < (uint)CONFIG_FLAG(MaxJITFunctionBytecodeByteLength));
  158. GetJITFunctionBody()->EnsureConsistentConstCount();
  159. if (this->IsTopFunc())
  160. {
  161. outputData->hasJittedStackClosure = false;
  162. outputData->localVarSlotsOffset = m_localVarSlotsOffset;
  163. outputData->localVarChangedOffset = m_hasLocalVarChangedOffset;
  164. }
  165. if (this->IsInlined())
  166. {
  167. m_inlineeId = ++(GetTopFunc()->m_inlineeId);
  168. }
  169. bool doStackNestedFunc = GetJITFunctionBody()->DoStackNestedFunc();
  170. bool doStackClosure = GetJITFunctionBody()->DoStackClosure() && !PHASE_OFF(Js::FrameDisplayFastPathPhase, this) && !PHASE_OFF(Js::StackClosurePhase, this);
  171. Assert(!doStackClosure || doStackNestedFunc);
  172. this->stackClosure = doStackClosure && this->IsTopFunc();
  173. if (this->stackClosure)
  174. {
  175. // TODO: calculate on runtime side?
  176. m_output.SetHasJITStackClosure();
  177. }
  178. if (m_workItem->Type() == JsFunctionType &&
  179. GetJITFunctionBody()->DoBackendArgumentsOptimization() &&
  180. !GetJITFunctionBody()->HasTry())
  181. {
  182. // doBackendArgumentsOptimization bit is set when there is no eval inside a function
  183. // as determined by the bytecode generator.
  184. SetHasStackArgs(true);
  185. }
  186. if (doStackNestedFunc && GetJITFunctionBody()->GetNestedCount() != 0 &&
  187. (this->IsTopFunc() || this->GetTopFunc()->m_workItem->Type() != JsLoopBodyWorkItemType)) // make sure none of the functions inlined in a jitted loop body allocate nested functions on the stack
  188. {
  189. Assert(!(this->IsJitInDebugMode() && !GetJITFunctionBody()->IsLibraryCode()));
  190. stackNestedFunc = true;
  191. this->GetTopFunc()->hasAnyStackNestedFunc = true;
  192. }
  193. if (GetJITFunctionBody()->HasOrParentHasArguments() || (parentFunc && parentFunc->thisOrParentInlinerHasArguments))
  194. {
  195. thisOrParentInlinerHasArguments = true;
  196. }
  197. if (parentFunc == nullptr)
  198. {
  199. inlineDepth = 0;
  200. m_symTable = JitAnew(alloc, SymTable);
  201. m_symTable->Init(this);
  202. m_symTable->SetStartingID(static_cast<SymID>(workItem->GetJITFunctionBody()->GetLocalsCount() + 1));
  203. Assert(Js::Constants::NoByteCodeOffset == postCallByteCodeOffset);
  204. Assert(Js::Constants::NoRegister == returnValueRegSlot);
  205. #if defined(_M_IX86) || defined(_M_X64)
  206. if (HasArgumentSlot())
  207. {
  208. // Pre-allocate the single argument slot we'll reserve for the arguments object.
  209. // For ARM, the argument slot is not part of the local but part of the register saves
  210. m_localStackHeight = MachArgsSlotOffset;
  211. }
  212. #endif
  213. }
  214. else
  215. {
  216. inlineDepth = parentFunc->inlineDepth + 1;
  217. Assert(Js::Constants::NoByteCodeOffset != postCallByteCodeOffset);
  218. }
  219. this->constructorCacheCount = 0;
  220. this->constructorCaches = AnewArrayZ(this->m_alloc, JITTimeConstructorCache*, GetJITFunctionBody()->GetProfiledCallSiteCount());
  221. #if DBG_DUMP
  222. m_codeSize = -1;
  223. #endif
  224. #if defined(_M_X64)
  225. m_spillSize = -1;
  226. m_argsSize = -1;
  227. m_savedRegSize = -1;
  228. #endif
  229. if (this->IsJitInDebugMode())
  230. {
  231. m_nonTempLocalVars = Anew(this->m_alloc, BVSparse<JitArenaAllocator>, this->m_alloc);
  232. }
  233. if (GetJITFunctionBody()->IsCoroutine())
  234. {
  235. m_yieldOffsetResumeLabelList = YieldOffsetResumeLabelList::New(this->m_alloc);
  236. }
  237. if (this->IsTopFunc())
  238. {
  239. m_globalObjTypeSpecFldInfoArray = JitAnewArrayZ(this->m_alloc, ObjTypeSpecFldInfo*, GetWorkItem()->GetJITTimeInfo()->GetGlobalObjTypeSpecFldInfoCount());
  240. }
  241. for (uint i = 0; i < GetJITFunctionBody()->GetInlineCacheCount(); ++i)
  242. {
  243. ObjTypeSpecFldInfo * info = GetWorkItem()->GetJITTimeInfo()->GetObjTypeSpecFldInfo(i);
  244. if (info != nullptr)
  245. {
  246. Assert(info->GetObjTypeSpecFldId() < GetTopFunc()->GetWorkItem()->GetJITTimeInfo()->GetGlobalObjTypeSpecFldInfoCount());
  247. GetTopFunc()->m_globalObjTypeSpecFldInfoArray[info->GetObjTypeSpecFldId()] = info;
  248. }
  249. }
  250. canHoistConstantAddressLoad = !PHASE_OFF(Js::HoistConstAddrPhase, this);
  251. m_forInLoopMaxDepth = this->GetJITFunctionBody()->GetForInLoopDepth();
  252. }
  253. bool
  254. Func::IsLoopBodyInTry() const
  255. {
  256. return IsLoopBody() && m_workItem->GetLoopHeader()->isInTry;
  257. }
  258. /* static */
  259. void
  260. Func::Codegen(JitArenaAllocator *alloc, JITTimeWorkItem * workItem,
  261. ThreadContextInfo * threadContextInfo,
  262. ScriptContextInfo * scriptContextInfo,
  263. JITOutputIDL * outputData,
  264. Js::EntryPointInfo* epInfo, // for in-proc jit only
  265. const FunctionJITRuntimeInfo *const runtimeInfo,
  266. JITTimePolymorphicInlineCacheInfo * const polymorphicInlineCacheInfo, void * const codeGenAllocators,
  267. #if !FLOATVAR
  268. CodeGenNumberAllocator * numberAllocator,
  269. #endif
  270. Js::ScriptContextProfiler *const codeGenProfiler, const bool isBackgroundJIT)
  271. {
  272. bool rejit;
  273. do
  274. {
  275. Func func(alloc, workItem, threadContextInfo,
  276. scriptContextInfo, outputData, epInfo, runtimeInfo,
  277. polymorphicInlineCacheInfo, codeGenAllocators,
  278. #if !FLOATVAR
  279. numberAllocator,
  280. #endif
  281. codeGenProfiler, isBackgroundJIT);
  282. try
  283. {
  284. func.TryCodegen();
  285. rejit = false;
  286. }
  287. catch (Js::RejitException ex)
  288. {
  289. // The work item needs to be rejitted, likely due to some optimization that was too aggressive
  290. switch (ex.Reason())
  291. {
  292. case RejitReason::AggressiveIntTypeSpecDisabled:
  293. outputData->disableAggressiveIntTypeSpec = TRUE;
  294. break;
  295. case RejitReason::InlineApplyDisabled:
  296. workItem->GetJITFunctionBody()->DisableInlineApply();
  297. outputData->disableInlineApply = TRUE;
  298. break;
  299. case RejitReason::InlineSpreadDisabled:
  300. workItem->GetJITFunctionBody()->DisableInlineSpread();
  301. outputData->disableInlineSpread = TRUE;
  302. break;
  303. case RejitReason::DisableStackArgOpt:
  304. outputData->disableStackArgOpt = TRUE;
  305. break;
  306. case RejitReason::DisableSwitchOptExpectingInteger:
  307. case RejitReason::DisableSwitchOptExpectingString:
  308. outputData->disableSwitchOpt = TRUE;
  309. break;
  310. case RejitReason::ArrayCheckHoistDisabled:
  311. case RejitReason::ArrayAccessHelperCallEliminationDisabled:
  312. outputData->disableArrayCheckHoist = TRUE;
  313. break;
  314. case RejitReason::TrackIntOverflowDisabled:
  315. outputData->disableTrackCompoundedIntOverflow = TRUE;
  316. break;
  317. default:
  318. Assume(UNREACHED);
  319. }
  320. if (PHASE_TRACE(Js::ReJITPhase, &func))
  321. {
  322. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  323. Output::Print(
  324. _u("Rejit (compile-time): function: %s (%s) reason: %S\n"),
  325. workItem->GetJITFunctionBody()->GetDisplayName(),
  326. workItem->GetJITTimeInfo()->GetDebugNumberSet(debugStringBuffer),
  327. ex.ReasonName());
  328. }
  329. rejit = true;
  330. }
  331. // Either the entry point has a reference to the number now, or we failed to code gen and we
  332. // don't need to numbers, we can flush the completed page now.
  333. //
  334. // If the number allocator is NULL then we are shutting down the thread context and so too the
  335. // code generator. The number allocator must be freed before the recycler (and thus before the
  336. // code generator) so we can't and don't need to flush it.
  337. // TODO: OOP JIT, allocator cleanup
  338. } while (rejit);
  339. }
  340. ///----------------------------------------------------------------------------
  341. ///
  342. /// Func::TryCodegen
  343. ///
  344. /// Attempt to Codegen this function.
  345. ///
  346. ///----------------------------------------------------------------------------
  347. void
  348. Func::TryCodegen()
  349. {
  350. Assert(!IsJitInDebugMode() || !GetJITFunctionBody()->HasTry());
  351. BEGIN_CODEGEN_PHASE(this, Js::BackEndPhase);
  352. {
  353. // IRBuilder
  354. BEGIN_CODEGEN_PHASE(this, Js::IRBuilderPhase);
  355. #ifdef ASMJS_PLAT
  356. if (GetJITFunctionBody()->IsAsmJsMode())
  357. {
  358. IRBuilderAsmJs asmIrBuilder(this);
  359. asmIrBuilder.Build();
  360. }
  361. else
  362. #endif
  363. {
  364. IRBuilder irBuilder(this);
  365. irBuilder.Build();
  366. }
  367. END_CODEGEN_PHASE(this, Js::IRBuilderPhase);
  368. #ifdef IR_VIEWER
  369. IRtoJSObjectBuilder::DumpIRtoGlobalObject(this, Js::IRBuilderPhase);
  370. #endif /* IR_VIEWER */
  371. BEGIN_CODEGEN_PHASE(this, Js::InlinePhase);
  372. InliningHeuristics heuristics(GetWorkItem()->GetJITTimeInfo(), this->IsLoopBody());
  373. Inline inliner(this, heuristics);
  374. inliner.Optimize();
  375. END_CODEGEN_PHASE(this, Js::InlinePhase);
  376. ThrowIfScriptClosed();
  377. // FlowGraph
  378. {
  379. // Scope for FlowGraph arena
  380. NoRecoverMemoryJitArenaAllocator fgAlloc(_u("BE-FlowGraph"), m_alloc->GetPageAllocator(), Js::Throw::OutOfMemory);
  381. BEGIN_CODEGEN_PHASE(this, Js::FGBuildPhase);
  382. this->m_fg = FlowGraph::New(this, &fgAlloc);
  383. this->m_fg->Build();
  384. END_CODEGEN_PHASE(this, Js::FGBuildPhase);
  385. // Global Optimization and Type Specialization
  386. BEGIN_CODEGEN_PHASE(this, Js::GlobOptPhase);
  387. GlobOpt globOpt(this);
  388. globOpt.Optimize();
  389. END_CODEGEN_PHASE(this, Js::GlobOptPhase);
  390. // Delete flowGraph now
  391. this->m_fg->Destroy();
  392. this->m_fg = nullptr;
  393. }
  394. #ifdef IR_VIEWER
  395. IRtoJSObjectBuilder::DumpIRtoGlobalObject(this, Js::GlobOptPhase);
  396. #endif /* IR_VIEWER */
  397. ThrowIfScriptClosed();
  398. // Lowering
  399. Lowerer lowerer(this);
  400. BEGIN_CODEGEN_PHASE(this, Js::LowererPhase);
  401. lowerer.Lower();
  402. END_CODEGEN_PHASE(this, Js::LowererPhase);
  403. #ifdef IR_VIEWER
  404. IRtoJSObjectBuilder::DumpIRtoGlobalObject(this, Js::LowererPhase);
  405. #endif /* IR_VIEWER */
  406. // Encode constants
  407. Security security(this);
  408. BEGIN_CODEGEN_PHASE(this, Js::EncodeConstantsPhase)
  409. security.EncodeLargeConstants();
  410. END_CODEGEN_PHASE(this, Js::EncodeConstantsPhase);
  411. if (GetJITFunctionBody()->DoInterruptProbe())
  412. {
  413. BEGIN_CODEGEN_PHASE(this, Js::InterruptProbePhase)
  414. lowerer.DoInterruptProbes();
  415. END_CODEGEN_PHASE(this, Js::InterruptProbePhase)
  416. }
  417. // Register Allocation
  418. BEGIN_CODEGEN_PHASE(this, Js::RegAllocPhase);
  419. LinearScan linearScan(this);
  420. linearScan.RegAlloc();
  421. END_CODEGEN_PHASE(this, Js::RegAllocPhase);
  422. #ifdef IR_VIEWER
  423. IRtoJSObjectBuilder::DumpIRtoGlobalObject(this, Js::RegAllocPhase);
  424. #endif /* IR_VIEWER */
  425. ThrowIfScriptClosed();
  426. // Peephole optimizations
  427. BEGIN_CODEGEN_PHASE(this, Js::PeepsPhase);
  428. Peeps peeps(this);
  429. peeps.PeepFunc();
  430. END_CODEGEN_PHASE(this, Js::PeepsPhase);
  431. // Layout
  432. BEGIN_CODEGEN_PHASE(this, Js::LayoutPhase);
  433. SimpleLayout layout(this);
  434. layout.Layout();
  435. END_CODEGEN_PHASE(this, Js::LayoutPhase);
  436. if (this->HasTry() && this->hasBailoutInEHRegion)
  437. {
  438. BEGIN_CODEGEN_PHASE(this, Js::EHBailoutPatchUpPhase);
  439. lowerer.EHBailoutPatchUp();
  440. END_CODEGEN_PHASE(this, Js::EHBailoutPatchUpPhase);
  441. }
  442. // Insert NOPs (moving this before prolog/epilog for AMD64 and possibly ARM).
  443. BEGIN_CODEGEN_PHASE(this, Js::InsertNOPsPhase);
  444. security.InsertNOPs();
  445. END_CODEGEN_PHASE(this, Js::InsertNOPsPhase);
  446. // Prolog/Epilog
  447. BEGIN_CODEGEN_PHASE(this, Js::PrologEpilogPhase);
  448. if (GetJITFunctionBody()->IsAsmJsMode())
  449. {
  450. lowerer.LowerPrologEpilogAsmJs();
  451. }
  452. else
  453. {
  454. lowerer.LowerPrologEpilog();
  455. }
  456. END_CODEGEN_PHASE(this, Js::PrologEpilogPhase);
  457. BEGIN_CODEGEN_PHASE(this, Js::FinalLowerPhase);
  458. lowerer.FinalLower();
  459. END_CODEGEN_PHASE(this, Js::FinalLowerPhase);
  460. // Encoder
  461. BEGIN_CODEGEN_PHASE(this, Js::EncoderPhase);
  462. Encoder encoder(this);
  463. encoder.Encode();
  464. END_CODEGEN_PHASE_NO_DUMP(this, Js::EncoderPhase);
  465. #ifdef IR_VIEWER
  466. IRtoJSObjectBuilder::DumpIRtoGlobalObject(this, Js::EncoderPhase);
  467. #endif /* IR_VIEWER */
  468. }
  469. #if DBG_DUMP
  470. if (Js::Configuration::Global.flags.IsEnabled(Js::AsmDumpModeFlag))
  471. {
  472. FILE * oldFile = 0;
  473. FILE * asmFile = GetScriptContext()->GetNativeCodeGenerator()->asmFile;
  474. if (asmFile)
  475. {
  476. oldFile = Output::SetFile(asmFile);
  477. }
  478. this->Dump(IRDumpFlags_AsmDumpMode);
  479. Output::Flush();
  480. if (asmFile)
  481. {
  482. FILE *openedFile = Output::SetFile(oldFile);
  483. Assert(openedFile == asmFile);
  484. }
  485. }
  486. #endif
  487. if (this->IsOOPJIT())
  488. {
  489. BEGIN_CODEGEN_PHASE(this, Js::NativeCodeDataPhase);
  490. auto dataAllocator = this->GetNativeCodeDataAllocator();
  491. if (dataAllocator->allocCount > 0)
  492. {
  493. NativeCodeData::DataChunk *chunk = (NativeCodeData::DataChunk*)dataAllocator->chunkList;
  494. NativeCodeData::DataChunk *next1 = chunk;
  495. while (next1)
  496. {
  497. if (next1->fixupFunc)
  498. {
  499. next1->fixupFunc(next1->data, chunk);
  500. }
  501. #if DBG
  502. if (CONFIG_FLAG(OOPJITFixupValidate))
  503. {
  504. // Scan memory to see if there's missing pointer needs to be fixed up
  505. // This can hit false positive if some data field happens to have value
  506. // falls into the NativeCodeData memory range.
  507. NativeCodeData::DataChunk *next2 = chunk;
  508. while (next2)
  509. {
  510. for (unsigned int i = 0; i < next1->len / sizeof(void*); i++)
  511. {
  512. if (((void**)next1->data)[i] == (void*)next2->data)
  513. {
  514. NativeCodeData::VerifyExistFixupEntry((void*)next2->data, &((void**)next1->data)[i], next1->data);
  515. }
  516. }
  517. next2 = next2->next;
  518. }
  519. }
  520. #endif
  521. next1 = next1->next;
  522. }
  523. JITOutputIDL* jitOutputData = m_output.GetOutputData();
  524. size_t allocSize = offsetof(NativeDataFixupTable, fixupRecords) + sizeof(NativeDataFixupRecord)* (dataAllocator->allocCount);
  525. jitOutputData->nativeDataFixupTable = (NativeDataFixupTable*)midl_user_allocate(allocSize);
  526. if (!jitOutputData->nativeDataFixupTable)
  527. {
  528. Js::Throw::OutOfMemory();
  529. }
  530. __analysis_assume(jitOutputData->nativeDataFixupTable);
  531. jitOutputData->nativeDataFixupTable->count = dataAllocator->allocCount;
  532. jitOutputData->buffer = (NativeDataBuffer*)midl_user_allocate(offsetof(NativeDataBuffer, data) + dataAllocator->totalSize);
  533. if (!jitOutputData->buffer)
  534. {
  535. Js::Throw::OutOfMemory();
  536. }
  537. __analysis_assume(jitOutputData->buffer);
  538. jitOutputData->buffer->len = dataAllocator->totalSize;
  539. unsigned int len = 0;
  540. unsigned int count = 0;
  541. next1 = chunk;
  542. while (next1)
  543. {
  544. memcpy(jitOutputData->buffer->data + len, next1->data, next1->len);
  545. len += next1->len;
  546. jitOutputData->nativeDataFixupTable->fixupRecords[count].index = next1->allocIndex;
  547. jitOutputData->nativeDataFixupTable->fixupRecords[count].length = next1->len;
  548. jitOutputData->nativeDataFixupTable->fixupRecords[count].startOffset = next1->offset;
  549. jitOutputData->nativeDataFixupTable->fixupRecords[count].updateList = next1->fixupList;
  550. count++;
  551. next1 = next1->next;
  552. }
  553. #if DBG
  554. if (PHASE_TRACE1(Js::NativeCodeDataPhase))
  555. {
  556. Output::Print(_u("NativeCodeData Server Buffer: %p, len: %x, chunk head: %p\n"), jitOutputData->buffer->data, jitOutputData->buffer->len, chunk);
  557. }
  558. #endif
  559. }
  560. END_CODEGEN_PHASE(this, Js::NativeCodeDataPhase);
  561. }
  562. END_CODEGEN_PHASE(this, Js::BackEndPhase);
  563. }
  564. ///----------------------------------------------------------------------------
  565. /// Func::StackAllocate
  566. /// Allocate stack space of given size.
  567. ///----------------------------------------------------------------------------
  568. int32
  569. Func::StackAllocate(int size)
  570. {
  571. Assert(this->IsTopFunc());
  572. int32 offset;
  573. #ifdef MD_GROW_LOCALS_AREA_UP
  574. // Locals have positive offsets and are allocated from bottom to top.
  575. m_localStackHeight = Math::Align(m_localStackHeight, min(size, MachStackAlignment));
  576. offset = m_localStackHeight;
  577. m_localStackHeight += size;
  578. #else
  579. // Locals have negative offsets and are allocated from top to bottom.
  580. m_localStackHeight += size;
  581. m_localStackHeight = Math::Align(m_localStackHeight, min(size, MachStackAlignment));
  582. offset = -m_localStackHeight;
  583. #endif
  584. return offset;
  585. }
  586. ///----------------------------------------------------------------------------
  587. ///
  588. /// Func::StackAllocate
  589. ///
  590. /// Allocate stack space for this symbol.
  591. ///
  592. ///----------------------------------------------------------------------------
  593. int32
  594. Func::StackAllocate(StackSym *stackSym, int size)
  595. {
  596. Assert(size > 0);
  597. if (stackSym->IsArgSlotSym() || stackSym->IsParamSlotSym() || stackSym->IsAllocated())
  598. {
  599. return stackSym->m_offset;
  600. }
  601. Assert(stackSym->m_offset == 0);
  602. stackSym->m_allocated = true;
  603. stackSym->m_offset = StackAllocate(size);
  604. return stackSym->m_offset;
  605. }
  606. void
  607. Func::SetArgOffset(StackSym *stackSym, int32 offset)
  608. {
  609. AssertMsg(offset >= 0, "Why is the offset, negative?");
  610. stackSym->m_offset = offset;
  611. stackSym->m_allocated = true;
  612. }
  613. ///
  614. /// Ensures that local var slots are created, if the function has locals.
  615. /// Allocate stack space for locals used for debugging
  616. /// (for local non-temp vars we write-through memory so that locals inspection can make use of that.).
  617. // On stack, after local slots we allocate space for metadata (in particular, whether any the locals was changed in debugger).
  618. ///
  619. void
  620. Func::EnsureLocalVarSlots()
  621. {
  622. Assert(IsJitInDebugMode());
  623. if (!this->HasLocalVarSlotCreated())
  624. {
  625. uint32 localSlotCount = GetJITFunctionBody()->GetNonTempLocalVarCount();
  626. if (localSlotCount && m_localVarSlotsOffset == Js::Constants::InvalidOffset)
  627. {
  628. // Allocate the slots.
  629. int32 size = localSlotCount * GetDiagLocalSlotSize();
  630. m_localVarSlotsOffset = StackAllocate(size);
  631. m_hasLocalVarChangedOffset = StackAllocate(max(1, MachStackAlignment)); // Can't alloc less than StackAlignment bytes.
  632. Assert(m_workItem->Type() == JsFunctionType);
  633. m_output.SetVarSlotsOffset(AdjustOffsetValue(m_localVarSlotsOffset));
  634. m_output.SetVarChangedOffset(AdjustOffsetValue(m_hasLocalVarChangedOffset));
  635. }
  636. }
  637. }
  638. void Func::SetFirstArgOffset(IR::Instr* inlineeStart)
  639. {
  640. Assert(inlineeStart->m_func == this);
  641. Assert(!IsTopFunc());
  642. int32 lastOffset;
  643. IR::Instr* arg = inlineeStart->GetNextArg();
  644. if (arg)
  645. {
  646. const auto lastArgOutStackSym = arg->GetDst()->AsSymOpnd()->m_sym->AsStackSym();
  647. lastOffset = lastArgOutStackSym->m_offset;
  648. Assert(lastArgOutStackSym->m_isSingleDef);
  649. const auto secondLastArgOutOpnd = lastArgOutStackSym->m_instrDef->GetSrc2();
  650. if (secondLastArgOutOpnd->IsSymOpnd())
  651. {
  652. const auto secondLastOffset = secondLastArgOutOpnd->AsSymOpnd()->m_sym->AsStackSym()->m_offset;
  653. if (secondLastOffset > lastOffset)
  654. {
  655. lastOffset = secondLastOffset;
  656. }
  657. }
  658. lastOffset += MachPtr;
  659. }
  660. else
  661. {
  662. Assert(this->GetTopFunc()->GetJITFunctionBody()->IsAsmJsMode());
  663. lastOffset = MachPtr;
  664. }
  665. int32 firstActualStackOffset = lastOffset - ((this->actualCount + Js::Constants::InlineeMetaArgCount) * MachPtr);
  666. Assert((this->firstActualStackOffset == -1) || (this->firstActualStackOffset == firstActualStackOffset));
  667. this->firstActualStackOffset = firstActualStackOffset;
  668. }
  669. int32
  670. Func::GetLocalVarSlotOffset(int32 slotId)
  671. {
  672. this->EnsureLocalVarSlots();
  673. Assert(m_localVarSlotsOffset != Js::Constants::InvalidOffset);
  674. int32 slotOffset = slotId * GetDiagLocalSlotSize();
  675. return m_localVarSlotsOffset + slotOffset;
  676. }
  677. void Func::OnAddSym(Sym* sym)
  678. {
  679. Assert(sym);
  680. if (this->IsJitInDebugMode() && this->IsNonTempLocalVar(sym->m_id))
  681. {
  682. Assert(m_nonTempLocalVars);
  683. m_nonTempLocalVars->Set(sym->m_id);
  684. }
  685. }
  686. ///
  687. /// Returns offset of the flag (1 byte) whether any local was changed (in debugger).
  688. /// If the function does not have any locals, returns -1.
  689. ///
  690. int32
  691. Func::GetHasLocalVarChangedOffset()
  692. {
  693. this->EnsureLocalVarSlots();
  694. return m_hasLocalVarChangedOffset;
  695. }
  696. bool
  697. Func::IsJitInDebugMode() const
  698. {
  699. return m_workItem->IsJitInDebugMode();
  700. }
  701. bool
  702. Func::IsNonTempLocalVar(uint32 slotIndex)
  703. {
  704. return GetJITFunctionBody()->IsNonTempLocalVar(slotIndex);
  705. }
  706. int32
  707. Func::AdjustOffsetValue(int32 offset)
  708. {
  709. #ifdef MD_GROW_LOCALS_AREA_UP
  710. return -(offset + BailOutInfo::StackSymBias);
  711. #else
  712. // Stack offset are negative, includes the PUSH EBP and return address
  713. return offset - (2 * MachPtr);
  714. #endif
  715. }
  716. #ifdef MD_GROW_LOCALS_AREA_UP
  717. // Note: this is called during jit-compile when we finalize bail out record.
  718. void
  719. Func::AjustLocalVarSlotOffset()
  720. {
  721. if (GetJITFunctionBody()->GetNonTempLocalVarCount())
  722. {
  723. // Turn positive SP-relative base locals offset into negative frame-pointer-relative offset
  724. // This is changing value for restoring the locals when read due to locals inspection.
  725. int localsOffset = m_localVarSlotsOffset - (m_localStackHeight + m_ArgumentsOffset);
  726. int valueChangeOffset = m_hasLocalVarChangedOffset - (m_localStackHeight + m_ArgumentsOffset);
  727. m_output.SetVarSlotsOffset(localsOffset);
  728. m_output.SetVarChangedOffset(valueChangeOffset);
  729. }
  730. }
  731. #endif
  732. bool
  733. Func::DoGlobOptsForGeneratorFunc() const
  734. {
  735. // Disable GlobOpt optimizations for generators initially. Will visit and enable each one by one.
  736. return !GetJITFunctionBody()->IsCoroutine();
  737. }
  738. bool
  739. Func::DoSimpleJitDynamicProfile() const
  740. {
  741. return IsSimpleJit() && !PHASE_OFF(Js::SimpleJitDynamicProfilePhase, GetTopFunc()) && !CONFIG_FLAG(NewSimpleJit);
  742. }
  743. void
  744. Func::SetDoFastPaths()
  745. {
  746. // Make sure we only call this once!
  747. Assert(!this->hasCalledSetDoFastPaths);
  748. bool doFastPaths = false;
  749. if(!PHASE_OFF(Js::FastPathPhase, this) && (!IsSimpleJit() || CONFIG_FLAG(NewSimpleJit)))
  750. {
  751. doFastPaths = true;
  752. }
  753. this->m_doFastPaths = doFastPaths;
  754. #ifdef DBG
  755. this->hasCalledSetDoFastPaths = true;
  756. #endif
  757. }
  758. #if LOWER_SPLIT_INT64
  759. Int64RegPair Func::FindOrCreateInt64Pair(IR::Opnd* opnd)
  760. {
  761. if (!this->IsTopFunc())
  762. {
  763. return GetTopFunc()->FindOrCreateInt64Pair(opnd);
  764. }
  765. AssertMsg(currentPhases.Top() == Js::LowererPhase, "New Int64 sym map is only allowed during lower");
  766. Int64RegPair pair;
  767. IRType pairType = opnd->GetType();
  768. if (opnd->IsInt64())
  769. {
  770. pairType = IRType_IsSignedInt(pairType) ? TyInt32 : TyUint32;
  771. }
  772. if (opnd->IsIndirOpnd())
  773. {
  774. IR::IndirOpnd* indir = opnd->AsIndirOpnd();
  775. indir->SetType(pairType);
  776. pair.low = indir;
  777. pair.high = indir->Copy(this)->AsIndirOpnd();
  778. pair.high->AsIndirOpnd()->SetOffset(indir->GetOffset() + 4);
  779. return pair;
  780. }
  781. // Only indir opnd can have a type other than int64
  782. Assert(opnd->IsInt64());
  783. if (opnd->IsImmediateOpnd())
  784. {
  785. int64 value = opnd->GetImmediateValue(this);
  786. pair.low = IR::IntConstOpnd::New((int32)value, pairType, this);
  787. pair.high = IR::IntConstOpnd::New((int32)(value >> 32), pairType, this);
  788. return pair;
  789. }
  790. Int64SymPair symPair;
  791. if (!m_int64SymPairMap)
  792. {
  793. m_int64SymPairMap = Anew(m_alloc, Int64SymPairMap, m_alloc);
  794. }
  795. StackSym* stackSym = opnd->GetStackSym();
  796. AssertOrFailFastMsg(stackSym, "Invalid int64 operand type");
  797. SymID symId = stackSym->m_id;
  798. if (!m_int64SymPairMap->TryGetValue(symId, &symPair))
  799. {
  800. if (stackSym->IsArgSlotSym() || stackSym->IsParamSlotSym())
  801. {
  802. const bool isArg = stackSym->IsArgSlotSym();
  803. if (isArg)
  804. {
  805. Js::ArgSlot slotNumber = stackSym->GetArgSlotNum();
  806. symPair.low = StackSym::NewArgSlotSym(slotNumber, this, pairType);
  807. symPair.high = StackSym::NewArgSlotSym(slotNumber, this, pairType);
  808. }
  809. else
  810. {
  811. Js::ArgSlot slotNumber = stackSym->GetParamSlotNum();
  812. symPair.low = StackSym::NewParamSlotSym(slotNumber, this, pairType);
  813. symPair.high = StackSym::NewParamSlotSym(slotNumber + 1, this, pairType);
  814. }
  815. symPair.low->m_allocated = true;
  816. symPair.low->m_offset = stackSym->m_offset;
  817. symPair.high->m_allocated = true;
  818. symPair.high->m_offset = stackSym->m_offset + 4;
  819. }
  820. else
  821. {
  822. symPair.low = StackSym::New(pairType, this);
  823. symPair.high = StackSym::New(pairType, this);
  824. }
  825. m_int64SymPairMap->Add(symId, symPair);
  826. }
  827. if (opnd->IsSymOpnd())
  828. {
  829. pair.low = IR::SymOpnd::New(symPair.low, opnd->AsSymOpnd()->m_offset, pairType, this);
  830. pair.high = IR::SymOpnd::New(symPair.high, opnd->AsSymOpnd()->m_offset, pairType, this);
  831. }
  832. else
  833. {
  834. pair.low = IR::RegOpnd::New(symPair.low, pairType, this);
  835. pair.high = IR::RegOpnd::New(symPair.high, pairType, this);
  836. }
  837. return pair;
  838. }
  839. void Func::Int64SplitExtendLoopLifetime(Loop* loop)
  840. {
  841. if (!this->IsTopFunc())
  842. {
  843. GetTopFunc()->Int64SplitExtendLoopLifetime(loop);
  844. return;
  845. }
  846. if (m_int64SymPairMap)
  847. {
  848. BVSparse<JitArenaAllocator> *liveOnBackEdgeSyms = loop->regAlloc.liveOnBackEdgeSyms;
  849. FOREACH_BITSET_IN_SPARSEBV(symId, liveOnBackEdgeSyms)
  850. {
  851. Int64SymPair pair;
  852. if (m_int64SymPairMap->TryGetValue(symId, &pair))
  853. {
  854. // If we have replaced any sym that was live on the back edge for 2 other syms
  855. // these 2 syms needs to be live on back edge as well.
  856. liveOnBackEdgeSyms->Set(pair.low->m_id);
  857. liveOnBackEdgeSyms->Set(pair.high->m_id);
  858. }
  859. } NEXT_BITSET_IN_SPARSEBV;
  860. }
  861. }
  862. #endif
  863. #if defined(_M_ARM32_OR_ARM64)
  864. RegNum
  865. Func::GetLocalsPointer() const
  866. {
  867. #ifdef DBG
  868. if (Js::Configuration::Global.flags.IsEnabled(Js::ForceLocalsPtrFlag))
  869. {
  870. return ALT_LOCALS_PTR;
  871. }
  872. #endif
  873. if (GetJITFunctionBody()->HasTry())
  874. {
  875. return ALT_LOCALS_PTR;
  876. }
  877. return RegSP;
  878. }
  879. #endif
  880. void Func::AddSlotArrayCheck(IR::SymOpnd *fieldOpnd)
  881. {
  882. if (PHASE_OFF(Js::ClosureRangeCheckPhase, this))
  883. {
  884. return;
  885. }
  886. Assert(IsTopFunc());
  887. if (this->slotArrayCheckTable == nullptr)
  888. {
  889. this->slotArrayCheckTable = SlotArrayCheckTable::New(m_alloc, 4);
  890. }
  891. PropertySym *propertySym = fieldOpnd->m_sym->AsPropertySym();
  892. uint32 slot = propertySym->m_propertyId;
  893. uint32 *pSlotId = this->slotArrayCheckTable->FindOrInsert(slot, propertySym->m_stackSym->m_id);
  894. if (pSlotId && (*pSlotId == (uint32)-1 || *pSlotId < slot))
  895. {
  896. *pSlotId = propertySym->m_propertyId;
  897. }
  898. }
  899. void Func::AddFrameDisplayCheck(IR::SymOpnd *fieldOpnd, uint32 slotId)
  900. {
  901. if (PHASE_OFF(Js::ClosureRangeCheckPhase, this))
  902. {
  903. return;
  904. }
  905. Assert(IsTopFunc());
  906. if (this->frameDisplayCheckTable == nullptr)
  907. {
  908. this->frameDisplayCheckTable = FrameDisplayCheckTable::New(m_alloc, 4);
  909. }
  910. PropertySym *propertySym = fieldOpnd->m_sym->AsPropertySym();
  911. FrameDisplayCheckRecord **record = this->frameDisplayCheckTable->FindOrInsertNew(propertySym->m_stackSym->m_id);
  912. if (*record == nullptr)
  913. {
  914. *record = JitAnew(m_alloc, FrameDisplayCheckRecord);
  915. }
  916. uint32 frameDisplaySlot = propertySym->m_propertyId;
  917. if ((*record)->table == nullptr || (*record)->slotId < frameDisplaySlot)
  918. {
  919. (*record)->slotId = frameDisplaySlot;
  920. }
  921. if (slotId != (uint32)-1)
  922. {
  923. if ((*record)->table == nullptr)
  924. {
  925. (*record)->table = SlotArrayCheckTable::New(m_alloc, 4);
  926. }
  927. uint32 *pSlotId = (*record)->table->FindOrInsert(slotId, frameDisplaySlot);
  928. if (pSlotId && *pSlotId < slotId)
  929. {
  930. *pSlotId = slotId;
  931. }
  932. }
  933. }
  934. void Func::InitLocalClosureSyms()
  935. {
  936. Assert(this->m_localClosureSym == nullptr);
  937. // Allocate stack space for closure pointers. Do this only if we're jitting for stack closures, and
  938. // tell bailout that these are not byte code symbols so that we don't try to encode them in the bailout record,
  939. // as they don't have normal lifetimes.
  940. Js::RegSlot regSlot = GetJITFunctionBody()->GetLocalClosureReg();
  941. if (regSlot != Js::Constants::NoRegister)
  942. {
  943. this->m_localClosureSym =
  944. StackSym::FindOrCreate(static_cast<SymID>(regSlot),
  945. this->DoStackFrameDisplay() ? (Js::RegSlot)-1 : regSlot,
  946. this);
  947. }
  948. regSlot = this->GetJITFunctionBody()->GetParamClosureReg();
  949. if (regSlot != Js::Constants::NoRegister)
  950. {
  951. Assert(this->GetParamClosureSym() == nullptr && !this->GetJITFunctionBody()->IsParamAndBodyScopeMerged());
  952. this->m_paramClosureSym =
  953. StackSym::FindOrCreate(static_cast<SymID>(regSlot),
  954. this->DoStackFrameDisplay() ? (Js::RegSlot) - 1 : regSlot,
  955. this);
  956. }
  957. regSlot = GetJITFunctionBody()->GetLocalFrameDisplayReg();
  958. if (regSlot != Js::Constants::NoRegister)
  959. {
  960. this->m_localFrameDisplaySym =
  961. StackSym::FindOrCreate(static_cast<SymID>(regSlot),
  962. this->DoStackFrameDisplay() ? (Js::RegSlot)-1 : regSlot,
  963. this);
  964. }
  965. }
  966. bool
  967. Func::IsTrackCompoundedIntOverflowDisabled() const
  968. {
  969. return (HasProfileInfo() && GetReadOnlyProfileInfo()->IsTrackCompoundedIntOverflowDisabled()) || m_output.IsTrackCompoundedIntOverflowDisabled();
  970. }
  971. bool
  972. Func::IsArrayCheckHoistDisabled() const
  973. {
  974. return (HasProfileInfo() && GetReadOnlyProfileInfo()->IsArrayCheckHoistDisabled(IsLoopBody())) || m_output.IsArrayCheckHoistDisabled();
  975. }
  976. bool
  977. Func::IsStackArgOptDisabled() const
  978. {
  979. return (HasProfileInfo() && GetReadOnlyProfileInfo()->IsStackArgOptDisabled()) || m_output.IsStackArgOptDisabled();
  980. }
  981. bool
  982. Func::IsSwitchOptDisabled() const
  983. {
  984. return (HasProfileInfo() && GetReadOnlyProfileInfo()->IsSwitchOptDisabled()) || m_output.IsSwitchOptDisabled();
  985. }
  986. bool
  987. Func::IsAggressiveIntTypeSpecDisabled() const
  988. {
  989. return (HasProfileInfo() && GetReadOnlyProfileInfo()->IsAggressiveIntTypeSpecDisabled(IsLoopBody())) || m_output.IsAggressiveIntTypeSpecDisabled();
  990. }
  991. bool Func::CanAllocInPreReservedHeapPageSegment ()
  992. {
  993. #ifdef _CONTROL_FLOW_GUARD
  994. return PHASE_FORCE1(Js::PreReservedHeapAllocPhase) || (!PHASE_OFF1(Js::PreReservedHeapAllocPhase) &&
  995. !IsJitInDebugMode() && GetThreadContextInfo()->IsCFGEnabled()
  996. //&& !GetScriptContext()->IsScriptContextInDebugMode()
  997. #if _M_IX86
  998. && m_workItem->GetJitMode() == ExecutionMode::FullJit
  999. #if ENABLE_OOP_NATIVE_CODEGEN
  1000. && (JITManager::GetJITManager()->IsJITServer()
  1001. ? GetOOPCodeGenAllocators()->canCreatePreReservedSegment
  1002. : GetInProcCodeGenAllocators()->canCreatePreReservedSegment)
  1003. #else
  1004. && GetInProcCodeGenAllocators()->canCreatePreReservedSegment
  1005. #endif
  1006. );
  1007. #elif TARGET_64
  1008. && true);
  1009. #else
  1010. && false); //Not yet implemented for architectures other than x86 and amd64.
  1011. #endif //_M_ARCH
  1012. #else
  1013. return false;
  1014. #endif//_CONTROL_FLOW_GUARD
  1015. }
  1016. ///----------------------------------------------------------------------------
  1017. ///
  1018. /// Func::GetInstrCount
  1019. ///
  1020. /// Returns the number of instrs.
  1021. /// Note: It counts all instrs for now, including labels, etc.
  1022. ///
  1023. ///----------------------------------------------------------------------------
  1024. uint32
  1025. Func::GetInstrCount()
  1026. {
  1027. uint instrCount = 0;
  1028. FOREACH_INSTR_IN_FUNC(instr, this)
  1029. {
  1030. instrCount++;
  1031. }NEXT_INSTR_IN_FUNC;
  1032. return instrCount;
  1033. }
  1034. ///----------------------------------------------------------------------------
  1035. ///
  1036. /// Func::NumberInstrs
  1037. ///
  1038. /// Number each instruction in order of appearance in the function.
  1039. ///
  1040. ///----------------------------------------------------------------------------
  1041. void
  1042. Func::NumberInstrs()
  1043. {
  1044. #if DBG_DUMP
  1045. Assert(this->IsTopFunc());
  1046. Assert(!this->hasInstrNumber);
  1047. this->hasInstrNumber = true;
  1048. #endif
  1049. uint instrCount = 1;
  1050. FOREACH_INSTR_IN_FUNC(instr, this)
  1051. {
  1052. instr->SetNumber(instrCount++);
  1053. }
  1054. NEXT_INSTR_IN_FUNC;
  1055. }
  1056. ///----------------------------------------------------------------------------
  1057. ///
  1058. /// Func::IsInPhase
  1059. ///
  1060. /// Determines whether the function is currently in the provided phase
  1061. ///
  1062. ///----------------------------------------------------------------------------
  1063. #if DBG
  1064. bool
  1065. Func::IsInPhase(Js::Phase tag)
  1066. {
  1067. return this->GetTopFunc()->currentPhases.Contains(tag);
  1068. }
  1069. #endif
  1070. ///----------------------------------------------------------------------------
  1071. ///
  1072. /// Func::BeginPhase
  1073. ///
  1074. /// Takes care of the profiler
  1075. ///
  1076. ///----------------------------------------------------------------------------
  1077. void
  1078. Func::BeginPhase(Js::Phase tag)
  1079. {
  1080. #ifdef DBG
  1081. this->GetTopFunc()->currentPhases.Push(tag);
  1082. if (PHASE_DEBUGBREAK_ON_PHASE_BEGIN(tag, this))
  1083. {
  1084. __debugbreak();
  1085. }
  1086. #endif
  1087. #ifdef PROFILE_EXEC
  1088. AssertMsg((this->m_codeGenProfiler != nullptr) == Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag),
  1089. "Profiler tag is supplied but the profiler pointer is NULL");
  1090. if (this->m_codeGenProfiler)
  1091. {
  1092. this->m_codeGenProfiler->ProfileBegin(tag);
  1093. }
  1094. #endif
  1095. }
  1096. ///----------------------------------------------------------------------------
  1097. ///
  1098. /// Func::EndPhase
  1099. ///
  1100. /// Takes care of the profiler and dumper
  1101. ///
  1102. ///----------------------------------------------------------------------------
  1103. void
  1104. Func::EndProfiler(Js::Phase tag)
  1105. {
  1106. #ifdef DBG
  1107. Assert(this->GetTopFunc()->currentPhases.Count() > 0);
  1108. Js::Phase popped = this->GetTopFunc()->currentPhases.Pop();
  1109. Assert(tag == popped);
  1110. #endif
  1111. #ifdef PROFILE_EXEC
  1112. AssertMsg((this->m_codeGenProfiler != nullptr) == Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag),
  1113. "Profiler tag is supplied but the profiler pointer is NULL");
  1114. if (this->m_codeGenProfiler)
  1115. {
  1116. this->m_codeGenProfiler->ProfileEnd(tag);
  1117. }
  1118. #endif
  1119. }
  1120. void
  1121. Func::EndPhase(Js::Phase tag, bool dump)
  1122. {
  1123. this->EndProfiler(tag);
  1124. #if DBG_DUMP
  1125. if(dump && (PHASE_DUMP(tag, this)
  1126. || PHASE_DUMP(Js::BackEndPhase, this)))
  1127. {
  1128. Output::Print(_u("-----------------------------------------------------------------------------\n"));
  1129. if (IsLoopBody())
  1130. {
  1131. Output::Print(_u("************ IR after %s (%S) Loop %d ************\n"),
  1132. Js::PhaseNames[tag],
  1133. ExecutionModeName(m_workItem->GetJitMode()),
  1134. m_workItem->GetLoopNumber());
  1135. }
  1136. else
  1137. {
  1138. Output::Print(_u("************ IR after %s (%S) ************\n"),
  1139. Js::PhaseNames[tag],
  1140. ExecutionModeName(m_workItem->GetJitMode()));
  1141. }
  1142. this->Dump(Js::Configuration::Global.flags.AsmDiff? IRDumpFlags_AsmDumpMode : IRDumpFlags_None);
  1143. }
  1144. #endif
  1145. #if DBG
  1146. if (tag == Js::LowererPhase)
  1147. {
  1148. Assert(!this->isPostLower);
  1149. this->isPostLower = true;
  1150. }
  1151. else if (tag == Js::RegAllocPhase)
  1152. {
  1153. Assert(!this->isPostRegAlloc);
  1154. this->isPostRegAlloc = true;
  1155. }
  1156. else if (tag == Js::PeepsPhase)
  1157. {
  1158. Assert(this->isPostLower && !this->isPostLayout);
  1159. this->isPostPeeps = true;
  1160. }
  1161. else if (tag == Js::LayoutPhase)
  1162. {
  1163. Assert(this->isPostPeeps && !this->isPostLayout);
  1164. this->isPostLayout = true;
  1165. }
  1166. else if (tag == Js::FinalLowerPhase)
  1167. {
  1168. Assert(this->isPostLayout && !this->isPostFinalLower);
  1169. this->isPostFinalLower = true;
  1170. }
  1171. if (this->isPostLower)
  1172. {
  1173. #ifndef _M_ARM // Need to verify ARM is clean.
  1174. DbCheckPostLower dbCheck(this);
  1175. dbCheck.Check();
  1176. #endif
  1177. }
  1178. this->m_alloc->MergeDelayFreeList();
  1179. #endif
  1180. }
  1181. Func const *
  1182. Func::GetTopFunc() const
  1183. {
  1184. Func const * func = this;
  1185. while (!func->IsTopFunc())
  1186. {
  1187. func = func->parentFunc;
  1188. }
  1189. return func;
  1190. }
  1191. Func *
  1192. Func::GetTopFunc()
  1193. {
  1194. Func * func = this;
  1195. while (!func->IsTopFunc())
  1196. {
  1197. func = func->parentFunc;
  1198. }
  1199. return func;
  1200. }
  1201. StackSym *
  1202. Func::EnsureLoopParamSym()
  1203. {
  1204. if (this->m_loopParamSym == nullptr)
  1205. {
  1206. this->m_loopParamSym = StackSym::New(TyMachPtr, this);
  1207. }
  1208. return this->m_loopParamSym;
  1209. }
  1210. void
  1211. Func::UpdateMaxInlineeArgOutSize(uint inlineeArgOutSize)
  1212. {
  1213. if (this->maxInlineeArgOutSize < inlineeArgOutSize)
  1214. {
  1215. this->maxInlineeArgOutSize = inlineeArgOutSize;
  1216. }
  1217. }
  1218. void
  1219. Func::BeginClone(Lowerer * lowerer, JitArenaAllocator *alloc)
  1220. {
  1221. Assert(this->IsTopFunc());
  1222. AssertMsg(m_cloner == nullptr, "Starting new clone while one is in progress");
  1223. m_cloner = JitAnew(alloc, Cloner, lowerer, alloc);
  1224. if (m_cloneMap == nullptr)
  1225. {
  1226. m_cloneMap = JitAnew(alloc, InstrMap, alloc, 7);
  1227. }
  1228. }
  1229. void
  1230. Func::EndClone()
  1231. {
  1232. Assert(this->IsTopFunc());
  1233. if (m_cloner)
  1234. {
  1235. m_cloner->Finish();
  1236. JitAdelete(m_cloner->alloc, m_cloner);
  1237. m_cloner = nullptr;
  1238. }
  1239. }
  1240. IR::SymOpnd *
  1241. Func::GetInlineeOpndAtOffset(int32 offset)
  1242. {
  1243. Assert(IsInlinee());
  1244. StackSym *stackSym = CreateInlineeStackSym();
  1245. this->SetArgOffset(stackSym, stackSym->m_offset + offset);
  1246. Assert(stackSym->m_offset >= 0);
  1247. return IR::SymOpnd::New(stackSym, 0, TyMachReg, this);
  1248. }
  1249. StackSym *
  1250. Func::CreateInlineeStackSym()
  1251. {
  1252. // Make sure this is an inlinee and that GlobOpt has initialized the offset
  1253. // in the inlinee's frame.
  1254. Assert(IsInlinee());
  1255. Assert(m_inlineeFrameStartSym->m_offset != -1);
  1256. StackSym *stackSym = m_symTable->GetArgSlotSym((Js::ArgSlot)-1);
  1257. stackSym->m_isInlinedArgSlot = true;
  1258. stackSym->m_offset = m_inlineeFrameStartSym->m_offset;
  1259. stackSym->m_allocated = true;
  1260. return stackSym;
  1261. }
  1262. uint16
  1263. Func::GetArgUsedForBranch() const
  1264. {
  1265. // this value can change while JITing, so or these together
  1266. return GetJITFunctionBody()->GetArgUsedForBranch() | GetJITOutput()->GetArgUsedForBranch();
  1267. }
  1268. intptr_t
  1269. Func::GetJittedLoopIterationsSinceLastBailoutAddress() const
  1270. {
  1271. Assert(this->m_workItem->Type() == JsLoopBodyWorkItemType);
  1272. return m_workItem->GetJittedLoopIterationsSinceLastBailoutAddr();
  1273. }
  1274. intptr_t
  1275. Func::GetWeakFuncRef() const
  1276. {
  1277. // TODO: OOP JIT figure out if this can be null
  1278. return m_workItem->GetJITTimeInfo()->GetWeakFuncRef();
  1279. }
  1280. intptr_t
  1281. Func::GetRuntimeInlineCache(const uint index) const
  1282. {
  1283. if(m_runtimeInfo != nullptr && m_runtimeInfo->HasClonedInlineCaches())
  1284. {
  1285. intptr_t inlineCache = m_runtimeInfo->GetClonedInlineCache(index);
  1286. if(inlineCache)
  1287. {
  1288. return inlineCache;
  1289. }
  1290. }
  1291. return GetJITFunctionBody()->GetInlineCache(index);
  1292. }
  1293. JITTimePolymorphicInlineCache *
  1294. Func::GetRuntimePolymorphicInlineCache(const uint index) const
  1295. {
  1296. if (this->m_polymorphicInlineCacheInfo && this->m_polymorphicInlineCacheInfo->HasInlineCaches())
  1297. {
  1298. return this->m_polymorphicInlineCacheInfo->GetInlineCache(index);
  1299. }
  1300. return nullptr;
  1301. }
  1302. byte
  1303. Func::GetPolyCacheUtilToInitialize(const uint index) const
  1304. {
  1305. return this->GetRuntimePolymorphicInlineCache(index) ? this->GetPolyCacheUtil(index) : PolymorphicInlineCacheUtilizationMinValue;
  1306. }
  1307. byte
  1308. Func::GetPolyCacheUtil(const uint index) const
  1309. {
  1310. return this->m_polymorphicInlineCacheInfo->GetUtil(index);
  1311. }
  1312. ObjTypeSpecFldInfo*
  1313. Func::GetObjTypeSpecFldInfo(const uint index) const
  1314. {
  1315. if (GetJITFunctionBody()->GetInlineCacheCount() == 0)
  1316. {
  1317. Assert(UNREACHED);
  1318. return nullptr;
  1319. }
  1320. return GetWorkItem()->GetJITTimeInfo()->GetObjTypeSpecFldInfo(index);
  1321. }
  1322. ObjTypeSpecFldInfo*
  1323. Func::GetGlobalObjTypeSpecFldInfo(uint propertyInfoId) const
  1324. {
  1325. Assert(propertyInfoId < GetTopFunc()->GetWorkItem()->GetJITTimeInfo()->GetGlobalObjTypeSpecFldInfoCount());
  1326. return GetTopFunc()->m_globalObjTypeSpecFldInfoArray[propertyInfoId];
  1327. }
  1328. void
  1329. Func::EnsurePinnedTypeRefs()
  1330. {
  1331. if (this->pinnedTypeRefs == nullptr)
  1332. {
  1333. this->pinnedTypeRefs = JitAnew(this->m_alloc, TypeRefSet, this->m_alloc);
  1334. }
  1335. }
  1336. void
  1337. Func::PinTypeRef(void* typeRef)
  1338. {
  1339. EnsurePinnedTypeRefs();
  1340. this->pinnedTypeRefs->AddNew(typeRef);
  1341. }
  1342. void
  1343. Func::EnsureSingleTypeGuards()
  1344. {
  1345. if (this->singleTypeGuards == nullptr)
  1346. {
  1347. this->singleTypeGuards = JitAnew(this->m_alloc, TypePropertyGuardDictionary, this->m_alloc);
  1348. }
  1349. }
  1350. Js::JitTypePropertyGuard*
  1351. Func::GetOrCreateSingleTypeGuard(intptr_t typeAddr)
  1352. {
  1353. EnsureSingleTypeGuards();
  1354. Js::JitTypePropertyGuard* guard = nullptr;
  1355. if (!this->singleTypeGuards->TryGetValue(typeAddr, &guard))
  1356. {
  1357. // Property guards are allocated by NativeCodeData::Allocator so that their lifetime extends as long as the EntryPointInfo is alive.
  1358. guard = NativeCodeDataNewNoFixup(GetNativeCodeDataAllocator(), Js::JitTypePropertyGuard, typeAddr, this->indexedPropertyGuardCount++);
  1359. this->singleTypeGuards->Add(typeAddr, guard);
  1360. }
  1361. else
  1362. {
  1363. Assert(guard->GetTypeAddr() == typeAddr);
  1364. }
  1365. return guard;
  1366. }
  1367. void
  1368. Func::EnsureEquivalentTypeGuards()
  1369. {
  1370. if (this->equivalentTypeGuards == nullptr)
  1371. {
  1372. this->equivalentTypeGuards = JitAnew(this->m_alloc, EquivalentTypeGuardList, this->m_alloc);
  1373. }
  1374. }
  1375. Js::JitEquivalentTypeGuard*
  1376. Func::CreateEquivalentTypeGuard(JITTypeHolder type, uint32 objTypeSpecFldId)
  1377. {
  1378. EnsureEquivalentTypeGuards();
  1379. Js::JitEquivalentTypeGuard* guard = NativeCodeDataNewNoFixup(GetNativeCodeDataAllocator(), Js::JitEquivalentTypeGuard, type->GetAddr(), this->indexedPropertyGuardCount++, objTypeSpecFldId);
  1380. // If we want to hard code the address of the cache, we will need to go back to allocating it from the native code data allocator.
  1381. // We would then need to maintain consistency (double write) to both the recycler allocated cache and the one on the heap.
  1382. Js::EquivalentTypeCache* cache = nullptr;
  1383. if (this->IsOOPJIT())
  1384. {
  1385. cache = JitAnewZ(this->m_alloc, Js::EquivalentTypeCache);
  1386. }
  1387. else
  1388. {
  1389. cache = NativeCodeDataNewZNoFixup(GetTransferDataAllocator(), Js::EquivalentTypeCache);
  1390. }
  1391. guard->SetCache(cache);
  1392. // Give the cache a back-pointer to the guard so that the guard can be cleared at runtime if necessary.
  1393. cache->SetGuard(guard);
  1394. this->equivalentTypeGuards->Prepend(guard);
  1395. return guard;
  1396. }
  1397. void
  1398. Func::EnsurePropertyGuardsByPropertyId()
  1399. {
  1400. if (this->propertyGuardsByPropertyId == nullptr)
  1401. {
  1402. this->propertyGuardsByPropertyId = JitAnew(this->m_alloc, PropertyGuardByPropertyIdMap, this->m_alloc);
  1403. }
  1404. }
  1405. void
  1406. Func::EnsureCtorCachesByPropertyId()
  1407. {
  1408. if (this->ctorCachesByPropertyId == nullptr)
  1409. {
  1410. this->ctorCachesByPropertyId = JitAnew(this->m_alloc, CtorCachesByPropertyIdMap, this->m_alloc);
  1411. }
  1412. }
  1413. void
  1414. Func::LinkGuardToPropertyId(Js::PropertyId propertyId, Js::JitIndexedPropertyGuard* guard)
  1415. {
  1416. Assert(guard != nullptr);
  1417. Assert(guard->GetValue() != NULL);
  1418. Assert(this->propertyGuardsByPropertyId != nullptr);
  1419. IndexedPropertyGuardSet* set;
  1420. if (!this->propertyGuardsByPropertyId->TryGetValue(propertyId, &set))
  1421. {
  1422. set = JitAnew(this->m_alloc, IndexedPropertyGuardSet, this->m_alloc);
  1423. this->propertyGuardsByPropertyId->Add(propertyId, set);
  1424. }
  1425. set->Item(guard);
  1426. }
  1427. void
  1428. Func::LinkCtorCacheToPropertyId(Js::PropertyId propertyId, JITTimeConstructorCache* cache)
  1429. {
  1430. Assert(cache != nullptr);
  1431. Assert(this->ctorCachesByPropertyId != nullptr);
  1432. CtorCacheSet* set;
  1433. if (!this->ctorCachesByPropertyId->TryGetValue(propertyId, &set))
  1434. {
  1435. set = JitAnew(this->m_alloc, CtorCacheSet, this->m_alloc);
  1436. this->ctorCachesByPropertyId->Add(propertyId, set);
  1437. }
  1438. set->Item(cache->GetRuntimeCacheAddr());
  1439. }
  1440. JITTimeConstructorCache* Func::GetConstructorCache(const Js::ProfileId profiledCallSiteId)
  1441. {
  1442. Assert(profiledCallSiteId < GetJITFunctionBody()->GetProfiledCallSiteCount());
  1443. Assert(this->constructorCaches != nullptr);
  1444. return this->constructorCaches[profiledCallSiteId];
  1445. }
  1446. void Func::SetConstructorCache(const Js::ProfileId profiledCallSiteId, JITTimeConstructorCache* constructorCache)
  1447. {
  1448. Assert(profiledCallSiteId < GetJITFunctionBody()->GetProfiledCallSiteCount());
  1449. Assert(constructorCache != nullptr);
  1450. Assert(this->constructorCaches != nullptr);
  1451. Assert(this->constructorCaches[profiledCallSiteId] == nullptr);
  1452. this->constructorCacheCount++;
  1453. this->constructorCaches[profiledCallSiteId] = constructorCache;
  1454. }
  1455. void Func::EnsurePropertiesWrittenTo()
  1456. {
  1457. if (this->propertiesWrittenTo == nullptr)
  1458. {
  1459. this->propertiesWrittenTo = JitAnew(this->m_alloc, PropertyIdSet, this->m_alloc);
  1460. }
  1461. }
  1462. void Func::EnsureCallSiteToArgumentsOffsetFixupMap()
  1463. {
  1464. if (this->callSiteToArgumentsOffsetFixupMap == nullptr)
  1465. {
  1466. this->callSiteToArgumentsOffsetFixupMap = JitAnew(this->m_alloc, CallSiteToArgumentsOffsetFixupMap, this->m_alloc);
  1467. }
  1468. }
  1469. IR::LabelInstr *
  1470. Func::GetFuncStartLabel()
  1471. {
  1472. return m_funcStartLabel;
  1473. }
  1474. IR::LabelInstr *
  1475. Func::EnsureFuncStartLabel()
  1476. {
  1477. if(m_funcStartLabel == nullptr)
  1478. {
  1479. m_funcStartLabel = IR::LabelInstr::New( Js::OpCode::Label, this );
  1480. m_funcStartLabel->m_isDataLabel = true;
  1481. }
  1482. return m_funcStartLabel;
  1483. }
  1484. IR::LabelInstr *
  1485. Func::GetFuncEndLabel()
  1486. {
  1487. return m_funcEndLabel;
  1488. }
  1489. IR::LabelInstr *
  1490. Func::EnsureFuncEndLabel()
  1491. {
  1492. if(m_funcEndLabel == nullptr)
  1493. {
  1494. m_funcEndLabel = IR::LabelInstr::New( Js::OpCode::Label, this );
  1495. m_funcEndLabel->m_isDataLabel = true;
  1496. }
  1497. return m_funcEndLabel;
  1498. }
  1499. void
  1500. Func::EnsureStackArgWithFormalsTracker()
  1501. {
  1502. if (stackArgWithFormalsTracker == nullptr)
  1503. {
  1504. stackArgWithFormalsTracker = JitAnew(m_alloc, StackArgWithFormalsTracker, m_alloc);
  1505. }
  1506. }
  1507. BOOL
  1508. Func::IsFormalsArraySym(SymID symId)
  1509. {
  1510. if (stackArgWithFormalsTracker == nullptr || stackArgWithFormalsTracker->GetFormalsArraySyms() == nullptr)
  1511. {
  1512. return false;
  1513. }
  1514. return stackArgWithFormalsTracker->GetFormalsArraySyms()->Test(symId);
  1515. }
  1516. void
  1517. Func::TrackFormalsArraySym(SymID symId)
  1518. {
  1519. EnsureStackArgWithFormalsTracker();
  1520. stackArgWithFormalsTracker->SetFormalsArraySyms(symId);
  1521. }
  1522. void
  1523. Func::TrackStackSymForFormalIndex(Js::ArgSlot formalsIndex, StackSym * sym)
  1524. {
  1525. EnsureStackArgWithFormalsTracker();
  1526. Js::ArgSlot formalsCount = GetJITFunctionBody()->GetInParamsCount() - 1;
  1527. stackArgWithFormalsTracker->SetStackSymInFormalsIndexMap(sym, formalsIndex, formalsCount);
  1528. }
  1529. StackSym *
  1530. Func::GetStackSymForFormal(Js::ArgSlot formalsIndex)
  1531. {
  1532. if (stackArgWithFormalsTracker == nullptr || stackArgWithFormalsTracker->GetFormalsIndexToStackSymMap() == nullptr)
  1533. {
  1534. return nullptr;
  1535. }
  1536. Js::ArgSlot formalsCount = GetJITFunctionBody()->GetInParamsCount() - 1;
  1537. StackSym ** formalsIndexToStackSymMap = stackArgWithFormalsTracker->GetFormalsIndexToStackSymMap();
  1538. AssertMsg(formalsIndex < formalsCount, "OutOfRange ? ");
  1539. return formalsIndexToStackSymMap[formalsIndex];
  1540. }
  1541. bool
  1542. Func::HasStackSymForFormal(Js::ArgSlot formalsIndex)
  1543. {
  1544. if (stackArgWithFormalsTracker == nullptr || stackArgWithFormalsTracker->GetFormalsIndexToStackSymMap() == nullptr)
  1545. {
  1546. return false;
  1547. }
  1548. return GetStackSymForFormal(formalsIndex) != nullptr;
  1549. }
  1550. void
  1551. Func::SetScopeObjSym(StackSym * sym)
  1552. {
  1553. EnsureStackArgWithFormalsTracker();
  1554. stackArgWithFormalsTracker->SetScopeObjSym(sym);
  1555. }
  1556. StackSym *
  1557. Func::GetNativeCodeDataSym() const
  1558. {
  1559. Assert(IsOOPJIT());
  1560. return m_nativeCodeDataSym;
  1561. }
  1562. void
  1563. Func::SetNativeCodeDataSym(StackSym * opnd)
  1564. {
  1565. Assert(IsOOPJIT());
  1566. m_nativeCodeDataSym = opnd;
  1567. }
  1568. StackSym*
  1569. Func::GetScopeObjSym()
  1570. {
  1571. if (stackArgWithFormalsTracker == nullptr)
  1572. {
  1573. return nullptr;
  1574. }
  1575. return stackArgWithFormalsTracker->GetScopeObjSym();
  1576. }
  1577. BVSparse<JitArenaAllocator> *
  1578. StackArgWithFormalsTracker::GetFormalsArraySyms()
  1579. {
  1580. return formalsArraySyms;
  1581. }
  1582. void
  1583. StackArgWithFormalsTracker::SetFormalsArraySyms(SymID symId)
  1584. {
  1585. if (formalsArraySyms == nullptr)
  1586. {
  1587. formalsArraySyms = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  1588. }
  1589. formalsArraySyms->Set(symId);
  1590. }
  1591. StackSym **
  1592. StackArgWithFormalsTracker::GetFormalsIndexToStackSymMap()
  1593. {
  1594. return formalsIndexToStackSymMap;
  1595. }
  1596. void
  1597. StackArgWithFormalsTracker::SetStackSymInFormalsIndexMap(StackSym * sym, Js::ArgSlot formalsIndex, Js::ArgSlot formalsCount)
  1598. {
  1599. if(formalsIndexToStackSymMap == nullptr)
  1600. {
  1601. formalsIndexToStackSymMap = JitAnewArrayZ(alloc, StackSym*, formalsCount);
  1602. }
  1603. AssertMsg(formalsIndex < formalsCount, "Out of range ?");
  1604. formalsIndexToStackSymMap[formalsIndex] = sym;
  1605. }
  1606. void
  1607. StackArgWithFormalsTracker::SetScopeObjSym(StackSym * sym)
  1608. {
  1609. m_scopeObjSym = sym;
  1610. }
  1611. StackSym *
  1612. StackArgWithFormalsTracker::GetScopeObjSym()
  1613. {
  1614. return m_scopeObjSym;
  1615. }
  1616. void
  1617. Cloner::AddInstr(IR::Instr * instrOrig, IR::Instr * instrClone)
  1618. {
  1619. if (!this->instrFirst)
  1620. {
  1621. this->instrFirst = instrClone;
  1622. }
  1623. this->instrLast = instrClone;
  1624. }
  1625. void
  1626. Cloner::Finish()
  1627. {
  1628. this->RetargetClonedBranches();
  1629. if (this->lowerer)
  1630. {
  1631. lowerer->LowerRange(this->instrFirst, this->instrLast, false, false);
  1632. }
  1633. }
  1634. void
  1635. Cloner::RetargetClonedBranches()
  1636. {
  1637. if (!this->fRetargetClonedBranch)
  1638. {
  1639. return;
  1640. }
  1641. FOREACH_INSTR_IN_RANGE(instr, this->instrFirst, this->instrLast)
  1642. {
  1643. if (instr->IsBranchInstr())
  1644. {
  1645. instr->AsBranchInstr()->RetargetClonedBranch();
  1646. }
  1647. }
  1648. NEXT_INSTR_IN_RANGE;
  1649. }
  1650. void Func::ThrowIfScriptClosed()
  1651. {
  1652. if (GetScriptContextInfo()->IsClosed())
  1653. {
  1654. // Should not be jitting something in the foreground when the script context is actually closed
  1655. Assert(IsBackgroundJIT() || !GetScriptContext()->IsActuallyClosed());
  1656. throw Js::OperationAbortedException();
  1657. }
  1658. }
  1659. IR::IndirOpnd * Func::GetConstantAddressIndirOpnd(intptr_t address, IR::Opnd * largeConstOpnd, IR::AddrOpndKind kind, IRType type, Js::OpCode loadOpCode)
  1660. {
  1661. Assert(this->GetTopFunc() == this);
  1662. if (!canHoistConstantAddressLoad)
  1663. {
  1664. // We can't hoist constant address load after lower, as we can't mark the sym as
  1665. // live on back edge
  1666. return nullptr;
  1667. }
  1668. int offset = 0;
  1669. IR::RegOpnd ** foundRegOpnd = this->constantAddressRegOpnd.Find([address, &offset](IR::RegOpnd * regOpnd)
  1670. {
  1671. Assert(regOpnd->m_sym->IsSingleDef());
  1672. Assert(regOpnd->m_sym->m_instrDef->GetSrc1()->IsAddrOpnd() || regOpnd->m_sym->m_instrDef->GetSrc1()->IsIntConstOpnd());
  1673. void * curr = regOpnd->m_sym->m_instrDef->GetSrc1()->IsAddrOpnd() ?
  1674. regOpnd->m_sym->m_instrDef->GetSrc1()->AsAddrOpnd()->m_address :
  1675. (void *)regOpnd->m_sym->m_instrDef->GetSrc1()->AsIntConstOpnd()->GetValue();
  1676. ptrdiff_t diff = (uintptr_t)address - (uintptr_t)curr;
  1677. if (!Math::FitsInDWord(diff))
  1678. {
  1679. return false;
  1680. }
  1681. offset = (int)diff;
  1682. return true;
  1683. });
  1684. IR::RegOpnd * addressRegOpnd;
  1685. if (foundRegOpnd != nullptr)
  1686. {
  1687. addressRegOpnd = *foundRegOpnd;
  1688. }
  1689. else
  1690. {
  1691. Assert(offset == 0);
  1692. addressRegOpnd = IR::RegOpnd::New(TyMachPtr, this);
  1693. IR::Instr *const newInstr =
  1694. IR::Instr::New(
  1695. loadOpCode,
  1696. addressRegOpnd,
  1697. largeConstOpnd,
  1698. this);
  1699. this->constantAddressRegOpnd.Prepend(addressRegOpnd);
  1700. IR::Instr * insertBeforeInstr = this->lastConstantAddressRegLoadInstr;
  1701. if (insertBeforeInstr == nullptr)
  1702. {
  1703. insertBeforeInstr = this->GetFunctionEntryInsertionPoint();
  1704. this->lastConstantAddressRegLoadInstr = newInstr;
  1705. }
  1706. insertBeforeInstr->InsertBefore(newInstr);
  1707. }
  1708. IR::IndirOpnd * indirOpnd = IR::IndirOpnd::New(addressRegOpnd, offset, type, this, true);
  1709. #if DBG_DUMP
  1710. // TODO: michhol make intptr_t
  1711. indirOpnd->SetAddrKind(kind, (void*)address);
  1712. #endif
  1713. return indirOpnd;
  1714. }
  1715. void Func::MarkConstantAddressSyms(BVSparse<JitArenaAllocator> * bv)
  1716. {
  1717. Assert(this->GetTopFunc() == this);
  1718. this->constantAddressRegOpnd.Iterate([bv](IR::RegOpnd * regOpnd)
  1719. {
  1720. bv->Set(regOpnd->m_sym->m_id);
  1721. });
  1722. }
  1723. IR::Instr *
  1724. Func::GetFunctionEntryInsertionPoint()
  1725. {
  1726. Assert(this->GetTopFunc() == this);
  1727. IR::Instr * insertInsert = this->lastConstantAddressRegLoadInstr;
  1728. if (insertInsert != nullptr)
  1729. {
  1730. return insertInsert->m_next;
  1731. }
  1732. insertInsert = this->m_headInstr;
  1733. if (this->HasTry())
  1734. {
  1735. // Insert it inside the root region
  1736. insertInsert = insertInsert->m_next;
  1737. Assert(insertInsert->IsLabelInstr() && insertInsert->AsLabelInstr()->GetRegion()->GetType() == RegionTypeRoot);
  1738. }
  1739. return insertInsert->m_next;
  1740. }
  1741. Js::Var
  1742. Func::AllocateNumber(double value)
  1743. {
  1744. Js::Var number = nullptr;
  1745. #if FLOATVAR
  1746. number = Js::JavascriptNumber::NewCodeGenInstance((double)value, nullptr);
  1747. #else
  1748. if (!IsOOPJIT()) // in-proc jit
  1749. {
  1750. number = Js::JavascriptNumber::NewCodeGenInstance(GetNumberAllocator(), (double)value, GetScriptContext());
  1751. }
  1752. else // OOP JIT
  1753. {
  1754. number = GetXProcNumberAllocator()->AllocateNumber(this, value);
  1755. }
  1756. #endif
  1757. return number;
  1758. }
  1759. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  1760. void
  1761. Func::DumpFullFunctionName()
  1762. {
  1763. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  1764. Output::Print(_u("Function %s (%s)"), GetJITFunctionBody()->GetDisplayName(), GetDebugNumberSet(debugStringBuffer));
  1765. }
  1766. #endif
  1767. void
  1768. Func::UpdateForInLoopMaxDepth(uint forInLoopMaxDepth)
  1769. {
  1770. Assert(this->IsTopFunc());
  1771. this->m_forInLoopMaxDepth = max(this->m_forInLoopMaxDepth, forInLoopMaxDepth);
  1772. }
  1773. int
  1774. Func::GetForInEnumeratorArrayOffset() const
  1775. {
  1776. Func const* topFunc = this->GetTopFunc();
  1777. Assert(this->m_forInLoopBaseDepth + this->GetJITFunctionBody()->GetForInLoopDepth() <= topFunc->m_forInLoopMaxDepth);
  1778. return topFunc->m_forInEnumeratorArrayOffset
  1779. + this->m_forInLoopBaseDepth * sizeof(Js::ForInObjectEnumerator);
  1780. }
  1781. #if DBG_DUMP
  1782. ///----------------------------------------------------------------------------
  1783. ///
  1784. /// Func::DumpHeader
  1785. ///
  1786. ///----------------------------------------------------------------------------
  1787. void
  1788. Func::DumpHeader()
  1789. {
  1790. Output::Print(_u("-----------------------------------------------------------------------------\n"));
  1791. DumpFullFunctionName();
  1792. Output::SkipToColumn(50);
  1793. Output::Print(_u("Instr Count:%d"), GetInstrCount());
  1794. if(m_codeSize > 0)
  1795. {
  1796. Output::Print(_u("\t\tSize:%d\n\n"), m_codeSize);
  1797. }
  1798. else
  1799. {
  1800. Output::Print(_u("\n\n"));
  1801. }
  1802. }
  1803. ///----------------------------------------------------------------------------
  1804. ///
  1805. /// Func::Dump
  1806. ///
  1807. ///----------------------------------------------------------------------------
  1808. void
  1809. Func::Dump(IRDumpFlags flags)
  1810. {
  1811. this->DumpHeader();
  1812. FOREACH_INSTR_IN_FUNC(instr, this)
  1813. {
  1814. instr->DumpGlobOptInstrString();
  1815. instr->Dump(flags);
  1816. }NEXT_INSTR_IN_FUNC;
  1817. Output::Flush();
  1818. }
  1819. void
  1820. Func::Dump()
  1821. {
  1822. this->Dump(IRDumpFlags_None);
  1823. }
  1824. #endif
  1825. #if DBG_DUMP || defined(ENABLE_IR_VIEWER)
  1826. LPCSTR
  1827. Func::GetVtableName(INT_PTR address)
  1828. {
  1829. #if DBG
  1830. if (vtableMap == nullptr)
  1831. {
  1832. vtableMap = VirtualTableRegistry::CreateVtableHashMap(this->m_alloc);
  1833. };
  1834. LPCSTR name = vtableMap->Lookup(address, nullptr);
  1835. if (name)
  1836. {
  1837. if (strncmp(name, "class ", _countof("class ") - 1) == 0)
  1838. {
  1839. name += _countof("class ") - 1;
  1840. }
  1841. }
  1842. return name;
  1843. #else
  1844. return "";
  1845. #endif
  1846. }
  1847. #endif
  1848. #if DBG_DUMP | defined(VTUNE_PROFILING)
  1849. bool Func::DoRecordNativeMap() const
  1850. {
  1851. #if defined(VTUNE_PROFILING)
  1852. if (VTuneChakraProfile::isJitProfilingActive)
  1853. {
  1854. return true;
  1855. }
  1856. #endif
  1857. #if DBG_DUMP
  1858. return PHASE_DUMP(Js::EncoderPhase, this) && Js::Configuration::Global.flags.Verbose;
  1859. #else
  1860. return false;
  1861. #endif
  1862. }
  1863. #endif
  1864. #ifdef PERF_HINT
  1865. void WritePerfHint(PerfHints hint, Func* func, uint byteCodeOffset /*= Js::Constants::NoByteCodeOffset*/)
  1866. {
  1867. if (!func->IsOOPJIT())
  1868. {
  1869. WritePerfHint(hint, (Js::FunctionBody*)func->GetJITFunctionBody()->GetAddr(), byteCodeOffset);
  1870. }
  1871. }
  1872. #endif