RegAllocGreedy.cpp 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673
  1. //===- RegAllocGreedy.cpp - greedy register allocator ---------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the RAGreedy function pass for register allocation in
  10. // optimized builds.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "RegAllocGreedy.h"
  14. #include "AllocationOrder.h"
  15. #include "InterferenceCache.h"
  16. #include "LiveDebugVariables.h"
  17. #include "RegAllocBase.h"
  18. #include "RegAllocEvictionAdvisor.h"
  19. #include "RegAllocPriorityAdvisor.h"
  20. #include "SpillPlacement.h"
  21. #include "SplitKit.h"
  22. #include "llvm/ADT/ArrayRef.h"
  23. #include "llvm/ADT/BitVector.h"
  24. #include "llvm/ADT/IndexedMap.h"
  25. #include "llvm/ADT/SmallPtrSet.h"
  26. #include "llvm/ADT/SmallSet.h"
  27. #include "llvm/ADT/SmallVector.h"
  28. #include "llvm/ADT/Statistic.h"
  29. #include "llvm/ADT/StringRef.h"
  30. #include "llvm/Analysis/AliasAnalysis.h"
  31. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  32. #include "llvm/CodeGen/CalcSpillWeights.h"
  33. #include "llvm/CodeGen/EdgeBundles.h"
  34. #include "llvm/CodeGen/LiveInterval.h"
  35. #include "llvm/CodeGen/LiveIntervalUnion.h"
  36. #include "llvm/CodeGen/LiveIntervals.h"
  37. #include "llvm/CodeGen/LiveRangeEdit.h"
  38. #include "llvm/CodeGen/LiveRegMatrix.h"
  39. #include "llvm/CodeGen/LiveStacks.h"
  40. #include "llvm/CodeGen/MachineBasicBlock.h"
  41. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  42. #include "llvm/CodeGen/MachineDominators.h"
  43. #include "llvm/CodeGen/MachineFrameInfo.h"
  44. #include "llvm/CodeGen/MachineFunction.h"
  45. #include "llvm/CodeGen/MachineFunctionPass.h"
  46. #include "llvm/CodeGen/MachineInstr.h"
  47. #include "llvm/CodeGen/MachineLoopInfo.h"
  48. #include "llvm/CodeGen/MachineOperand.h"
  49. #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
  50. #include "llvm/CodeGen/MachineRegisterInfo.h"
  51. #include "llvm/CodeGen/RegAllocRegistry.h"
  52. #include "llvm/CodeGen/RegisterClassInfo.h"
  53. #include "llvm/CodeGen/SlotIndexes.h"
  54. #include "llvm/CodeGen/Spiller.h"
  55. #include "llvm/CodeGen/TargetInstrInfo.h"
  56. #include "llvm/CodeGen/TargetRegisterInfo.h"
  57. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  58. #include "llvm/CodeGen/VirtRegMap.h"
  59. #include "llvm/IR/DebugInfoMetadata.h"
  60. #include "llvm/IR/Function.h"
  61. #include "llvm/IR/LLVMContext.h"
  62. #include "llvm/InitializePasses.h"
  63. #include "llvm/MC/MCRegisterInfo.h"
  64. #include "llvm/Pass.h"
  65. #include "llvm/Support/BlockFrequency.h"
  66. #include "llvm/Support/BranchProbability.h"
  67. #include "llvm/Support/CommandLine.h"
  68. #include "llvm/Support/Debug.h"
  69. #include "llvm/Support/MathExtras.h"
  70. #include "llvm/Support/Timer.h"
  71. #include "llvm/Support/raw_ostream.h"
  72. #include <algorithm>
  73. #include <cassert>
  74. #include <cstdint>
  75. #include <utility>
  76. using namespace llvm;
  77. #define DEBUG_TYPE "regalloc"
  78. STATISTIC(NumGlobalSplits, "Number of split global live ranges");
  79. STATISTIC(NumLocalSplits, "Number of split local live ranges");
  80. STATISTIC(NumEvicted, "Number of interferences evicted");
  81. static cl::opt<SplitEditor::ComplementSpillMode> SplitSpillMode(
  82. "split-spill-mode", cl::Hidden,
  83. cl::desc("Spill mode for splitting live ranges"),
  84. cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
  85. clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
  86. clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed")),
  87. cl::init(SplitEditor::SM_Speed));
  88. static cl::opt<unsigned>
  89. LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden,
  90. cl::desc("Last chance recoloring max depth"),
  91. cl::init(5));
  92. static cl::opt<unsigned> LastChanceRecoloringMaxInterference(
  93. "lcr-max-interf", cl::Hidden,
  94. cl::desc("Last chance recoloring maximum number of considered"
  95. " interference at a time"),
  96. cl::init(8));
  97. static cl::opt<bool> ExhaustiveSearch(
  98. "exhaustive-register-search", cl::NotHidden,
  99. cl::desc("Exhaustive Search for registers bypassing the depth "
  100. "and interference cutoffs of last chance recoloring"),
  101. cl::Hidden);
  102. static cl::opt<bool> EnableDeferredSpilling(
  103. "enable-deferred-spilling", cl::Hidden,
  104. cl::desc("Instead of spilling a variable right away, defer the actual "
  105. "code insertion to the end of the allocation. That way the "
  106. "allocator might still find a suitable coloring for this "
  107. "variable because of other evicted variables."),
  108. cl::init(false));
  109. // FIXME: Find a good default for this flag and remove the flag.
  110. static cl::opt<unsigned>
  111. CSRFirstTimeCost("regalloc-csr-first-time-cost",
  112. cl::desc("Cost for first time use of callee-saved register."),
  113. cl::init(0), cl::Hidden);
  114. static cl::opt<unsigned long> GrowRegionComplexityBudget(
  115. "grow-region-complexity-budget",
  116. cl::desc("growRegion() does not scale with the number of BB edges, so "
  117. "limit its budget and bail out once we reach the limit."),
  118. cl::init(10000), cl::Hidden);
  119. static cl::opt<bool> GreedyRegClassPriorityTrumpsGlobalness(
  120. "greedy-regclass-priority-trumps-globalness",
  121. cl::desc("Change the greedy register allocator's live range priority "
  122. "calculation to make the AllocationPriority of the register class "
  123. "more important then whether the range is global"),
  124. cl::Hidden);
  125. static cl::opt<bool> GreedyReverseLocalAssignment(
  126. "greedy-reverse-local-assignment",
  127. cl::desc("Reverse allocation order of local live ranges, such that "
  128. "shorter local live ranges will tend to be allocated first"),
  129. cl::Hidden);
  130. static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
  131. createGreedyRegisterAllocator);
  132. char RAGreedy::ID = 0;
  133. char &llvm::RAGreedyID = RAGreedy::ID;
  134. INITIALIZE_PASS_BEGIN(RAGreedy, "greedy",
  135. "Greedy Register Allocator", false, false)
  136. INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
  137. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  138. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  139. INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
  140. INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
  141. INITIALIZE_PASS_DEPENDENCY(LiveStacks)
  142. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  143. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  144. INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
  145. INITIALIZE_PASS_DEPENDENCY(LiveRegMatrix)
  146. INITIALIZE_PASS_DEPENDENCY(EdgeBundles)
  147. INITIALIZE_PASS_DEPENDENCY(SpillPlacement)
  148. INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass)
  149. INITIALIZE_PASS_DEPENDENCY(RegAllocEvictionAdvisorAnalysis)
  150. INITIALIZE_PASS_DEPENDENCY(RegAllocPriorityAdvisorAnalysis)
  151. INITIALIZE_PASS_END(RAGreedy, "greedy",
  152. "Greedy Register Allocator", false, false)
  153. #ifndef NDEBUG
  154. const char *const RAGreedy::StageName[] = {
  155. "RS_New",
  156. "RS_Assign",
  157. "RS_Split",
  158. "RS_Split2",
  159. "RS_Spill",
  160. "RS_Memory",
  161. "RS_Done"
  162. };
  163. #endif
  164. // Hysteresis to use when comparing floats.
  165. // This helps stabilize decisions based on float comparisons.
  166. const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
  167. FunctionPass* llvm::createGreedyRegisterAllocator() {
  168. return new RAGreedy();
  169. }
  170. FunctionPass *llvm::createGreedyRegisterAllocator(RegClassFilterFunc Ftor) {
  171. return new RAGreedy(Ftor);
  172. }
  173. RAGreedy::RAGreedy(RegClassFilterFunc F):
  174. MachineFunctionPass(ID),
  175. RegAllocBase(F) {
  176. }
  177. void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
  178. AU.setPreservesCFG();
  179. AU.addRequired<MachineBlockFrequencyInfo>();
  180. AU.addPreserved<MachineBlockFrequencyInfo>();
  181. AU.addRequired<LiveIntervals>();
  182. AU.addPreserved<LiveIntervals>();
  183. AU.addRequired<SlotIndexes>();
  184. AU.addPreserved<SlotIndexes>();
  185. AU.addRequired<LiveDebugVariables>();
  186. AU.addPreserved<LiveDebugVariables>();
  187. AU.addRequired<LiveStacks>();
  188. AU.addPreserved<LiveStacks>();
  189. AU.addRequired<MachineDominatorTree>();
  190. AU.addPreserved<MachineDominatorTree>();
  191. AU.addRequired<MachineLoopInfo>();
  192. AU.addPreserved<MachineLoopInfo>();
  193. AU.addRequired<VirtRegMap>();
  194. AU.addPreserved<VirtRegMap>();
  195. AU.addRequired<LiveRegMatrix>();
  196. AU.addPreserved<LiveRegMatrix>();
  197. AU.addRequired<EdgeBundles>();
  198. AU.addRequired<SpillPlacement>();
  199. AU.addRequired<MachineOptimizationRemarkEmitterPass>();
  200. AU.addRequired<RegAllocEvictionAdvisorAnalysis>();
  201. AU.addRequired<RegAllocPriorityAdvisorAnalysis>();
  202. MachineFunctionPass::getAnalysisUsage(AU);
  203. }
  204. //===----------------------------------------------------------------------===//
  205. // LiveRangeEdit delegate methods
  206. //===----------------------------------------------------------------------===//
  207. bool RAGreedy::LRE_CanEraseVirtReg(Register VirtReg) {
  208. LiveInterval &LI = LIS->getInterval(VirtReg);
  209. if (VRM->hasPhys(VirtReg)) {
  210. Matrix->unassign(LI);
  211. aboutToRemoveInterval(LI);
  212. return true;
  213. }
  214. // Unassigned virtreg is probably in the priority queue.
  215. // RegAllocBase will erase it after dequeueing.
  216. // Nonetheless, clear the live-range so that the debug
  217. // dump will show the right state for that VirtReg.
  218. LI.clear();
  219. return false;
  220. }
  221. void RAGreedy::LRE_WillShrinkVirtReg(Register VirtReg) {
  222. if (!VRM->hasPhys(VirtReg))
  223. return;
  224. // Register is assigned, put it back on the queue for reassignment.
  225. LiveInterval &LI = LIS->getInterval(VirtReg);
  226. Matrix->unassign(LI);
  227. RegAllocBase::enqueue(&LI);
  228. }
  229. void RAGreedy::LRE_DidCloneVirtReg(Register New, Register Old) {
  230. ExtraInfo->LRE_DidCloneVirtReg(New, Old);
  231. }
  232. void RAGreedy::ExtraRegInfo::LRE_DidCloneVirtReg(Register New, Register Old) {
  233. // Cloning a register we haven't even heard about yet? Just ignore it.
  234. if (!Info.inBounds(Old))
  235. return;
  236. // LRE may clone a virtual register because dead code elimination causes it to
  237. // be split into connected components. The new components are much smaller
  238. // than the original, so they should get a new chance at being assigned.
  239. // same stage as the parent.
  240. Info[Old].Stage = RS_Assign;
  241. Info.grow(New.id());
  242. Info[New] = Info[Old];
  243. }
  244. void RAGreedy::releaseMemory() {
  245. SpillerInstance.reset();
  246. GlobalCand.clear();
  247. }
  248. void RAGreedy::enqueueImpl(const LiveInterval *LI) { enqueue(Queue, LI); }
  249. void RAGreedy::enqueue(PQueue &CurQueue, const LiveInterval *LI) {
  250. // Prioritize live ranges by size, assigning larger ranges first.
  251. // The queue holds (size, reg) pairs.
  252. const Register Reg = LI->reg();
  253. assert(Reg.isVirtual() && "Can only enqueue virtual registers");
  254. auto Stage = ExtraInfo->getOrInitStage(Reg);
  255. if (Stage == RS_New) {
  256. Stage = RS_Assign;
  257. ExtraInfo->setStage(Reg, Stage);
  258. }
  259. unsigned Ret = PriorityAdvisor->getPriority(*LI);
  260. // The virtual register number is a tie breaker for same-sized ranges.
  261. // Give lower vreg numbers higher priority to assign them first.
  262. CurQueue.push(std::make_pair(Ret, ~Reg));
  263. }
  264. unsigned DefaultPriorityAdvisor::getPriority(const LiveInterval &LI) const {
  265. const unsigned Size = LI.getSize();
  266. const Register Reg = LI.reg();
  267. unsigned Prio;
  268. LiveRangeStage Stage = RA.getExtraInfo().getStage(LI);
  269. if (Stage == RS_Split) {
  270. // Unsplit ranges that couldn't be allocated immediately are deferred until
  271. // everything else has been allocated.
  272. Prio = Size;
  273. } else if (Stage == RS_Memory) {
  274. // Memory operand should be considered last.
  275. // Change the priority such that Memory operand are assigned in
  276. // the reverse order that they came in.
  277. // TODO: Make this a member variable and probably do something about hints.
  278. static unsigned MemOp = 0;
  279. Prio = MemOp++;
  280. } else {
  281. // Giant live ranges fall back to the global assignment heuristic, which
  282. // prevents excessive spilling in pathological cases.
  283. const TargetRegisterClass &RC = *MRI->getRegClass(Reg);
  284. bool ForceGlobal = RC.GlobalPriority ||
  285. (!ReverseLocalAssignment &&
  286. (Size / SlotIndex::InstrDist) >
  287. (2 * RegClassInfo.getNumAllocatableRegs(&RC)));
  288. unsigned GlobalBit = 0;
  289. if (Stage == RS_Assign && !ForceGlobal && !LI.empty() &&
  290. LIS->intervalIsInOneMBB(LI)) {
  291. // Allocate original local ranges in linear instruction order. Since they
  292. // are singly defined, this produces optimal coloring in the absence of
  293. // global interference and other constraints.
  294. if (!ReverseLocalAssignment)
  295. Prio = LI.beginIndex().getApproxInstrDistance(Indexes->getLastIndex());
  296. else {
  297. // Allocating bottom up may allow many short LRGs to be assigned first
  298. // to one of the cheap registers. This could be much faster for very
  299. // large blocks on targets with many physical registers.
  300. Prio = Indexes->getZeroIndex().getApproxInstrDistance(LI.endIndex());
  301. }
  302. } else {
  303. // Allocate global and split ranges in long->short order. Long ranges that
  304. // don't fit should be spilled (or split) ASAP so they don't create
  305. // interference. Mark a bit to prioritize global above local ranges.
  306. Prio = Size;
  307. GlobalBit = 1;
  308. }
  309. // Priority bit layout:
  310. // 31 RS_Assign priority
  311. // 30 Preference priority
  312. // if (RegClassPriorityTrumpsGlobalness)
  313. // 29-25 AllocPriority
  314. // 24 GlobalBit
  315. // else
  316. // 29 Global bit
  317. // 28-24 AllocPriority
  318. // 0-23 Size/Instr distance
  319. // Clamp the size to fit with the priority masking scheme
  320. Prio = std::min(Prio, (unsigned)maxUIntN(24));
  321. assert(isUInt<5>(RC.AllocationPriority) && "allocation priority overflow");
  322. if (RegClassPriorityTrumpsGlobalness)
  323. Prio |= RC.AllocationPriority << 25 | GlobalBit << 24;
  324. else
  325. Prio |= GlobalBit << 29 | RC.AllocationPriority << 24;
  326. // Mark a higher bit to prioritize global and local above RS_Split.
  327. Prio |= (1u << 31);
  328. // Boost ranges that have a physical register hint.
  329. if (VRM->hasKnownPreference(Reg))
  330. Prio |= (1u << 30);
  331. }
  332. return Prio;
  333. }
  334. const LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); }
  335. const LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
  336. if (CurQueue.empty())
  337. return nullptr;
  338. LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
  339. CurQueue.pop();
  340. return LI;
  341. }
  342. //===----------------------------------------------------------------------===//
  343. // Direct Assignment
  344. //===----------------------------------------------------------------------===//
  345. /// tryAssign - Try to assign VirtReg to an available register.
  346. MCRegister RAGreedy::tryAssign(const LiveInterval &VirtReg,
  347. AllocationOrder &Order,
  348. SmallVectorImpl<Register> &NewVRegs,
  349. const SmallVirtRegSet &FixedRegisters) {
  350. MCRegister PhysReg;
  351. for (auto I = Order.begin(), E = Order.end(); I != E && !PhysReg; ++I) {
  352. assert(*I);
  353. if (!Matrix->checkInterference(VirtReg, *I)) {
  354. if (I.isHint())
  355. return *I;
  356. else
  357. PhysReg = *I;
  358. }
  359. }
  360. if (!PhysReg.isValid())
  361. return PhysReg;
  362. // PhysReg is available, but there may be a better choice.
  363. // If we missed a simple hint, try to cheaply evict interference from the
  364. // preferred register.
  365. if (Register Hint = MRI->getSimpleHint(VirtReg.reg()))
  366. if (Order.isHint(Hint)) {
  367. MCRegister PhysHint = Hint.asMCReg();
  368. LLVM_DEBUG(dbgs() << "missed hint " << printReg(PhysHint, TRI) << '\n');
  369. if (EvictAdvisor->canEvictHintInterference(VirtReg, PhysHint,
  370. FixedRegisters)) {
  371. evictInterference(VirtReg, PhysHint, NewVRegs);
  372. return PhysHint;
  373. }
  374. // Record the missed hint, we may be able to recover
  375. // at the end if the surrounding allocation changed.
  376. SetOfBrokenHints.insert(&VirtReg);
  377. }
  378. // Try to evict interference from a cheaper alternative.
  379. uint8_t Cost = RegCosts[PhysReg];
  380. // Most registers have 0 additional cost.
  381. if (!Cost)
  382. return PhysReg;
  383. LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << " is available at cost "
  384. << (unsigned)Cost << '\n');
  385. MCRegister CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost, FixedRegisters);
  386. return CheapReg ? CheapReg : PhysReg;
  387. }
  388. //===----------------------------------------------------------------------===//
  389. // Interference eviction
  390. //===----------------------------------------------------------------------===//
  391. Register RegAllocEvictionAdvisor::canReassign(const LiveInterval &VirtReg,
  392. Register PrevReg) const {
  393. auto Order =
  394. AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
  395. MCRegister PhysReg;
  396. for (auto I = Order.begin(), E = Order.end(); I != E && !PhysReg; ++I) {
  397. if ((*I).id() == PrevReg.id())
  398. continue;
  399. MCRegUnitIterator Units(*I, TRI);
  400. for (; Units.isValid(); ++Units) {
  401. // Instantiate a "subquery", not to be confused with the Queries array.
  402. LiveIntervalUnion::Query subQ(VirtReg, Matrix->getLiveUnions()[*Units]);
  403. if (subQ.checkInterference())
  404. break;
  405. }
  406. // If no units have interference, break out with the current PhysReg.
  407. if (!Units.isValid())
  408. PhysReg = *I;
  409. }
  410. if (PhysReg)
  411. LLVM_DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
  412. << printReg(PrevReg, TRI) << " to "
  413. << printReg(PhysReg, TRI) << '\n');
  414. return PhysReg;
  415. }
  416. /// evictInterference - Evict any interferring registers that prevent VirtReg
  417. /// from being assigned to Physreg. This assumes that canEvictInterference
  418. /// returned true.
  419. void RAGreedy::evictInterference(const LiveInterval &VirtReg,
  420. MCRegister PhysReg,
  421. SmallVectorImpl<Register> &NewVRegs) {
  422. // Make sure that VirtReg has a cascade number, and assign that cascade
  423. // number to every evicted register. These live ranges than then only be
  424. // evicted by a newer cascade, preventing infinite loops.
  425. unsigned Cascade = ExtraInfo->getOrAssignNewCascade(VirtReg.reg());
  426. LLVM_DEBUG(dbgs() << "evicting " << printReg(PhysReg, TRI)
  427. << " interference: Cascade " << Cascade << '\n');
  428. // Collect all interfering virtregs first.
  429. SmallVector<const LiveInterval *, 8> Intfs;
  430. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
  431. LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
  432. // We usually have the interfering VRegs cached so collectInterferingVRegs()
  433. // should be fast, we may need to recalculate if when different physregs
  434. // overlap the same register unit so we had different SubRanges queried
  435. // against it.
  436. ArrayRef<const LiveInterval *> IVR = Q.interferingVRegs();
  437. Intfs.append(IVR.begin(), IVR.end());
  438. }
  439. // Evict them second. This will invalidate the queries.
  440. for (const LiveInterval *Intf : Intfs) {
  441. // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
  442. if (!VRM->hasPhys(Intf->reg()))
  443. continue;
  444. Matrix->unassign(*Intf);
  445. assert((ExtraInfo->getCascade(Intf->reg()) < Cascade ||
  446. VirtReg.isSpillable() < Intf->isSpillable()) &&
  447. "Cannot decrease cascade number, illegal eviction");
  448. ExtraInfo->setCascade(Intf->reg(), Cascade);
  449. ++NumEvicted;
  450. NewVRegs.push_back(Intf->reg());
  451. }
  452. }
  453. /// Returns true if the given \p PhysReg is a callee saved register and has not
  454. /// been used for allocation yet.
  455. bool RegAllocEvictionAdvisor::isUnusedCalleeSavedReg(MCRegister PhysReg) const {
  456. MCRegister CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg);
  457. if (!CSR)
  458. return false;
  459. return !Matrix->isPhysRegUsed(PhysReg);
  460. }
  461. std::optional<unsigned>
  462. RegAllocEvictionAdvisor::getOrderLimit(const LiveInterval &VirtReg,
  463. const AllocationOrder &Order,
  464. unsigned CostPerUseLimit) const {
  465. unsigned OrderLimit = Order.getOrder().size();
  466. if (CostPerUseLimit < uint8_t(~0u)) {
  467. // Check of any registers in RC are below CostPerUseLimit.
  468. const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg());
  469. uint8_t MinCost = RegClassInfo.getMinCost(RC);
  470. if (MinCost >= CostPerUseLimit) {
  471. LLVM_DEBUG(dbgs() << TRI->getRegClassName(RC) << " minimum cost = "
  472. << MinCost << ", no cheaper registers to be found.\n");
  473. return std::nullopt;
  474. }
  475. // It is normal for register classes to have a long tail of registers with
  476. // the same cost. We don't need to look at them if they're too expensive.
  477. if (RegCosts[Order.getOrder().back()] >= CostPerUseLimit) {
  478. OrderLimit = RegClassInfo.getLastCostChange(RC);
  479. LLVM_DEBUG(dbgs() << "Only trying the first " << OrderLimit
  480. << " regs.\n");
  481. }
  482. }
  483. return OrderLimit;
  484. }
  485. bool RegAllocEvictionAdvisor::canAllocatePhysReg(unsigned CostPerUseLimit,
  486. MCRegister PhysReg) const {
  487. if (RegCosts[PhysReg] >= CostPerUseLimit)
  488. return false;
  489. // The first use of a callee-saved register in a function has cost 1.
  490. // Don't start using a CSR when the CostPerUseLimit is low.
  491. if (CostPerUseLimit == 1 && isUnusedCalleeSavedReg(PhysReg)) {
  492. LLVM_DEBUG(
  493. dbgs() << printReg(PhysReg, TRI) << " would clobber CSR "
  494. << printReg(RegClassInfo.getLastCalleeSavedAlias(PhysReg), TRI)
  495. << '\n');
  496. return false;
  497. }
  498. return true;
  499. }
  500. /// tryEvict - Try to evict all interferences for a physreg.
  501. /// @param VirtReg Currently unassigned virtual register.
  502. /// @param Order Physregs to try.
  503. /// @return Physreg to assign VirtReg, or 0.
  504. MCRegister RAGreedy::tryEvict(const LiveInterval &VirtReg,
  505. AllocationOrder &Order,
  506. SmallVectorImpl<Register> &NewVRegs,
  507. uint8_t CostPerUseLimit,
  508. const SmallVirtRegSet &FixedRegisters) {
  509. NamedRegionTimer T("evict", "Evict", TimerGroupName, TimerGroupDescription,
  510. TimePassesIsEnabled);
  511. MCRegister BestPhys = EvictAdvisor->tryFindEvictionCandidate(
  512. VirtReg, Order, CostPerUseLimit, FixedRegisters);
  513. if (BestPhys.isValid())
  514. evictInterference(VirtReg, BestPhys, NewVRegs);
  515. return BestPhys;
  516. }
  517. //===----------------------------------------------------------------------===//
  518. // Region Splitting
  519. //===----------------------------------------------------------------------===//
  520. /// addSplitConstraints - Fill out the SplitConstraints vector based on the
  521. /// interference pattern in Physreg and its aliases. Add the constraints to
  522. /// SpillPlacement and return the static cost of this split in Cost, assuming
  523. /// that all preferences in SplitConstraints are met.
  524. /// Return false if there are no bundles with positive bias.
  525. bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
  526. BlockFrequency &Cost) {
  527. ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
  528. // Reset interference dependent info.
  529. SplitConstraints.resize(UseBlocks.size());
  530. BlockFrequency StaticCost = 0;
  531. for (unsigned I = 0; I != UseBlocks.size(); ++I) {
  532. const SplitAnalysis::BlockInfo &BI = UseBlocks[I];
  533. SpillPlacement::BlockConstraint &BC = SplitConstraints[I];
  534. BC.Number = BI.MBB->getNumber();
  535. Intf.moveToBlock(BC.Number);
  536. BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
  537. BC.Exit = (BI.LiveOut &&
  538. !LIS->getInstructionFromIndex(BI.LastInstr)->isImplicitDef())
  539. ? SpillPlacement::PrefReg
  540. : SpillPlacement::DontCare;
  541. BC.ChangesValue = BI.FirstDef.isValid();
  542. if (!Intf.hasInterference())
  543. continue;
  544. // Number of spill code instructions to insert.
  545. unsigned Ins = 0;
  546. // Interference for the live-in value.
  547. if (BI.LiveIn) {
  548. if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number)) {
  549. BC.Entry = SpillPlacement::MustSpill;
  550. ++Ins;
  551. } else if (Intf.first() < BI.FirstInstr) {
  552. BC.Entry = SpillPlacement::PrefSpill;
  553. ++Ins;
  554. } else if (Intf.first() < BI.LastInstr) {
  555. ++Ins;
  556. }
  557. // Abort if the spill cannot be inserted at the MBB' start
  558. if (((BC.Entry == SpillPlacement::MustSpill) ||
  559. (BC.Entry == SpillPlacement::PrefSpill)) &&
  560. SlotIndex::isEarlierInstr(BI.FirstInstr,
  561. SA->getFirstSplitPoint(BC.Number)))
  562. return false;
  563. }
  564. // Interference for the live-out value.
  565. if (BI.LiveOut) {
  566. if (Intf.last() >= SA->getLastSplitPoint(BC.Number)) {
  567. BC.Exit = SpillPlacement::MustSpill;
  568. ++Ins;
  569. } else if (Intf.last() > BI.LastInstr) {
  570. BC.Exit = SpillPlacement::PrefSpill;
  571. ++Ins;
  572. } else if (Intf.last() > BI.FirstInstr) {
  573. ++Ins;
  574. }
  575. }
  576. // Accumulate the total frequency of inserted spill code.
  577. while (Ins--)
  578. StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
  579. }
  580. Cost = StaticCost;
  581. // Add constraints for use-blocks. Note that these are the only constraints
  582. // that may add a positive bias, it is downhill from here.
  583. SpillPlacer->addConstraints(SplitConstraints);
  584. return SpillPlacer->scanActiveBundles();
  585. }
  586. /// addThroughConstraints - Add constraints and links to SpillPlacer from the
  587. /// live-through blocks in Blocks.
  588. bool RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
  589. ArrayRef<unsigned> Blocks) {
  590. const unsigned GroupSize = 8;
  591. SpillPlacement::BlockConstraint BCS[GroupSize];
  592. unsigned TBS[GroupSize];
  593. unsigned B = 0, T = 0;
  594. for (unsigned Number : Blocks) {
  595. Intf.moveToBlock(Number);
  596. if (!Intf.hasInterference()) {
  597. assert(T < GroupSize && "Array overflow");
  598. TBS[T] = Number;
  599. if (++T == GroupSize) {
  600. SpillPlacer->addLinks(ArrayRef(TBS, T));
  601. T = 0;
  602. }
  603. continue;
  604. }
  605. assert(B < GroupSize && "Array overflow");
  606. BCS[B].Number = Number;
  607. // Abort if the spill cannot be inserted at the MBB' start
  608. MachineBasicBlock *MBB = MF->getBlockNumbered(Number);
  609. auto FirstNonDebugInstr = MBB->getFirstNonDebugInstr();
  610. if (FirstNonDebugInstr != MBB->end() &&
  611. SlotIndex::isEarlierInstr(LIS->getInstructionIndex(*FirstNonDebugInstr),
  612. SA->getFirstSplitPoint(Number)))
  613. return false;
  614. // Interference for the live-in value.
  615. if (Intf.first() <= Indexes->getMBBStartIdx(Number))
  616. BCS[B].Entry = SpillPlacement::MustSpill;
  617. else
  618. BCS[B].Entry = SpillPlacement::PrefSpill;
  619. // Interference for the live-out value.
  620. if (Intf.last() >= SA->getLastSplitPoint(Number))
  621. BCS[B].Exit = SpillPlacement::MustSpill;
  622. else
  623. BCS[B].Exit = SpillPlacement::PrefSpill;
  624. if (++B == GroupSize) {
  625. SpillPlacer->addConstraints(ArrayRef(BCS, B));
  626. B = 0;
  627. }
  628. }
  629. SpillPlacer->addConstraints(ArrayRef(BCS, B));
  630. SpillPlacer->addLinks(ArrayRef(TBS, T));
  631. return true;
  632. }
  633. bool RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
  634. // Keep track of through blocks that have not been added to SpillPlacer.
  635. BitVector Todo = SA->getThroughBlocks();
  636. SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
  637. unsigned AddedTo = 0;
  638. #ifndef NDEBUG
  639. unsigned Visited = 0;
  640. #endif
  641. unsigned long Budget = GrowRegionComplexityBudget;
  642. while (true) {
  643. ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
  644. // Find new through blocks in the periphery of PrefRegBundles.
  645. for (unsigned Bundle : NewBundles) {
  646. // Look at all blocks connected to Bundle in the full graph.
  647. ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
  648. // Limit compilation time by bailing out after we use all our budget.
  649. if (Blocks.size() >= Budget)
  650. return false;
  651. Budget -= Blocks.size();
  652. for (unsigned Block : Blocks) {
  653. if (!Todo.test(Block))
  654. continue;
  655. Todo.reset(Block);
  656. // This is a new through block. Add it to SpillPlacer later.
  657. ActiveBlocks.push_back(Block);
  658. #ifndef NDEBUG
  659. ++Visited;
  660. #endif
  661. }
  662. }
  663. // Any new blocks to add?
  664. if (ActiveBlocks.size() == AddedTo)
  665. break;
  666. // Compute through constraints from the interference, or assume that all
  667. // through blocks prefer spilling when forming compact regions.
  668. auto NewBlocks = ArrayRef(ActiveBlocks).slice(AddedTo);
  669. if (Cand.PhysReg) {
  670. if (!addThroughConstraints(Cand.Intf, NewBlocks))
  671. return false;
  672. } else
  673. // Provide a strong negative bias on through blocks to prevent unwanted
  674. // liveness on loop backedges.
  675. SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
  676. AddedTo = ActiveBlocks.size();
  677. // Perhaps iterating can enable more bundles?
  678. SpillPlacer->iterate();
  679. }
  680. LLVM_DEBUG(dbgs() << ", v=" << Visited);
  681. return true;
  682. }
  683. /// calcCompactRegion - Compute the set of edge bundles that should be live
  684. /// when splitting the current live range into compact regions. Compact
  685. /// regions can be computed without looking at interference. They are the
  686. /// regions formed by removing all the live-through blocks from the live range.
  687. ///
  688. /// Returns false if the current live range is already compact, or if the
  689. /// compact regions would form single block regions anyway.
  690. bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
  691. // Without any through blocks, the live range is already compact.
  692. if (!SA->getNumThroughBlocks())
  693. return false;
  694. // Compact regions don't correspond to any physreg.
  695. Cand.reset(IntfCache, MCRegister::NoRegister);
  696. LLVM_DEBUG(dbgs() << "Compact region bundles");
  697. // Use the spill placer to determine the live bundles. GrowRegion pretends
  698. // that all the through blocks have interference when PhysReg is unset.
  699. SpillPlacer->prepare(Cand.LiveBundles);
  700. // The static split cost will be zero since Cand.Intf reports no interference.
  701. BlockFrequency Cost;
  702. if (!addSplitConstraints(Cand.Intf, Cost)) {
  703. LLVM_DEBUG(dbgs() << ", none.\n");
  704. return false;
  705. }
  706. if (!growRegion(Cand)) {
  707. LLVM_DEBUG(dbgs() << ", cannot spill all interferences.\n");
  708. return false;
  709. }
  710. SpillPlacer->finish();
  711. if (!Cand.LiveBundles.any()) {
  712. LLVM_DEBUG(dbgs() << ", none.\n");
  713. return false;
  714. }
  715. LLVM_DEBUG({
  716. for (int I : Cand.LiveBundles.set_bits())
  717. dbgs() << " EB#" << I;
  718. dbgs() << ".\n";
  719. });
  720. return true;
  721. }
  722. /// calcSpillCost - Compute how expensive it would be to split the live range in
  723. /// SA around all use blocks instead of forming bundle regions.
  724. BlockFrequency RAGreedy::calcSpillCost() {
  725. BlockFrequency Cost = 0;
  726. ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
  727. for (const SplitAnalysis::BlockInfo &BI : UseBlocks) {
  728. unsigned Number = BI.MBB->getNumber();
  729. // We normally only need one spill instruction - a load or a store.
  730. Cost += SpillPlacer->getBlockFrequency(Number);
  731. // Unless the value is redefined in the block.
  732. if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
  733. Cost += SpillPlacer->getBlockFrequency(Number);
  734. }
  735. return Cost;
  736. }
  737. /// calcGlobalSplitCost - Return the global split cost of following the split
  738. /// pattern in LiveBundles. This cost should be added to the local cost of the
  739. /// interference pattern in SplitConstraints.
  740. ///
  741. BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand,
  742. const AllocationOrder &Order) {
  743. BlockFrequency GlobalCost = 0;
  744. const BitVector &LiveBundles = Cand.LiveBundles;
  745. ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
  746. for (unsigned I = 0; I != UseBlocks.size(); ++I) {
  747. const SplitAnalysis::BlockInfo &BI = UseBlocks[I];
  748. SpillPlacement::BlockConstraint &BC = SplitConstraints[I];
  749. bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, false)];
  750. bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, true)];
  751. unsigned Ins = 0;
  752. Cand.Intf.moveToBlock(BC.Number);
  753. if (BI.LiveIn)
  754. Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
  755. if (BI.LiveOut)
  756. Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
  757. while (Ins--)
  758. GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
  759. }
  760. for (unsigned Number : Cand.ActiveBlocks) {
  761. bool RegIn = LiveBundles[Bundles->getBundle(Number, false)];
  762. bool RegOut = LiveBundles[Bundles->getBundle(Number, true)];
  763. if (!RegIn && !RegOut)
  764. continue;
  765. if (RegIn && RegOut) {
  766. // We need double spill code if this block has interference.
  767. Cand.Intf.moveToBlock(Number);
  768. if (Cand.Intf.hasInterference()) {
  769. GlobalCost += SpillPlacer->getBlockFrequency(Number);
  770. GlobalCost += SpillPlacer->getBlockFrequency(Number);
  771. }
  772. continue;
  773. }
  774. // live-in / stack-out or stack-in live-out.
  775. GlobalCost += SpillPlacer->getBlockFrequency(Number);
  776. }
  777. return GlobalCost;
  778. }
  779. /// splitAroundRegion - Split the current live range around the regions
  780. /// determined by BundleCand and GlobalCand.
  781. ///
  782. /// Before calling this function, GlobalCand and BundleCand must be initialized
  783. /// so each bundle is assigned to a valid candidate, or NoCand for the
  784. /// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
  785. /// objects must be initialized for the current live range, and intervals
  786. /// created for the used candidates.
  787. ///
  788. /// @param LREdit The LiveRangeEdit object handling the current split.
  789. /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
  790. /// must appear in this list.
  791. void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
  792. ArrayRef<unsigned> UsedCands) {
  793. // These are the intervals created for new global ranges. We may create more
  794. // intervals for local ranges.
  795. const unsigned NumGlobalIntvs = LREdit.size();
  796. LLVM_DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs
  797. << " globals.\n");
  798. assert(NumGlobalIntvs && "No global intervals configured");
  799. // Isolate even single instructions when dealing with a proper sub-class.
  800. // That guarantees register class inflation for the stack interval because it
  801. // is all copies.
  802. Register Reg = SA->getParent().reg();
  803. bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
  804. // First handle all the blocks with uses.
  805. ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
  806. for (const SplitAnalysis::BlockInfo &BI : UseBlocks) {
  807. unsigned Number = BI.MBB->getNumber();
  808. unsigned IntvIn = 0, IntvOut = 0;
  809. SlotIndex IntfIn, IntfOut;
  810. if (BI.LiveIn) {
  811. unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)];
  812. if (CandIn != NoCand) {
  813. GlobalSplitCandidate &Cand = GlobalCand[CandIn];
  814. IntvIn = Cand.IntvIdx;
  815. Cand.Intf.moveToBlock(Number);
  816. IntfIn = Cand.Intf.first();
  817. }
  818. }
  819. if (BI.LiveOut) {
  820. unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)];
  821. if (CandOut != NoCand) {
  822. GlobalSplitCandidate &Cand = GlobalCand[CandOut];
  823. IntvOut = Cand.IntvIdx;
  824. Cand.Intf.moveToBlock(Number);
  825. IntfOut = Cand.Intf.last();
  826. }
  827. }
  828. // Create separate intervals for isolated blocks with multiple uses.
  829. if (!IntvIn && !IntvOut) {
  830. LLVM_DEBUG(dbgs() << printMBBReference(*BI.MBB) << " isolated.\n");
  831. if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
  832. SE->splitSingleBlock(BI);
  833. continue;
  834. }
  835. if (IntvIn && IntvOut)
  836. SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
  837. else if (IntvIn)
  838. SE->splitRegInBlock(BI, IntvIn, IntfIn);
  839. else
  840. SE->splitRegOutBlock(BI, IntvOut, IntfOut);
  841. }
  842. // Handle live-through blocks. The relevant live-through blocks are stored in
  843. // the ActiveBlocks list with each candidate. We need to filter out
  844. // duplicates.
  845. BitVector Todo = SA->getThroughBlocks();
  846. for (unsigned UsedCand : UsedCands) {
  847. ArrayRef<unsigned> Blocks = GlobalCand[UsedCand].ActiveBlocks;
  848. for (unsigned Number : Blocks) {
  849. if (!Todo.test(Number))
  850. continue;
  851. Todo.reset(Number);
  852. unsigned IntvIn = 0, IntvOut = 0;
  853. SlotIndex IntfIn, IntfOut;
  854. unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)];
  855. if (CandIn != NoCand) {
  856. GlobalSplitCandidate &Cand = GlobalCand[CandIn];
  857. IntvIn = Cand.IntvIdx;
  858. Cand.Intf.moveToBlock(Number);
  859. IntfIn = Cand.Intf.first();
  860. }
  861. unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)];
  862. if (CandOut != NoCand) {
  863. GlobalSplitCandidate &Cand = GlobalCand[CandOut];
  864. IntvOut = Cand.IntvIdx;
  865. Cand.Intf.moveToBlock(Number);
  866. IntfOut = Cand.Intf.last();
  867. }
  868. if (!IntvIn && !IntvOut)
  869. continue;
  870. SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
  871. }
  872. }
  873. ++NumGlobalSplits;
  874. SmallVector<unsigned, 8> IntvMap;
  875. SE->finish(&IntvMap);
  876. DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
  877. unsigned OrigBlocks = SA->getNumLiveBlocks();
  878. // Sort out the new intervals created by splitting. We get four kinds:
  879. // - Remainder intervals should not be split again.
  880. // - Candidate intervals can be assigned to Cand.PhysReg.
  881. // - Block-local splits are candidates for local splitting.
  882. // - DCE leftovers should go back on the queue.
  883. for (unsigned I = 0, E = LREdit.size(); I != E; ++I) {
  884. const LiveInterval &Reg = LIS->getInterval(LREdit.get(I));
  885. // Ignore old intervals from DCE.
  886. if (ExtraInfo->getOrInitStage(Reg.reg()) != RS_New)
  887. continue;
  888. // Remainder interval. Don't try splitting again, spill if it doesn't
  889. // allocate.
  890. if (IntvMap[I] == 0) {
  891. ExtraInfo->setStage(Reg, RS_Spill);
  892. continue;
  893. }
  894. // Global intervals. Allow repeated splitting as long as the number of live
  895. // blocks is strictly decreasing.
  896. if (IntvMap[I] < NumGlobalIntvs) {
  897. if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
  898. LLVM_DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
  899. << " blocks as original.\n");
  900. // Don't allow repeated splitting as a safe guard against looping.
  901. ExtraInfo->setStage(Reg, RS_Split2);
  902. }
  903. continue;
  904. }
  905. // Other intervals are treated as new. This includes local intervals created
  906. // for blocks with multiple uses, and anything created by DCE.
  907. }
  908. if (VerifyEnabled)
  909. MF->verify(this, "After splitting live range around region");
  910. }
  911. MCRegister RAGreedy::tryRegionSplit(const LiveInterval &VirtReg,
  912. AllocationOrder &Order,
  913. SmallVectorImpl<Register> &NewVRegs) {
  914. if (!TRI->shouldRegionSplitForVirtReg(*MF, VirtReg))
  915. return MCRegister::NoRegister;
  916. unsigned NumCands = 0;
  917. BlockFrequency SpillCost = calcSpillCost();
  918. BlockFrequency BestCost;
  919. // Check if we can split this live range around a compact region.
  920. bool HasCompact = calcCompactRegion(GlobalCand.front());
  921. if (HasCompact) {
  922. // Yes, keep GlobalCand[0] as the compact region candidate.
  923. NumCands = 1;
  924. BestCost = BlockFrequency::getMaxFrequency();
  925. } else {
  926. // No benefit from the compact region, our fallback will be per-block
  927. // splitting. Make sure we find a solution that is cheaper than spilling.
  928. BestCost = SpillCost;
  929. LLVM_DEBUG(dbgs() << "Cost of isolating all blocks = ";
  930. MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
  931. }
  932. unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
  933. NumCands, false /*IgnoreCSR*/);
  934. // No solutions found, fall back to single block splitting.
  935. if (!HasCompact && BestCand == NoCand)
  936. return MCRegister::NoRegister;
  937. return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
  938. }
  939. unsigned RAGreedy::calculateRegionSplitCost(const LiveInterval &VirtReg,
  940. AllocationOrder &Order,
  941. BlockFrequency &BestCost,
  942. unsigned &NumCands,
  943. bool IgnoreCSR) {
  944. unsigned BestCand = NoCand;
  945. for (MCPhysReg PhysReg : Order) {
  946. assert(PhysReg);
  947. if (IgnoreCSR && EvictAdvisor->isUnusedCalleeSavedReg(PhysReg))
  948. continue;
  949. // Discard bad candidates before we run out of interference cache cursors.
  950. // This will only affect register classes with a lot of registers (>32).
  951. if (NumCands == IntfCache.getMaxCursors()) {
  952. unsigned WorstCount = ~0u;
  953. unsigned Worst = 0;
  954. for (unsigned CandIndex = 0; CandIndex != NumCands; ++CandIndex) {
  955. if (CandIndex == BestCand || !GlobalCand[CandIndex].PhysReg)
  956. continue;
  957. unsigned Count = GlobalCand[CandIndex].LiveBundles.count();
  958. if (Count < WorstCount) {
  959. Worst = CandIndex;
  960. WorstCount = Count;
  961. }
  962. }
  963. --NumCands;
  964. GlobalCand[Worst] = GlobalCand[NumCands];
  965. if (BestCand == NumCands)
  966. BestCand = Worst;
  967. }
  968. if (GlobalCand.size() <= NumCands)
  969. GlobalCand.resize(NumCands+1);
  970. GlobalSplitCandidate &Cand = GlobalCand[NumCands];
  971. Cand.reset(IntfCache, PhysReg);
  972. SpillPlacer->prepare(Cand.LiveBundles);
  973. BlockFrequency Cost;
  974. if (!addSplitConstraints(Cand.Intf, Cost)) {
  975. LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << "\tno positive bundles\n");
  976. continue;
  977. }
  978. LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << "\tstatic = ";
  979. MBFI->printBlockFreq(dbgs(), Cost));
  980. if (Cost >= BestCost) {
  981. LLVM_DEBUG({
  982. if (BestCand == NoCand)
  983. dbgs() << " worse than no bundles\n";
  984. else
  985. dbgs() << " worse than "
  986. << printReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
  987. });
  988. continue;
  989. }
  990. if (!growRegion(Cand)) {
  991. LLVM_DEBUG(dbgs() << ", cannot spill all interferences.\n");
  992. continue;
  993. }
  994. SpillPlacer->finish();
  995. // No live bundles, defer to splitSingleBlocks().
  996. if (!Cand.LiveBundles.any()) {
  997. LLVM_DEBUG(dbgs() << " no bundles.\n");
  998. continue;
  999. }
  1000. Cost += calcGlobalSplitCost(Cand, Order);
  1001. LLVM_DEBUG({
  1002. dbgs() << ", total = ";
  1003. MBFI->printBlockFreq(dbgs(), Cost) << " with bundles";
  1004. for (int I : Cand.LiveBundles.set_bits())
  1005. dbgs() << " EB#" << I;
  1006. dbgs() << ".\n";
  1007. });
  1008. if (Cost < BestCost) {
  1009. BestCand = NumCands;
  1010. BestCost = Cost;
  1011. }
  1012. ++NumCands;
  1013. }
  1014. return BestCand;
  1015. }
  1016. unsigned RAGreedy::doRegionSplit(const LiveInterval &VirtReg, unsigned BestCand,
  1017. bool HasCompact,
  1018. SmallVectorImpl<Register> &NewVRegs) {
  1019. SmallVector<unsigned, 8> UsedCands;
  1020. // Prepare split editor.
  1021. LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
  1022. SE->reset(LREdit, SplitSpillMode);
  1023. // Assign all edge bundles to the preferred candidate, or NoCand.
  1024. BundleCand.assign(Bundles->getNumBundles(), NoCand);
  1025. // Assign bundles for the best candidate region.
  1026. if (BestCand != NoCand) {
  1027. GlobalSplitCandidate &Cand = GlobalCand[BestCand];
  1028. if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
  1029. UsedCands.push_back(BestCand);
  1030. Cand.IntvIdx = SE->openIntv();
  1031. LLVM_DEBUG(dbgs() << "Split for " << printReg(Cand.PhysReg, TRI) << " in "
  1032. << B << " bundles, intv " << Cand.IntvIdx << ".\n");
  1033. (void)B;
  1034. }
  1035. }
  1036. // Assign bundles for the compact region.
  1037. if (HasCompact) {
  1038. GlobalSplitCandidate &Cand = GlobalCand.front();
  1039. assert(!Cand.PhysReg && "Compact region has no physreg");
  1040. if (unsigned B = Cand.getBundles(BundleCand, 0)) {
  1041. UsedCands.push_back(0);
  1042. Cand.IntvIdx = SE->openIntv();
  1043. LLVM_DEBUG(dbgs() << "Split for compact region in " << B
  1044. << " bundles, intv " << Cand.IntvIdx << ".\n");
  1045. (void)B;
  1046. }
  1047. }
  1048. splitAroundRegion(LREdit, UsedCands);
  1049. return 0;
  1050. }
  1051. //===----------------------------------------------------------------------===//
  1052. // Per-Block Splitting
  1053. //===----------------------------------------------------------------------===//
  1054. /// tryBlockSplit - Split a global live range around every block with uses. This
  1055. /// creates a lot of local live ranges, that will be split by tryLocalSplit if
  1056. /// they don't allocate.
  1057. unsigned RAGreedy::tryBlockSplit(const LiveInterval &VirtReg,
  1058. AllocationOrder &Order,
  1059. SmallVectorImpl<Register> &NewVRegs) {
  1060. assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
  1061. Register Reg = VirtReg.reg();
  1062. bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
  1063. LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
  1064. SE->reset(LREdit, SplitSpillMode);
  1065. ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
  1066. for (const SplitAnalysis::BlockInfo &BI : UseBlocks) {
  1067. if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
  1068. SE->splitSingleBlock(BI);
  1069. }
  1070. // No blocks were split.
  1071. if (LREdit.empty())
  1072. return 0;
  1073. // We did split for some blocks.
  1074. SmallVector<unsigned, 8> IntvMap;
  1075. SE->finish(&IntvMap);
  1076. // Tell LiveDebugVariables about the new ranges.
  1077. DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
  1078. // Sort out the new intervals created by splitting. The remainder interval
  1079. // goes straight to spilling, the new local ranges get to stay RS_New.
  1080. for (unsigned I = 0, E = LREdit.size(); I != E; ++I) {
  1081. const LiveInterval &LI = LIS->getInterval(LREdit.get(I));
  1082. if (ExtraInfo->getOrInitStage(LI.reg()) == RS_New && IntvMap[I] == 0)
  1083. ExtraInfo->setStage(LI, RS_Spill);
  1084. }
  1085. if (VerifyEnabled)
  1086. MF->verify(this, "After splitting live range around basic blocks");
  1087. return 0;
  1088. }
  1089. //===----------------------------------------------------------------------===//
  1090. // Per-Instruction Splitting
  1091. //===----------------------------------------------------------------------===//
  1092. /// Get the number of allocatable registers that match the constraints of \p Reg
  1093. /// on \p MI and that are also in \p SuperRC.
  1094. static unsigned getNumAllocatableRegsForConstraints(
  1095. const MachineInstr *MI, Register Reg, const TargetRegisterClass *SuperRC,
  1096. const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
  1097. const RegisterClassInfo &RCI) {
  1098. assert(SuperRC && "Invalid register class");
  1099. const TargetRegisterClass *ConstrainedRC =
  1100. MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI,
  1101. /* ExploreBundle */ true);
  1102. if (!ConstrainedRC)
  1103. return 0;
  1104. return RCI.getNumAllocatableRegs(ConstrainedRC);
  1105. }
  1106. static LaneBitmask getInstReadLaneMask(const MachineRegisterInfo &MRI,
  1107. const TargetRegisterInfo &TRI,
  1108. const MachineInstr &MI, Register Reg) {
  1109. LaneBitmask Mask;
  1110. for (const MachineOperand &MO : MI.operands()) {
  1111. if (!MO.isReg() || MO.getReg() != Reg)
  1112. continue;
  1113. unsigned SubReg = MO.getSubReg();
  1114. if (SubReg == 0 && MO.isUse()) {
  1115. Mask |= MRI.getMaxLaneMaskForVReg(Reg);
  1116. continue;
  1117. }
  1118. LaneBitmask SubRegMask = TRI.getSubRegIndexLaneMask(SubReg);
  1119. if (MO.isDef()) {
  1120. if (!MO.isUndef())
  1121. Mask |= ~SubRegMask;
  1122. } else
  1123. Mask |= SubRegMask;
  1124. }
  1125. return Mask;
  1126. }
  1127. /// Return true if \p MI at \P Use reads a subset of the lanes live in \p
  1128. /// VirtReg.
  1129. static bool readsLaneSubset(const MachineRegisterInfo &MRI,
  1130. const MachineInstr *MI, const LiveInterval &VirtReg,
  1131. const TargetRegisterInfo *TRI, SlotIndex Use) {
  1132. // Early check the common case.
  1133. if (MI->isCopy() &&
  1134. MI->getOperand(0).getSubReg() == MI->getOperand(1).getSubReg())
  1135. return false;
  1136. // FIXME: We're only considering uses, but should be consider defs too?
  1137. LaneBitmask ReadMask = getInstReadLaneMask(MRI, *TRI, *MI, VirtReg.reg());
  1138. LaneBitmask LiveAtMask;
  1139. for (const LiveInterval::SubRange &S : VirtReg.subranges()) {
  1140. if (S.liveAt(Use))
  1141. LiveAtMask |= S.LaneMask;
  1142. }
  1143. // If the live lanes aren't different from the lanes used by the instruction,
  1144. // this doesn't help.
  1145. return (ReadMask & ~(LiveAtMask & TRI->getCoveringLanes())).any();
  1146. }
  1147. /// tryInstructionSplit - Split a live range around individual instructions.
  1148. /// This is normally not worthwhile since the spiller is doing essentially the
  1149. /// same thing. However, when the live range is in a constrained register
  1150. /// class, it may help to insert copies such that parts of the live range can
  1151. /// be moved to a larger register class.
  1152. ///
  1153. /// This is similar to spilling to a larger register class.
  1154. unsigned RAGreedy::tryInstructionSplit(const LiveInterval &VirtReg,
  1155. AllocationOrder &Order,
  1156. SmallVectorImpl<Register> &NewVRegs) {
  1157. const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg());
  1158. // There is no point to this if there are no larger sub-classes.
  1159. bool SplitSubClass = true;
  1160. if (!RegClassInfo.isProperSubClass(CurRC)) {
  1161. if (!VirtReg.hasSubRanges())
  1162. return 0;
  1163. SplitSubClass = false;
  1164. }
  1165. // Always enable split spill mode, since we're effectively spilling to a
  1166. // register.
  1167. LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
  1168. SE->reset(LREdit, SplitEditor::SM_Size);
  1169. ArrayRef<SlotIndex> Uses = SA->getUseSlots();
  1170. if (Uses.size() <= 1)
  1171. return 0;
  1172. LLVM_DEBUG(dbgs() << "Split around " << Uses.size()
  1173. << " individual instrs.\n");
  1174. const TargetRegisterClass *SuperRC =
  1175. TRI->getLargestLegalSuperClass(CurRC, *MF);
  1176. unsigned SuperRCNumAllocatableRegs =
  1177. RegClassInfo.getNumAllocatableRegs(SuperRC);
  1178. // Split around every non-copy instruction if this split will relax
  1179. // the constraints on the virtual register.
  1180. // Otherwise, splitting just inserts uncoalescable copies that do not help
  1181. // the allocation.
  1182. for (const SlotIndex Use : Uses) {
  1183. if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Use)) {
  1184. if (MI->isFullCopy() ||
  1185. (SplitSubClass &&
  1186. SuperRCNumAllocatableRegs ==
  1187. getNumAllocatableRegsForConstraints(MI, VirtReg.reg(), SuperRC,
  1188. TII, TRI, RegClassInfo)) ||
  1189. // TODO: Handle split for subranges with subclass constraints?
  1190. (!SplitSubClass && VirtReg.hasSubRanges() &&
  1191. !readsLaneSubset(*MRI, MI, VirtReg, TRI, Use))) {
  1192. LLVM_DEBUG(dbgs() << " skip:\t" << Use << '\t' << *MI);
  1193. continue;
  1194. }
  1195. }
  1196. SE->openIntv();
  1197. SlotIndex SegStart = SE->enterIntvBefore(Use);
  1198. SlotIndex SegStop = SE->leaveIntvAfter(Use);
  1199. SE->useIntv(SegStart, SegStop);
  1200. }
  1201. if (LREdit.empty()) {
  1202. LLVM_DEBUG(dbgs() << "All uses were copies.\n");
  1203. return 0;
  1204. }
  1205. SmallVector<unsigned, 8> IntvMap;
  1206. SE->finish(&IntvMap);
  1207. DebugVars->splitRegister(VirtReg.reg(), LREdit.regs(), *LIS);
  1208. // Assign all new registers to RS_Spill. This was the last chance.
  1209. ExtraInfo->setStage(LREdit.begin(), LREdit.end(), RS_Spill);
  1210. return 0;
  1211. }
  1212. //===----------------------------------------------------------------------===//
  1213. // Local Splitting
  1214. //===----------------------------------------------------------------------===//
  1215. /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
  1216. /// in order to use PhysReg between two entries in SA->UseSlots.
  1217. ///
  1218. /// GapWeight[I] represents the gap between UseSlots[I] and UseSlots[I + 1].
  1219. ///
  1220. void RAGreedy::calcGapWeights(MCRegister PhysReg,
  1221. SmallVectorImpl<float> &GapWeight) {
  1222. assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
  1223. const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
  1224. ArrayRef<SlotIndex> Uses = SA->getUseSlots();
  1225. const unsigned NumGaps = Uses.size()-1;
  1226. // Start and end points for the interference check.
  1227. SlotIndex StartIdx =
  1228. BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
  1229. SlotIndex StopIdx =
  1230. BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
  1231. GapWeight.assign(NumGaps, 0.0f);
  1232. // Add interference from each overlapping register.
  1233. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
  1234. if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
  1235. .checkInterference())
  1236. continue;
  1237. // We know that VirtReg is a continuous interval from FirstInstr to
  1238. // LastInstr, so we don't need InterferenceQuery.
  1239. //
  1240. // Interference that overlaps an instruction is counted in both gaps
  1241. // surrounding the instruction. The exception is interference before
  1242. // StartIdx and after StopIdx.
  1243. //
  1244. LiveIntervalUnion::SegmentIter IntI =
  1245. Matrix->getLiveUnions()[*Units] .find(StartIdx);
  1246. for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
  1247. // Skip the gaps before IntI.
  1248. while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
  1249. if (++Gap == NumGaps)
  1250. break;
  1251. if (Gap == NumGaps)
  1252. break;
  1253. // Update the gaps covered by IntI.
  1254. const float weight = IntI.value()->weight();
  1255. for (; Gap != NumGaps; ++Gap) {
  1256. GapWeight[Gap] = std::max(GapWeight[Gap], weight);
  1257. if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
  1258. break;
  1259. }
  1260. if (Gap == NumGaps)
  1261. break;
  1262. }
  1263. }
  1264. // Add fixed interference.
  1265. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
  1266. const LiveRange &LR = LIS->getRegUnit(*Units);
  1267. LiveRange::const_iterator I = LR.find(StartIdx);
  1268. LiveRange::const_iterator E = LR.end();
  1269. // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
  1270. for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
  1271. while (Uses[Gap+1].getBoundaryIndex() < I->start)
  1272. if (++Gap == NumGaps)
  1273. break;
  1274. if (Gap == NumGaps)
  1275. break;
  1276. for (; Gap != NumGaps; ++Gap) {
  1277. GapWeight[Gap] = huge_valf;
  1278. if (Uses[Gap+1].getBaseIndex() >= I->end)
  1279. break;
  1280. }
  1281. if (Gap == NumGaps)
  1282. break;
  1283. }
  1284. }
  1285. }
  1286. /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
  1287. /// basic block.
  1288. ///
  1289. unsigned RAGreedy::tryLocalSplit(const LiveInterval &VirtReg,
  1290. AllocationOrder &Order,
  1291. SmallVectorImpl<Register> &NewVRegs) {
  1292. // TODO: the function currently only handles a single UseBlock; it should be
  1293. // possible to generalize.
  1294. if (SA->getUseBlocks().size() != 1)
  1295. return 0;
  1296. const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
  1297. // Note that it is possible to have an interval that is live-in or live-out
  1298. // while only covering a single block - A phi-def can use undef values from
  1299. // predecessors, and the block could be a single-block loop.
  1300. // We don't bother doing anything clever about such a case, we simply assume
  1301. // that the interval is continuous from FirstInstr to LastInstr. We should
  1302. // make sure that we don't do anything illegal to such an interval, though.
  1303. ArrayRef<SlotIndex> Uses = SA->getUseSlots();
  1304. if (Uses.size() <= 2)
  1305. return 0;
  1306. const unsigned NumGaps = Uses.size()-1;
  1307. LLVM_DEBUG({
  1308. dbgs() << "tryLocalSplit: ";
  1309. for (const auto &Use : Uses)
  1310. dbgs() << ' ' << Use;
  1311. dbgs() << '\n';
  1312. });
  1313. // If VirtReg is live across any register mask operands, compute a list of
  1314. // gaps with register masks.
  1315. SmallVector<unsigned, 8> RegMaskGaps;
  1316. if (Matrix->checkRegMaskInterference(VirtReg)) {
  1317. // Get regmask slots for the whole block.
  1318. ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
  1319. LLVM_DEBUG(dbgs() << RMS.size() << " regmasks in block:");
  1320. // Constrain to VirtReg's live range.
  1321. unsigned RI =
  1322. llvm::lower_bound(RMS, Uses.front().getRegSlot()) - RMS.begin();
  1323. unsigned RE = RMS.size();
  1324. for (unsigned I = 0; I != NumGaps && RI != RE; ++I) {
  1325. // Look for Uses[I] <= RMS <= Uses[I + 1].
  1326. assert(!SlotIndex::isEarlierInstr(RMS[RI], Uses[I]));
  1327. if (SlotIndex::isEarlierInstr(Uses[I + 1], RMS[RI]))
  1328. continue;
  1329. // Skip a regmask on the same instruction as the last use. It doesn't
  1330. // overlap the live range.
  1331. if (SlotIndex::isSameInstr(Uses[I + 1], RMS[RI]) && I + 1 == NumGaps)
  1332. break;
  1333. LLVM_DEBUG(dbgs() << ' ' << RMS[RI] << ':' << Uses[I] << '-'
  1334. << Uses[I + 1]);
  1335. RegMaskGaps.push_back(I);
  1336. // Advance ri to the next gap. A regmask on one of the uses counts in
  1337. // both gaps.
  1338. while (RI != RE && SlotIndex::isEarlierInstr(RMS[RI], Uses[I + 1]))
  1339. ++RI;
  1340. }
  1341. LLVM_DEBUG(dbgs() << '\n');
  1342. }
  1343. // Since we allow local split results to be split again, there is a risk of
  1344. // creating infinite loops. It is tempting to require that the new live
  1345. // ranges have less instructions than the original. That would guarantee
  1346. // convergence, but it is too strict. A live range with 3 instructions can be
  1347. // split 2+3 (including the COPY), and we want to allow that.
  1348. //
  1349. // Instead we use these rules:
  1350. //
  1351. // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
  1352. // noop split, of course).
  1353. // 2. Require progress be made for ranges with getStage() == RS_Split2. All
  1354. // the new ranges must have fewer instructions than before the split.
  1355. // 3. New ranges with the same number of instructions are marked RS_Split2,
  1356. // smaller ranges are marked RS_New.
  1357. //
  1358. // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
  1359. // excessive splitting and infinite loops.
  1360. //
  1361. bool ProgressRequired = ExtraInfo->getStage(VirtReg) >= RS_Split2;
  1362. // Best split candidate.
  1363. unsigned BestBefore = NumGaps;
  1364. unsigned BestAfter = 0;
  1365. float BestDiff = 0;
  1366. const float blockFreq =
  1367. SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
  1368. (1.0f / MBFI->getEntryFreq());
  1369. SmallVector<float, 8> GapWeight;
  1370. for (MCPhysReg PhysReg : Order) {
  1371. assert(PhysReg);
  1372. // Keep track of the largest spill weight that would need to be evicted in
  1373. // order to make use of PhysReg between UseSlots[I] and UseSlots[I + 1].
  1374. calcGapWeights(PhysReg, GapWeight);
  1375. // Remove any gaps with regmask clobbers.
  1376. if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
  1377. for (unsigned I = 0, E = RegMaskGaps.size(); I != E; ++I)
  1378. GapWeight[RegMaskGaps[I]] = huge_valf;
  1379. // Try to find the best sequence of gaps to close.
  1380. // The new spill weight must be larger than any gap interference.
  1381. // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
  1382. unsigned SplitBefore = 0, SplitAfter = 1;
  1383. // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
  1384. // It is the spill weight that needs to be evicted.
  1385. float MaxGap = GapWeight[0];
  1386. while (true) {
  1387. // Live before/after split?
  1388. const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
  1389. const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
  1390. LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << ' ' << Uses[SplitBefore]
  1391. << '-' << Uses[SplitAfter] << " I=" << MaxGap);
  1392. // Stop before the interval gets so big we wouldn't be making progress.
  1393. if (!LiveBefore && !LiveAfter) {
  1394. LLVM_DEBUG(dbgs() << " all\n");
  1395. break;
  1396. }
  1397. // Should the interval be extended or shrunk?
  1398. bool Shrink = true;
  1399. // How many gaps would the new range have?
  1400. unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
  1401. // Legally, without causing looping?
  1402. bool Legal = !ProgressRequired || NewGaps < NumGaps;
  1403. if (Legal && MaxGap < huge_valf) {
  1404. // Estimate the new spill weight. Each instruction reads or writes the
  1405. // register. Conservatively assume there are no read-modify-write
  1406. // instructions.
  1407. //
  1408. // Try to guess the size of the new interval.
  1409. const float EstWeight = normalizeSpillWeight(
  1410. blockFreq * (NewGaps + 1),
  1411. Uses[SplitBefore].distance(Uses[SplitAfter]) +
  1412. (LiveBefore + LiveAfter) * SlotIndex::InstrDist,
  1413. 1);
  1414. // Would this split be possible to allocate?
  1415. // Never allocate all gaps, we wouldn't be making progress.
  1416. LLVM_DEBUG(dbgs() << " w=" << EstWeight);
  1417. if (EstWeight * Hysteresis >= MaxGap) {
  1418. Shrink = false;
  1419. float Diff = EstWeight - MaxGap;
  1420. if (Diff > BestDiff) {
  1421. LLVM_DEBUG(dbgs() << " (best)");
  1422. BestDiff = Hysteresis * Diff;
  1423. BestBefore = SplitBefore;
  1424. BestAfter = SplitAfter;
  1425. }
  1426. }
  1427. }
  1428. // Try to shrink.
  1429. if (Shrink) {
  1430. if (++SplitBefore < SplitAfter) {
  1431. LLVM_DEBUG(dbgs() << " shrink\n");
  1432. // Recompute the max when necessary.
  1433. if (GapWeight[SplitBefore - 1] >= MaxGap) {
  1434. MaxGap = GapWeight[SplitBefore];
  1435. for (unsigned I = SplitBefore + 1; I != SplitAfter; ++I)
  1436. MaxGap = std::max(MaxGap, GapWeight[I]);
  1437. }
  1438. continue;
  1439. }
  1440. MaxGap = 0;
  1441. }
  1442. // Try to extend the interval.
  1443. if (SplitAfter >= NumGaps) {
  1444. LLVM_DEBUG(dbgs() << " end\n");
  1445. break;
  1446. }
  1447. LLVM_DEBUG(dbgs() << " extend\n");
  1448. MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
  1449. }
  1450. }
  1451. // Didn't find any candidates?
  1452. if (BestBefore == NumGaps)
  1453. return 0;
  1454. LLVM_DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore] << '-'
  1455. << Uses[BestAfter] << ", " << BestDiff << ", "
  1456. << (BestAfter - BestBefore + 1) << " instrs\n");
  1457. LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
  1458. SE->reset(LREdit);
  1459. SE->openIntv();
  1460. SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
  1461. SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
  1462. SE->useIntv(SegStart, SegStop);
  1463. SmallVector<unsigned, 8> IntvMap;
  1464. SE->finish(&IntvMap);
  1465. DebugVars->splitRegister(VirtReg.reg(), LREdit.regs(), *LIS);
  1466. // If the new range has the same number of instructions as before, mark it as
  1467. // RS_Split2 so the next split will be forced to make progress. Otherwise,
  1468. // leave the new intervals as RS_New so they can compete.
  1469. bool LiveBefore = BestBefore != 0 || BI.LiveIn;
  1470. bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
  1471. unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
  1472. if (NewGaps >= NumGaps) {
  1473. LLVM_DEBUG(dbgs() << "Tagging non-progress ranges:");
  1474. assert(!ProgressRequired && "Didn't make progress when it was required.");
  1475. for (unsigned I = 0, E = IntvMap.size(); I != E; ++I)
  1476. if (IntvMap[I] == 1) {
  1477. ExtraInfo->setStage(LIS->getInterval(LREdit.get(I)), RS_Split2);
  1478. LLVM_DEBUG(dbgs() << ' ' << printReg(LREdit.get(I)));
  1479. }
  1480. LLVM_DEBUG(dbgs() << '\n');
  1481. }
  1482. ++NumLocalSplits;
  1483. return 0;
  1484. }
  1485. //===----------------------------------------------------------------------===//
  1486. // Live Range Splitting
  1487. //===----------------------------------------------------------------------===//
  1488. /// trySplit - Try to split VirtReg or one of its interferences, making it
  1489. /// assignable.
  1490. /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
  1491. unsigned RAGreedy::trySplit(const LiveInterval &VirtReg, AllocationOrder &Order,
  1492. SmallVectorImpl<Register> &NewVRegs,
  1493. const SmallVirtRegSet &FixedRegisters) {
  1494. // Ranges must be Split2 or less.
  1495. if (ExtraInfo->getStage(VirtReg) >= RS_Spill)
  1496. return 0;
  1497. // Local intervals are handled separately.
  1498. if (LIS->intervalIsInOneMBB(VirtReg)) {
  1499. NamedRegionTimer T("local_split", "Local Splitting", TimerGroupName,
  1500. TimerGroupDescription, TimePassesIsEnabled);
  1501. SA->analyze(&VirtReg);
  1502. Register PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
  1503. if (PhysReg || !NewVRegs.empty())
  1504. return PhysReg;
  1505. return tryInstructionSplit(VirtReg, Order, NewVRegs);
  1506. }
  1507. NamedRegionTimer T("global_split", "Global Splitting", TimerGroupName,
  1508. TimerGroupDescription, TimePassesIsEnabled);
  1509. SA->analyze(&VirtReg);
  1510. // First try to split around a region spanning multiple blocks. RS_Split2
  1511. // ranges already made dubious progress with region splitting, so they go
  1512. // straight to single block splitting.
  1513. if (ExtraInfo->getStage(VirtReg) < RS_Split2) {
  1514. MCRegister PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
  1515. if (PhysReg || !NewVRegs.empty())
  1516. return PhysReg;
  1517. }
  1518. // Then isolate blocks.
  1519. return tryBlockSplit(VirtReg, Order, NewVRegs);
  1520. }
  1521. //===----------------------------------------------------------------------===//
  1522. // Last Chance Recoloring
  1523. //===----------------------------------------------------------------------===//
  1524. /// Return true if \p reg has any tied def operand.
  1525. static bool hasTiedDef(MachineRegisterInfo *MRI, unsigned reg) {
  1526. for (const MachineOperand &MO : MRI->def_operands(reg))
  1527. if (MO.isTied())
  1528. return true;
  1529. return false;
  1530. }
  1531. /// Return true if the existing assignment of \p Intf overlaps, but is not the
  1532. /// same, as \p PhysReg.
  1533. static bool assignedRegPartiallyOverlaps(const TargetRegisterInfo &TRI,
  1534. const VirtRegMap &VRM,
  1535. MCRegister PhysReg,
  1536. const LiveInterval &Intf) {
  1537. MCRegister AssignedReg = VRM.getPhys(Intf.reg());
  1538. if (PhysReg == AssignedReg)
  1539. return false;
  1540. return TRI.regsOverlap(PhysReg, AssignedReg);
  1541. }
  1542. /// mayRecolorAllInterferences - Check if the virtual registers that
  1543. /// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be
  1544. /// recolored to free \p PhysReg.
  1545. /// When true is returned, \p RecoloringCandidates has been augmented with all
  1546. /// the live intervals that need to be recolored in order to free \p PhysReg
  1547. /// for \p VirtReg.
  1548. /// \p FixedRegisters contains all the virtual registers that cannot be
  1549. /// recolored.
  1550. bool RAGreedy::mayRecolorAllInterferences(
  1551. MCRegister PhysReg, const LiveInterval &VirtReg,
  1552. SmallLISet &RecoloringCandidates, const SmallVirtRegSet &FixedRegisters) {
  1553. const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg());
  1554. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
  1555. LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
  1556. // If there is LastChanceRecoloringMaxInterference or more interferences,
  1557. // chances are one would not be recolorable.
  1558. if (Q.interferingVRegs(LastChanceRecoloringMaxInterference).size() >=
  1559. LastChanceRecoloringMaxInterference &&
  1560. !ExhaustiveSearch) {
  1561. LLVM_DEBUG(dbgs() << "Early abort: too many interferences.\n");
  1562. CutOffInfo |= CO_Interf;
  1563. return false;
  1564. }
  1565. for (const LiveInterval *Intf : reverse(Q.interferingVRegs())) {
  1566. // If Intf is done and sits on the same register class as VirtReg, it
  1567. // would not be recolorable as it is in the same state as
  1568. // VirtReg. However there are at least two exceptions.
  1569. //
  1570. // If VirtReg has tied defs and Intf doesn't, then
  1571. // there is still a point in examining if it can be recolorable.
  1572. //
  1573. // Additionally, if the register class has overlapping tuple members, it
  1574. // may still be recolorable using a different tuple. This is more likely
  1575. // if the existing assignment aliases with the candidate.
  1576. //
  1577. if (((ExtraInfo->getStage(*Intf) == RS_Done &&
  1578. MRI->getRegClass(Intf->reg()) == CurRC &&
  1579. !assignedRegPartiallyOverlaps(*TRI, *VRM, PhysReg, *Intf)) &&
  1580. !(hasTiedDef(MRI, VirtReg.reg()) &&
  1581. !hasTiedDef(MRI, Intf->reg()))) ||
  1582. FixedRegisters.count(Intf->reg())) {
  1583. LLVM_DEBUG(
  1584. dbgs() << "Early abort: the interference is not recolorable.\n");
  1585. return false;
  1586. }
  1587. RecoloringCandidates.insert(Intf);
  1588. }
  1589. }
  1590. return true;
  1591. }
  1592. /// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
  1593. /// its interferences.
  1594. /// Last chance recoloring chooses a color for \p VirtReg and recolors every
  1595. /// virtual register that was using it. The recoloring process may recursively
  1596. /// use the last chance recoloring. Therefore, when a virtual register has been
  1597. /// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
  1598. /// be last-chance-recolored again during this recoloring "session".
  1599. /// E.g.,
  1600. /// Let
  1601. /// vA can use {R1, R2 }
  1602. /// vB can use { R2, R3}
  1603. /// vC can use {R1 }
  1604. /// Where vA, vB, and vC cannot be split anymore (they are reloads for
  1605. /// instance) and they all interfere.
  1606. ///
  1607. /// vA is assigned R1
  1608. /// vB is assigned R2
  1609. /// vC tries to evict vA but vA is already done.
  1610. /// Regular register allocation fails.
  1611. ///
  1612. /// Last chance recoloring kicks in:
  1613. /// vC does as if vA was evicted => vC uses R1.
  1614. /// vC is marked as fixed.
  1615. /// vA needs to find a color.
  1616. /// None are available.
  1617. /// vA cannot evict vC: vC is a fixed virtual register now.
  1618. /// vA does as if vB was evicted => vA uses R2.
  1619. /// vB needs to find a color.
  1620. /// R3 is available.
  1621. /// Recoloring => vC = R1, vA = R2, vB = R3
  1622. ///
  1623. /// \p Order defines the preferred allocation order for \p VirtReg.
  1624. /// \p NewRegs will contain any new virtual register that have been created
  1625. /// (split, spill) during the process and that must be assigned.
  1626. /// \p FixedRegisters contains all the virtual registers that cannot be
  1627. /// recolored.
  1628. ///
  1629. /// \p RecolorStack tracks the original assignments of successfully recolored
  1630. /// registers.
  1631. ///
  1632. /// \p Depth gives the current depth of the last chance recoloring.
  1633. /// \return a physical register that can be used for VirtReg or ~0u if none
  1634. /// exists.
  1635. unsigned RAGreedy::tryLastChanceRecoloring(const LiveInterval &VirtReg,
  1636. AllocationOrder &Order,
  1637. SmallVectorImpl<Register> &NewVRegs,
  1638. SmallVirtRegSet &FixedRegisters,
  1639. RecoloringStack &RecolorStack,
  1640. unsigned Depth) {
  1641. if (!TRI->shouldUseLastChanceRecoloringForVirtReg(*MF, VirtReg))
  1642. return ~0u;
  1643. LLVM_DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
  1644. const ssize_t EntryStackSize = RecolorStack.size();
  1645. // Ranges must be Done.
  1646. assert((ExtraInfo->getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
  1647. "Last chance recoloring should really be last chance");
  1648. // Set the max depth to LastChanceRecoloringMaxDepth.
  1649. // We may want to reconsider that if we end up with a too large search space
  1650. // for target with hundreds of registers.
  1651. // Indeed, in that case we may want to cut the search space earlier.
  1652. if (Depth >= LastChanceRecoloringMaxDepth && !ExhaustiveSearch) {
  1653. LLVM_DEBUG(dbgs() << "Abort because max depth has been reached.\n");
  1654. CutOffInfo |= CO_Depth;
  1655. return ~0u;
  1656. }
  1657. // Set of Live intervals that will need to be recolored.
  1658. SmallLISet RecoloringCandidates;
  1659. // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in
  1660. // this recoloring "session".
  1661. assert(!FixedRegisters.count(VirtReg.reg()));
  1662. FixedRegisters.insert(VirtReg.reg());
  1663. SmallVector<Register, 4> CurrentNewVRegs;
  1664. for (MCRegister PhysReg : Order) {
  1665. assert(PhysReg.isValid());
  1666. LLVM_DEBUG(dbgs() << "Try to assign: " << VirtReg << " to "
  1667. << printReg(PhysReg, TRI) << '\n');
  1668. RecoloringCandidates.clear();
  1669. CurrentNewVRegs.clear();
  1670. // It is only possible to recolor virtual register interference.
  1671. if (Matrix->checkInterference(VirtReg, PhysReg) >
  1672. LiveRegMatrix::IK_VirtReg) {
  1673. LLVM_DEBUG(
  1674. dbgs() << "Some interferences are not with virtual registers.\n");
  1675. continue;
  1676. }
  1677. // Early give up on this PhysReg if it is obvious we cannot recolor all
  1678. // the interferences.
  1679. if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
  1680. FixedRegisters)) {
  1681. LLVM_DEBUG(dbgs() << "Some interferences cannot be recolored.\n");
  1682. continue;
  1683. }
  1684. // RecoloringCandidates contains all the virtual registers that interfere
  1685. // with VirtReg on PhysReg (or one of its aliases). Enqueue them for
  1686. // recoloring and perform the actual recoloring.
  1687. PQueue RecoloringQueue;
  1688. for (const LiveInterval *RC : RecoloringCandidates) {
  1689. Register ItVirtReg = RC->reg();
  1690. enqueue(RecoloringQueue, RC);
  1691. assert(VRM->hasPhys(ItVirtReg) &&
  1692. "Interferences are supposed to be with allocated variables");
  1693. // Record the current allocation.
  1694. RecolorStack.push_back(std::make_pair(RC, VRM->getPhys(ItVirtReg)));
  1695. // unset the related struct.
  1696. Matrix->unassign(*RC);
  1697. }
  1698. // Do as if VirtReg was assigned to PhysReg so that the underlying
  1699. // recoloring has the right information about the interferes and
  1700. // available colors.
  1701. Matrix->assign(VirtReg, PhysReg);
  1702. // Save the current recoloring state.
  1703. // If we cannot recolor all the interferences, we will have to start again
  1704. // at this point for the next physical register.
  1705. SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
  1706. if (tryRecoloringCandidates(RecoloringQueue, CurrentNewVRegs,
  1707. FixedRegisters, RecolorStack, Depth)) {
  1708. // Push the queued vregs into the main queue.
  1709. for (Register NewVReg : CurrentNewVRegs)
  1710. NewVRegs.push_back(NewVReg);
  1711. // Do not mess up with the global assignment process.
  1712. // I.e., VirtReg must be unassigned.
  1713. Matrix->unassign(VirtReg);
  1714. return PhysReg;
  1715. }
  1716. LLVM_DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to "
  1717. << printReg(PhysReg, TRI) << '\n');
  1718. // The recoloring attempt failed, undo the changes.
  1719. FixedRegisters = SaveFixedRegisters;
  1720. Matrix->unassign(VirtReg);
  1721. // For a newly created vreg which is also in RecoloringCandidates,
  1722. // don't add it to NewVRegs because its physical register will be restored
  1723. // below. Other vregs in CurrentNewVRegs are created by calling
  1724. // selectOrSplit and should be added into NewVRegs.
  1725. for (Register &R : CurrentNewVRegs) {
  1726. if (RecoloringCandidates.count(&LIS->getInterval(R)))
  1727. continue;
  1728. NewVRegs.push_back(R);
  1729. }
  1730. // Roll back our unsuccessful recoloring. Also roll back any successful
  1731. // recolorings in any recursive recoloring attempts, since it's possible
  1732. // they would have introduced conflicts with assignments we will be
  1733. // restoring further up the stack. Perform all unassignments prior to
  1734. // reassigning, since sub-recolorings may have conflicted with the registers
  1735. // we are going to restore to their original assignments.
  1736. for (ssize_t I = RecolorStack.size() - 1; I >= EntryStackSize; --I) {
  1737. const LiveInterval *LI;
  1738. MCRegister PhysReg;
  1739. std::tie(LI, PhysReg) = RecolorStack[I];
  1740. if (VRM->hasPhys(LI->reg()))
  1741. Matrix->unassign(*LI);
  1742. }
  1743. for (size_t I = EntryStackSize; I != RecolorStack.size(); ++I) {
  1744. const LiveInterval *LI;
  1745. MCRegister PhysReg;
  1746. std::tie(LI, PhysReg) = RecolorStack[I];
  1747. if (!LI->empty() && !MRI->reg_nodbg_empty(LI->reg()))
  1748. Matrix->assign(*LI, PhysReg);
  1749. }
  1750. // Pop the stack of recoloring attempts.
  1751. RecolorStack.resize(EntryStackSize);
  1752. }
  1753. // Last chance recoloring did not worked either, give up.
  1754. return ~0u;
  1755. }
  1756. /// tryRecoloringCandidates - Try to assign a new color to every register
  1757. /// in \RecoloringQueue.
  1758. /// \p NewRegs will contain any new virtual register created during the
  1759. /// recoloring process.
  1760. /// \p FixedRegisters[in/out] contains all the registers that have been
  1761. /// recolored.
  1762. /// \return true if all virtual registers in RecoloringQueue were successfully
  1763. /// recolored, false otherwise.
  1764. bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
  1765. SmallVectorImpl<Register> &NewVRegs,
  1766. SmallVirtRegSet &FixedRegisters,
  1767. RecoloringStack &RecolorStack,
  1768. unsigned Depth) {
  1769. while (!RecoloringQueue.empty()) {
  1770. const LiveInterval *LI = dequeue(RecoloringQueue);
  1771. LLVM_DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
  1772. MCRegister PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters,
  1773. RecolorStack, Depth + 1);
  1774. // When splitting happens, the live-range may actually be empty.
  1775. // In that case, this is okay to continue the recoloring even
  1776. // if we did not find an alternative color for it. Indeed,
  1777. // there will not be anything to color for LI in the end.
  1778. if (PhysReg == ~0u || (!PhysReg && !LI->empty()))
  1779. return false;
  1780. if (!PhysReg) {
  1781. assert(LI->empty() && "Only empty live-range do not require a register");
  1782. LLVM_DEBUG(dbgs() << "Recoloring of " << *LI
  1783. << " succeeded. Empty LI.\n");
  1784. continue;
  1785. }
  1786. LLVM_DEBUG(dbgs() << "Recoloring of " << *LI
  1787. << " succeeded with: " << printReg(PhysReg, TRI) << '\n');
  1788. Matrix->assign(*LI, PhysReg);
  1789. FixedRegisters.insert(LI->reg());
  1790. }
  1791. return true;
  1792. }
  1793. //===----------------------------------------------------------------------===//
  1794. // Main Entry Point
  1795. //===----------------------------------------------------------------------===//
  1796. MCRegister RAGreedy::selectOrSplit(const LiveInterval &VirtReg,
  1797. SmallVectorImpl<Register> &NewVRegs) {
  1798. CutOffInfo = CO_None;
  1799. LLVMContext &Ctx = MF->getFunction().getContext();
  1800. SmallVirtRegSet FixedRegisters;
  1801. RecoloringStack RecolorStack;
  1802. MCRegister Reg =
  1803. selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters, RecolorStack);
  1804. if (Reg == ~0U && (CutOffInfo != CO_None)) {
  1805. uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf);
  1806. if (CutOffEncountered == CO_Depth)
  1807. Ctx.emitError("register allocation failed: maximum depth for recoloring "
  1808. "reached. Use -fexhaustive-register-search to skip "
  1809. "cutoffs");
  1810. else if (CutOffEncountered == CO_Interf)
  1811. Ctx.emitError("register allocation failed: maximum interference for "
  1812. "recoloring reached. Use -fexhaustive-register-search "
  1813. "to skip cutoffs");
  1814. else if (CutOffEncountered == (CO_Depth | CO_Interf))
  1815. Ctx.emitError("register allocation failed: maximum interference and "
  1816. "depth for recoloring reached. Use "
  1817. "-fexhaustive-register-search to skip cutoffs");
  1818. }
  1819. return Reg;
  1820. }
  1821. /// Using a CSR for the first time has a cost because it causes push|pop
  1822. /// to be added to prologue|epilogue. Splitting a cold section of the live
  1823. /// range can have lower cost than using the CSR for the first time;
  1824. /// Spilling a live range in the cold path can have lower cost than using
  1825. /// the CSR for the first time. Returns the physical register if we decide
  1826. /// to use the CSR; otherwise return 0.
  1827. MCRegister RAGreedy::tryAssignCSRFirstTime(
  1828. const LiveInterval &VirtReg, AllocationOrder &Order, MCRegister PhysReg,
  1829. uint8_t &CostPerUseLimit, SmallVectorImpl<Register> &NewVRegs) {
  1830. if (ExtraInfo->getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) {
  1831. // We choose spill over using the CSR for the first time if the spill cost
  1832. // is lower than CSRCost.
  1833. SA->analyze(&VirtReg);
  1834. if (calcSpillCost() >= CSRCost)
  1835. return PhysReg;
  1836. // We are going to spill, set CostPerUseLimit to 1 to make sure that
  1837. // we will not use a callee-saved register in tryEvict.
  1838. CostPerUseLimit = 1;
  1839. return 0;
  1840. }
  1841. if (ExtraInfo->getStage(VirtReg) < RS_Split) {
  1842. // We choose pre-splitting over using the CSR for the first time if
  1843. // the cost of splitting is lower than CSRCost.
  1844. SA->analyze(&VirtReg);
  1845. unsigned NumCands = 0;
  1846. BlockFrequency BestCost = CSRCost; // Don't modify CSRCost.
  1847. unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
  1848. NumCands, true /*IgnoreCSR*/);
  1849. if (BestCand == NoCand)
  1850. // Use the CSR if we can't find a region split below CSRCost.
  1851. return PhysReg;
  1852. // Perform the actual pre-splitting.
  1853. doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs);
  1854. return 0;
  1855. }
  1856. return PhysReg;
  1857. }
  1858. void RAGreedy::aboutToRemoveInterval(const LiveInterval &LI) {
  1859. // Do not keep invalid information around.
  1860. SetOfBrokenHints.remove(&LI);
  1861. }
  1862. void RAGreedy::initializeCSRCost() {
  1863. // We use the larger one out of the command-line option and the value report
  1864. // by TRI.
  1865. CSRCost = BlockFrequency(
  1866. std::max((unsigned)CSRFirstTimeCost, TRI->getCSRFirstUseCost()));
  1867. if (!CSRCost.getFrequency())
  1868. return;
  1869. // Raw cost is relative to Entry == 2^14; scale it appropriately.
  1870. uint64_t ActualEntry = MBFI->getEntryFreq();
  1871. if (!ActualEntry) {
  1872. CSRCost = 0;
  1873. return;
  1874. }
  1875. uint64_t FixedEntry = 1 << 14;
  1876. if (ActualEntry < FixedEntry)
  1877. CSRCost *= BranchProbability(ActualEntry, FixedEntry);
  1878. else if (ActualEntry <= UINT32_MAX)
  1879. // Invert the fraction and divide.
  1880. CSRCost /= BranchProbability(FixedEntry, ActualEntry);
  1881. else
  1882. // Can't use BranchProbability in general, since it takes 32-bit numbers.
  1883. CSRCost = CSRCost.getFrequency() * (ActualEntry / FixedEntry);
  1884. }
  1885. /// Collect the hint info for \p Reg.
  1886. /// The results are stored into \p Out.
  1887. /// \p Out is not cleared before being populated.
  1888. void RAGreedy::collectHintInfo(Register Reg, HintsInfo &Out) {
  1889. for (const MachineInstr &Instr : MRI->reg_nodbg_instructions(Reg)) {
  1890. if (!Instr.isFullCopy())
  1891. continue;
  1892. // Look for the other end of the copy.
  1893. Register OtherReg = Instr.getOperand(0).getReg();
  1894. if (OtherReg == Reg) {
  1895. OtherReg = Instr.getOperand(1).getReg();
  1896. if (OtherReg == Reg)
  1897. continue;
  1898. }
  1899. // Get the current assignment.
  1900. MCRegister OtherPhysReg =
  1901. OtherReg.isPhysical() ? OtherReg.asMCReg() : VRM->getPhys(OtherReg);
  1902. // Push the collected information.
  1903. Out.push_back(HintInfo(MBFI->getBlockFreq(Instr.getParent()), OtherReg,
  1904. OtherPhysReg));
  1905. }
  1906. }
  1907. /// Using the given \p List, compute the cost of the broken hints if
  1908. /// \p PhysReg was used.
  1909. /// \return The cost of \p List for \p PhysReg.
  1910. BlockFrequency RAGreedy::getBrokenHintFreq(const HintsInfo &List,
  1911. MCRegister PhysReg) {
  1912. BlockFrequency Cost = 0;
  1913. for (const HintInfo &Info : List) {
  1914. if (Info.PhysReg != PhysReg)
  1915. Cost += Info.Freq;
  1916. }
  1917. return Cost;
  1918. }
  1919. /// Using the register assigned to \p VirtReg, try to recolor
  1920. /// all the live ranges that are copy-related with \p VirtReg.
  1921. /// The recoloring is then propagated to all the live-ranges that have
  1922. /// been recolored and so on, until no more copies can be coalesced or
  1923. /// it is not profitable.
  1924. /// For a given live range, profitability is determined by the sum of the
  1925. /// frequencies of the non-identity copies it would introduce with the old
  1926. /// and new register.
  1927. void RAGreedy::tryHintRecoloring(const LiveInterval &VirtReg) {
  1928. // We have a broken hint, check if it is possible to fix it by
  1929. // reusing PhysReg for the copy-related live-ranges. Indeed, we evicted
  1930. // some register and PhysReg may be available for the other live-ranges.
  1931. SmallSet<Register, 4> Visited;
  1932. SmallVector<unsigned, 2> RecoloringCandidates;
  1933. HintsInfo Info;
  1934. Register Reg = VirtReg.reg();
  1935. MCRegister PhysReg = VRM->getPhys(Reg);
  1936. // Start the recoloring algorithm from the input live-interval, then
  1937. // it will propagate to the ones that are copy-related with it.
  1938. Visited.insert(Reg);
  1939. RecoloringCandidates.push_back(Reg);
  1940. LLVM_DEBUG(dbgs() << "Trying to reconcile hints for: " << printReg(Reg, TRI)
  1941. << '(' << printReg(PhysReg, TRI) << ")\n");
  1942. do {
  1943. Reg = RecoloringCandidates.pop_back_val();
  1944. // We cannot recolor physical register.
  1945. if (Reg.isPhysical())
  1946. continue;
  1947. // This may be a skipped class
  1948. if (!VRM->hasPhys(Reg)) {
  1949. assert(!ShouldAllocateClass(*TRI, *MRI->getRegClass(Reg)) &&
  1950. "We have an unallocated variable which should have been handled");
  1951. continue;
  1952. }
  1953. // Get the live interval mapped with this virtual register to be able
  1954. // to check for the interference with the new color.
  1955. LiveInterval &LI = LIS->getInterval(Reg);
  1956. MCRegister CurrPhys = VRM->getPhys(Reg);
  1957. // Check that the new color matches the register class constraints and
  1958. // that it is free for this live range.
  1959. if (CurrPhys != PhysReg && (!MRI->getRegClass(Reg)->contains(PhysReg) ||
  1960. Matrix->checkInterference(LI, PhysReg)))
  1961. continue;
  1962. LLVM_DEBUG(dbgs() << printReg(Reg, TRI) << '(' << printReg(CurrPhys, TRI)
  1963. << ") is recolorable.\n");
  1964. // Gather the hint info.
  1965. Info.clear();
  1966. collectHintInfo(Reg, Info);
  1967. // Check if recoloring the live-range will increase the cost of the
  1968. // non-identity copies.
  1969. if (CurrPhys != PhysReg) {
  1970. LLVM_DEBUG(dbgs() << "Checking profitability:\n");
  1971. BlockFrequency OldCopiesCost = getBrokenHintFreq(Info, CurrPhys);
  1972. BlockFrequency NewCopiesCost = getBrokenHintFreq(Info, PhysReg);
  1973. LLVM_DEBUG(dbgs() << "Old Cost: " << OldCopiesCost.getFrequency()
  1974. << "\nNew Cost: " << NewCopiesCost.getFrequency()
  1975. << '\n');
  1976. if (OldCopiesCost < NewCopiesCost) {
  1977. LLVM_DEBUG(dbgs() << "=> Not profitable.\n");
  1978. continue;
  1979. }
  1980. // At this point, the cost is either cheaper or equal. If it is
  1981. // equal, we consider this is profitable because it may expose
  1982. // more recoloring opportunities.
  1983. LLVM_DEBUG(dbgs() << "=> Profitable.\n");
  1984. // Recolor the live-range.
  1985. Matrix->unassign(LI);
  1986. Matrix->assign(LI, PhysReg);
  1987. }
  1988. // Push all copy-related live-ranges to keep reconciling the broken
  1989. // hints.
  1990. for (const HintInfo &HI : Info) {
  1991. if (Visited.insert(HI.Reg).second)
  1992. RecoloringCandidates.push_back(HI.Reg);
  1993. }
  1994. } while (!RecoloringCandidates.empty());
  1995. }
  1996. /// Try to recolor broken hints.
  1997. /// Broken hints may be repaired by recoloring when an evicted variable
  1998. /// freed up a register for a larger live-range.
  1999. /// Consider the following example:
  2000. /// BB1:
  2001. /// a =
  2002. /// b =
  2003. /// BB2:
  2004. /// ...
  2005. /// = b
  2006. /// = a
  2007. /// Let us assume b gets split:
  2008. /// BB1:
  2009. /// a =
  2010. /// b =
  2011. /// BB2:
  2012. /// c = b
  2013. /// ...
  2014. /// d = c
  2015. /// = d
  2016. /// = a
  2017. /// Because of how the allocation work, b, c, and d may be assigned different
  2018. /// colors. Now, if a gets evicted later:
  2019. /// BB1:
  2020. /// a =
  2021. /// st a, SpillSlot
  2022. /// b =
  2023. /// BB2:
  2024. /// c = b
  2025. /// ...
  2026. /// d = c
  2027. /// = d
  2028. /// e = ld SpillSlot
  2029. /// = e
  2030. /// This is likely that we can assign the same register for b, c, and d,
  2031. /// getting rid of 2 copies.
  2032. void RAGreedy::tryHintsRecoloring() {
  2033. for (const LiveInterval *LI : SetOfBrokenHints) {
  2034. assert(LI->reg().isVirtual() &&
  2035. "Recoloring is possible only for virtual registers");
  2036. // Some dead defs may be around (e.g., because of debug uses).
  2037. // Ignore those.
  2038. if (!VRM->hasPhys(LI->reg()))
  2039. continue;
  2040. tryHintRecoloring(*LI);
  2041. }
  2042. }
  2043. MCRegister RAGreedy::selectOrSplitImpl(const LiveInterval &VirtReg,
  2044. SmallVectorImpl<Register> &NewVRegs,
  2045. SmallVirtRegSet &FixedRegisters,
  2046. RecoloringStack &RecolorStack,
  2047. unsigned Depth) {
  2048. uint8_t CostPerUseLimit = uint8_t(~0u);
  2049. // First try assigning a free register.
  2050. auto Order =
  2051. AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
  2052. if (MCRegister PhysReg =
  2053. tryAssign(VirtReg, Order, NewVRegs, FixedRegisters)) {
  2054. // When NewVRegs is not empty, we may have made decisions such as evicting
  2055. // a virtual register, go with the earlier decisions and use the physical
  2056. // register.
  2057. if (CSRCost.getFrequency() &&
  2058. EvictAdvisor->isUnusedCalleeSavedReg(PhysReg) && NewVRegs.empty()) {
  2059. MCRegister CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
  2060. CostPerUseLimit, NewVRegs);
  2061. if (CSRReg || !NewVRegs.empty())
  2062. // Return now if we decide to use a CSR or create new vregs due to
  2063. // pre-splitting.
  2064. return CSRReg;
  2065. } else
  2066. return PhysReg;
  2067. }
  2068. LiveRangeStage Stage = ExtraInfo->getStage(VirtReg);
  2069. LLVM_DEBUG(dbgs() << StageName[Stage] << " Cascade "
  2070. << ExtraInfo->getCascade(VirtReg.reg()) << '\n');
  2071. // Try to evict a less worthy live range, but only for ranges from the primary
  2072. // queue. The RS_Split ranges already failed to do this, and they should not
  2073. // get a second chance until they have been split.
  2074. if (Stage != RS_Split)
  2075. if (Register PhysReg =
  2076. tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit,
  2077. FixedRegisters)) {
  2078. Register Hint = MRI->getSimpleHint(VirtReg.reg());
  2079. // If VirtReg has a hint and that hint is broken record this
  2080. // virtual register as a recoloring candidate for broken hint.
  2081. // Indeed, since we evicted a variable in its neighborhood it is
  2082. // likely we can at least partially recolor some of the
  2083. // copy-related live-ranges.
  2084. if (Hint && Hint != PhysReg)
  2085. SetOfBrokenHints.insert(&VirtReg);
  2086. return PhysReg;
  2087. }
  2088. assert((NewVRegs.empty() || Depth) && "Cannot append to existing NewVRegs");
  2089. // The first time we see a live range, don't try to split or spill.
  2090. // Wait until the second time, when all smaller ranges have been allocated.
  2091. // This gives a better picture of the interference to split around.
  2092. if (Stage < RS_Split) {
  2093. ExtraInfo->setStage(VirtReg, RS_Split);
  2094. LLVM_DEBUG(dbgs() << "wait for second round\n");
  2095. NewVRegs.push_back(VirtReg.reg());
  2096. return 0;
  2097. }
  2098. if (Stage < RS_Spill) {
  2099. // Try splitting VirtReg or interferences.
  2100. unsigned NewVRegSizeBefore = NewVRegs.size();
  2101. Register PhysReg = trySplit(VirtReg, Order, NewVRegs, FixedRegisters);
  2102. if (PhysReg || (NewVRegs.size() - NewVRegSizeBefore))
  2103. return PhysReg;
  2104. }
  2105. // If we couldn't allocate a register from spilling, there is probably some
  2106. // invalid inline assembly. The base class will report it.
  2107. if (Stage >= RS_Done || !VirtReg.isSpillable()) {
  2108. return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
  2109. RecolorStack, Depth);
  2110. }
  2111. // Finally spill VirtReg itself.
  2112. if ((EnableDeferredSpilling ||
  2113. TRI->shouldUseDeferredSpillingForVirtReg(*MF, VirtReg)) &&
  2114. ExtraInfo->getStage(VirtReg) < RS_Memory) {
  2115. // TODO: This is experimental and in particular, we do not model
  2116. // the live range splitting done by spilling correctly.
  2117. // We would need a deep integration with the spiller to do the
  2118. // right thing here. Anyway, that is still good for early testing.
  2119. ExtraInfo->setStage(VirtReg, RS_Memory);
  2120. LLVM_DEBUG(dbgs() << "Do as if this register is in memory\n");
  2121. NewVRegs.push_back(VirtReg.reg());
  2122. } else {
  2123. NamedRegionTimer T("spill", "Spiller", TimerGroupName,
  2124. TimerGroupDescription, TimePassesIsEnabled);
  2125. LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
  2126. spiller().spill(LRE);
  2127. ExtraInfo->setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
  2128. // Tell LiveDebugVariables about the new ranges. Ranges not being covered by
  2129. // the new regs are kept in LDV (still mapping to the old register), until
  2130. // we rewrite spilled locations in LDV at a later stage.
  2131. DebugVars->splitRegister(VirtReg.reg(), LRE.regs(), *LIS);
  2132. if (VerifyEnabled)
  2133. MF->verify(this, "After spilling");
  2134. }
  2135. // The live virtual register requesting allocation was spilled, so tell
  2136. // the caller not to allocate anything during this round.
  2137. return 0;
  2138. }
  2139. void RAGreedy::RAGreedyStats::report(MachineOptimizationRemarkMissed &R) {
  2140. using namespace ore;
  2141. if (Spills) {
  2142. R << NV("NumSpills", Spills) << " spills ";
  2143. R << NV("TotalSpillsCost", SpillsCost) << " total spills cost ";
  2144. }
  2145. if (FoldedSpills) {
  2146. R << NV("NumFoldedSpills", FoldedSpills) << " folded spills ";
  2147. R << NV("TotalFoldedSpillsCost", FoldedSpillsCost)
  2148. << " total folded spills cost ";
  2149. }
  2150. if (Reloads) {
  2151. R << NV("NumReloads", Reloads) << " reloads ";
  2152. R << NV("TotalReloadsCost", ReloadsCost) << " total reloads cost ";
  2153. }
  2154. if (FoldedReloads) {
  2155. R << NV("NumFoldedReloads", FoldedReloads) << " folded reloads ";
  2156. R << NV("TotalFoldedReloadsCost", FoldedReloadsCost)
  2157. << " total folded reloads cost ";
  2158. }
  2159. if (ZeroCostFoldedReloads)
  2160. R << NV("NumZeroCostFoldedReloads", ZeroCostFoldedReloads)
  2161. << " zero cost folded reloads ";
  2162. if (Copies) {
  2163. R << NV("NumVRCopies", Copies) << " virtual registers copies ";
  2164. R << NV("TotalCopiesCost", CopiesCost) << " total copies cost ";
  2165. }
  2166. }
  2167. RAGreedy::RAGreedyStats RAGreedy::computeStats(MachineBasicBlock &MBB) {
  2168. RAGreedyStats Stats;
  2169. const MachineFrameInfo &MFI = MF->getFrameInfo();
  2170. int FI;
  2171. auto isSpillSlotAccess = [&MFI](const MachineMemOperand *A) {
  2172. return MFI.isSpillSlotObjectIndex(cast<FixedStackPseudoSourceValue>(
  2173. A->getPseudoValue())->getFrameIndex());
  2174. };
  2175. auto isPatchpointInstr = [](const MachineInstr &MI) {
  2176. return MI.getOpcode() == TargetOpcode::PATCHPOINT ||
  2177. MI.getOpcode() == TargetOpcode::STACKMAP ||
  2178. MI.getOpcode() == TargetOpcode::STATEPOINT;
  2179. };
  2180. for (MachineInstr &MI : MBB) {
  2181. if (MI.isCopy()) {
  2182. const MachineOperand &Dest = MI.getOperand(0);
  2183. const MachineOperand &Src = MI.getOperand(1);
  2184. Register SrcReg = Src.getReg();
  2185. Register DestReg = Dest.getReg();
  2186. // Only count `COPY`s with a virtual register as source or destination.
  2187. if (SrcReg.isVirtual() || DestReg.isVirtual()) {
  2188. if (SrcReg.isVirtual()) {
  2189. SrcReg = VRM->getPhys(SrcReg);
  2190. if (Src.getSubReg())
  2191. SrcReg = TRI->getSubReg(SrcReg, Src.getSubReg());
  2192. }
  2193. if (DestReg.isVirtual()) {
  2194. DestReg = VRM->getPhys(DestReg);
  2195. if (Dest.getSubReg())
  2196. DestReg = TRI->getSubReg(DestReg, Dest.getSubReg());
  2197. }
  2198. if (SrcReg != DestReg)
  2199. ++Stats.Copies;
  2200. }
  2201. continue;
  2202. }
  2203. SmallVector<const MachineMemOperand *, 2> Accesses;
  2204. if (TII->isLoadFromStackSlot(MI, FI) && MFI.isSpillSlotObjectIndex(FI)) {
  2205. ++Stats.Reloads;
  2206. continue;
  2207. }
  2208. if (TII->isStoreToStackSlot(MI, FI) && MFI.isSpillSlotObjectIndex(FI)) {
  2209. ++Stats.Spills;
  2210. continue;
  2211. }
  2212. if (TII->hasLoadFromStackSlot(MI, Accesses) &&
  2213. llvm::any_of(Accesses, isSpillSlotAccess)) {
  2214. if (!isPatchpointInstr(MI)) {
  2215. Stats.FoldedReloads += Accesses.size();
  2216. continue;
  2217. }
  2218. // For statepoint there may be folded and zero cost folded stack reloads.
  2219. std::pair<unsigned, unsigned> NonZeroCostRange =
  2220. TII->getPatchpointUnfoldableRange(MI);
  2221. SmallSet<unsigned, 16> FoldedReloads;
  2222. SmallSet<unsigned, 16> ZeroCostFoldedReloads;
  2223. for (unsigned Idx = 0, E = MI.getNumOperands(); Idx < E; ++Idx) {
  2224. MachineOperand &MO = MI.getOperand(Idx);
  2225. if (!MO.isFI() || !MFI.isSpillSlotObjectIndex(MO.getIndex()))
  2226. continue;
  2227. if (Idx >= NonZeroCostRange.first && Idx < NonZeroCostRange.second)
  2228. FoldedReloads.insert(MO.getIndex());
  2229. else
  2230. ZeroCostFoldedReloads.insert(MO.getIndex());
  2231. }
  2232. // If stack slot is used in folded reload it is not zero cost then.
  2233. for (unsigned Slot : FoldedReloads)
  2234. ZeroCostFoldedReloads.erase(Slot);
  2235. Stats.FoldedReloads += FoldedReloads.size();
  2236. Stats.ZeroCostFoldedReloads += ZeroCostFoldedReloads.size();
  2237. continue;
  2238. }
  2239. Accesses.clear();
  2240. if (TII->hasStoreToStackSlot(MI, Accesses) &&
  2241. llvm::any_of(Accesses, isSpillSlotAccess)) {
  2242. Stats.FoldedSpills += Accesses.size();
  2243. }
  2244. }
  2245. // Set cost of collected statistic by multiplication to relative frequency of
  2246. // this basic block.
  2247. float RelFreq = MBFI->getBlockFreqRelativeToEntryBlock(&MBB);
  2248. Stats.ReloadsCost = RelFreq * Stats.Reloads;
  2249. Stats.FoldedReloadsCost = RelFreq * Stats.FoldedReloads;
  2250. Stats.SpillsCost = RelFreq * Stats.Spills;
  2251. Stats.FoldedSpillsCost = RelFreq * Stats.FoldedSpills;
  2252. Stats.CopiesCost = RelFreq * Stats.Copies;
  2253. return Stats;
  2254. }
  2255. RAGreedy::RAGreedyStats RAGreedy::reportStats(MachineLoop *L) {
  2256. RAGreedyStats Stats;
  2257. // Sum up the spill and reloads in subloops.
  2258. for (MachineLoop *SubLoop : *L)
  2259. Stats.add(reportStats(SubLoop));
  2260. for (MachineBasicBlock *MBB : L->getBlocks())
  2261. // Handle blocks that were not included in subloops.
  2262. if (Loops->getLoopFor(MBB) == L)
  2263. Stats.add(computeStats(*MBB));
  2264. if (!Stats.isEmpty()) {
  2265. using namespace ore;
  2266. ORE->emit([&]() {
  2267. MachineOptimizationRemarkMissed R(DEBUG_TYPE, "LoopSpillReloadCopies",
  2268. L->getStartLoc(), L->getHeader());
  2269. Stats.report(R);
  2270. R << "generated in loop";
  2271. return R;
  2272. });
  2273. }
  2274. return Stats;
  2275. }
  2276. void RAGreedy::reportStats() {
  2277. if (!ORE->allowExtraAnalysis(DEBUG_TYPE))
  2278. return;
  2279. RAGreedyStats Stats;
  2280. for (MachineLoop *L : *Loops)
  2281. Stats.add(reportStats(L));
  2282. // Process non-loop blocks.
  2283. for (MachineBasicBlock &MBB : *MF)
  2284. if (!Loops->getLoopFor(&MBB))
  2285. Stats.add(computeStats(MBB));
  2286. if (!Stats.isEmpty()) {
  2287. using namespace ore;
  2288. ORE->emit([&]() {
  2289. DebugLoc Loc;
  2290. if (auto *SP = MF->getFunction().getSubprogram())
  2291. Loc = DILocation::get(SP->getContext(), SP->getLine(), 1, SP);
  2292. MachineOptimizationRemarkMissed R(DEBUG_TYPE, "SpillReloadCopies", Loc,
  2293. &MF->front());
  2294. Stats.report(R);
  2295. R << "generated in function";
  2296. return R;
  2297. });
  2298. }
  2299. }
  2300. bool RAGreedy::hasVirtRegAlloc() {
  2301. for (unsigned I = 0, E = MRI->getNumVirtRegs(); I != E; ++I) {
  2302. Register Reg = Register::index2VirtReg(I);
  2303. if (MRI->reg_nodbg_empty(Reg))
  2304. continue;
  2305. const TargetRegisterClass *RC = MRI->getRegClass(Reg);
  2306. if (!RC)
  2307. continue;
  2308. if (ShouldAllocateClass(*TRI, *RC))
  2309. return true;
  2310. }
  2311. return false;
  2312. }
  2313. bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
  2314. LLVM_DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
  2315. << "********** Function: " << mf.getName() << '\n');
  2316. MF = &mf;
  2317. TII = MF->getSubtarget().getInstrInfo();
  2318. if (VerifyEnabled)
  2319. MF->verify(this, "Before greedy register allocator");
  2320. RegAllocBase::init(getAnalysis<VirtRegMap>(),
  2321. getAnalysis<LiveIntervals>(),
  2322. getAnalysis<LiveRegMatrix>());
  2323. // Early return if there is no virtual register to be allocated to a
  2324. // physical register.
  2325. if (!hasVirtRegAlloc())
  2326. return false;
  2327. Indexes = &getAnalysis<SlotIndexes>();
  2328. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  2329. DomTree = &getAnalysis<MachineDominatorTree>();
  2330. ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
  2331. Loops = &getAnalysis<MachineLoopInfo>();
  2332. Bundles = &getAnalysis<EdgeBundles>();
  2333. SpillPlacer = &getAnalysis<SpillPlacement>();
  2334. DebugVars = &getAnalysis<LiveDebugVariables>();
  2335. initializeCSRCost();
  2336. RegCosts = TRI->getRegisterCosts(*MF);
  2337. RegClassPriorityTrumpsGlobalness =
  2338. GreedyRegClassPriorityTrumpsGlobalness.getNumOccurrences()
  2339. ? GreedyRegClassPriorityTrumpsGlobalness
  2340. : TRI->regClassPriorityTrumpsGlobalness(*MF);
  2341. ReverseLocalAssignment = GreedyReverseLocalAssignment.getNumOccurrences()
  2342. ? GreedyReverseLocalAssignment
  2343. : TRI->reverseLocalAssignment();
  2344. ExtraInfo.emplace();
  2345. EvictAdvisor =
  2346. getAnalysis<RegAllocEvictionAdvisorAnalysis>().getAdvisor(*MF, *this);
  2347. PriorityAdvisor =
  2348. getAnalysis<RegAllocPriorityAdvisorAnalysis>().getAdvisor(*MF, *this);
  2349. VRAI = std::make_unique<VirtRegAuxInfo>(*MF, *LIS, *VRM, *Loops, *MBFI);
  2350. SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM, *VRAI));
  2351. VRAI->calculateSpillWeightsAndHints();
  2352. LLVM_DEBUG(LIS->dump());
  2353. SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
  2354. SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI, *VRAI));
  2355. IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
  2356. GlobalCand.resize(32); // This will grow as needed.
  2357. SetOfBrokenHints.clear();
  2358. allocatePhysRegs();
  2359. tryHintsRecoloring();
  2360. if (VerifyEnabled)
  2361. MF->verify(this, "Before post optimization");
  2362. postOptimization();
  2363. reportStats();
  2364. releaseMemory();
  2365. return true;
  2366. }