RegAllocBasic.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. //===-- RegAllocBasic.cpp - Basic 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 RABasic function pass, which provides a minimal
  10. // implementation of the basic register allocator.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "AllocationOrder.h"
  14. #include "LiveDebugVariables.h"
  15. #include "RegAllocBase.h"
  16. #include "llvm/Analysis/AliasAnalysis.h"
  17. #include "llvm/CodeGen/CalcSpillWeights.h"
  18. #include "llvm/CodeGen/LiveIntervals.h"
  19. #include "llvm/CodeGen/LiveRangeEdit.h"
  20. #include "llvm/CodeGen/LiveRegMatrix.h"
  21. #include "llvm/CodeGen/LiveStacks.h"
  22. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  23. #include "llvm/CodeGen/MachineFunctionPass.h"
  24. #include "llvm/CodeGen/MachineLoopInfo.h"
  25. #include "llvm/CodeGen/Passes.h"
  26. #include "llvm/CodeGen/RegAllocRegistry.h"
  27. #include "llvm/CodeGen/Spiller.h"
  28. #include "llvm/CodeGen/TargetRegisterInfo.h"
  29. #include "llvm/CodeGen/VirtRegMap.h"
  30. #include "llvm/Pass.h"
  31. #include "llvm/Support/Debug.h"
  32. #include "llvm/Support/raw_ostream.h"
  33. #include <queue>
  34. using namespace llvm;
  35. #define DEBUG_TYPE "regalloc"
  36. static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
  37. createBasicRegisterAllocator);
  38. namespace {
  39. struct CompSpillWeight {
  40. bool operator()(const LiveInterval *A, const LiveInterval *B) const {
  41. return A->weight() < B->weight();
  42. }
  43. };
  44. }
  45. namespace {
  46. /// RABasic provides a minimal implementation of the basic register allocation
  47. /// algorithm. It prioritizes live virtual registers by spill weight and spills
  48. /// whenever a register is unavailable. This is not practical in production but
  49. /// provides a useful baseline both for measuring other allocators and comparing
  50. /// the speed of the basic algorithm against other styles of allocators.
  51. class RABasic : public MachineFunctionPass,
  52. public RegAllocBase,
  53. private LiveRangeEdit::Delegate {
  54. // context
  55. MachineFunction *MF;
  56. // state
  57. std::unique_ptr<Spiller> SpillerInstance;
  58. std::priority_queue<const LiveInterval *, std::vector<const LiveInterval *>,
  59. CompSpillWeight>
  60. Queue;
  61. // Scratch space. Allocated here to avoid repeated malloc calls in
  62. // selectOrSplit().
  63. BitVector UsableRegs;
  64. bool LRE_CanEraseVirtReg(Register) override;
  65. void LRE_WillShrinkVirtReg(Register) override;
  66. public:
  67. RABasic(const RegClassFilterFunc F = allocateAllRegClasses);
  68. /// Return the pass name.
  69. StringRef getPassName() const override { return "Basic Register Allocator"; }
  70. /// RABasic analysis usage.
  71. void getAnalysisUsage(AnalysisUsage &AU) const override;
  72. void releaseMemory() override;
  73. Spiller &spiller() override { return *SpillerInstance; }
  74. void enqueueImpl(const LiveInterval *LI) override { Queue.push(LI); }
  75. const LiveInterval *dequeue() override {
  76. if (Queue.empty())
  77. return nullptr;
  78. const LiveInterval *LI = Queue.top();
  79. Queue.pop();
  80. return LI;
  81. }
  82. MCRegister selectOrSplit(const LiveInterval &VirtReg,
  83. SmallVectorImpl<Register> &SplitVRegs) override;
  84. /// Perform register allocation.
  85. bool runOnMachineFunction(MachineFunction &mf) override;
  86. MachineFunctionProperties getRequiredProperties() const override {
  87. return MachineFunctionProperties().set(
  88. MachineFunctionProperties::Property::NoPHIs);
  89. }
  90. MachineFunctionProperties getClearedProperties() const override {
  91. return MachineFunctionProperties().set(
  92. MachineFunctionProperties::Property::IsSSA);
  93. }
  94. // Helper for spilling all live virtual registers currently unified under preg
  95. // that interfere with the most recently queried lvr. Return true if spilling
  96. // was successful, and append any new spilled/split intervals to splitLVRs.
  97. bool spillInterferences(const LiveInterval &VirtReg, MCRegister PhysReg,
  98. SmallVectorImpl<Register> &SplitVRegs);
  99. static char ID;
  100. };
  101. char RABasic::ID = 0;
  102. } // end anonymous namespace
  103. char &llvm::RABasicID = RABasic::ID;
  104. INITIALIZE_PASS_BEGIN(RABasic, "regallocbasic", "Basic Register Allocator",
  105. false, false)
  106. INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
  107. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  108. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  109. INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
  110. INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
  111. INITIALIZE_PASS_DEPENDENCY(LiveStacks)
  112. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  113. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  114. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  115. INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
  116. INITIALIZE_PASS_DEPENDENCY(LiveRegMatrix)
  117. INITIALIZE_PASS_END(RABasic, "regallocbasic", "Basic Register Allocator", false,
  118. false)
  119. bool RABasic::LRE_CanEraseVirtReg(Register VirtReg) {
  120. LiveInterval &LI = LIS->getInterval(VirtReg);
  121. if (VRM->hasPhys(VirtReg)) {
  122. Matrix->unassign(LI);
  123. aboutToRemoveInterval(LI);
  124. return true;
  125. }
  126. // Unassigned virtreg is probably in the priority queue.
  127. // RegAllocBase will erase it after dequeueing.
  128. // Nonetheless, clear the live-range so that the debug
  129. // dump will show the right state for that VirtReg.
  130. LI.clear();
  131. return false;
  132. }
  133. void RABasic::LRE_WillShrinkVirtReg(Register VirtReg) {
  134. if (!VRM->hasPhys(VirtReg))
  135. return;
  136. // Register is assigned, put it back on the queue for reassignment.
  137. LiveInterval &LI = LIS->getInterval(VirtReg);
  138. Matrix->unassign(LI);
  139. enqueue(&LI);
  140. }
  141. RABasic::RABasic(RegClassFilterFunc F):
  142. MachineFunctionPass(ID),
  143. RegAllocBase(F) {
  144. }
  145. void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
  146. AU.setPreservesCFG();
  147. AU.addRequired<AAResultsWrapperPass>();
  148. AU.addPreserved<AAResultsWrapperPass>();
  149. AU.addRequired<LiveIntervals>();
  150. AU.addPreserved<LiveIntervals>();
  151. AU.addPreserved<SlotIndexes>();
  152. AU.addRequired<LiveDebugVariables>();
  153. AU.addPreserved<LiveDebugVariables>();
  154. AU.addRequired<LiveStacks>();
  155. AU.addPreserved<LiveStacks>();
  156. AU.addRequired<MachineBlockFrequencyInfo>();
  157. AU.addPreserved<MachineBlockFrequencyInfo>();
  158. AU.addRequiredID(MachineDominatorsID);
  159. AU.addPreservedID(MachineDominatorsID);
  160. AU.addRequired<MachineLoopInfo>();
  161. AU.addPreserved<MachineLoopInfo>();
  162. AU.addRequired<VirtRegMap>();
  163. AU.addPreserved<VirtRegMap>();
  164. AU.addRequired<LiveRegMatrix>();
  165. AU.addPreserved<LiveRegMatrix>();
  166. MachineFunctionPass::getAnalysisUsage(AU);
  167. }
  168. void RABasic::releaseMemory() {
  169. SpillerInstance.reset();
  170. }
  171. // Spill or split all live virtual registers currently unified under PhysReg
  172. // that interfere with VirtReg. The newly spilled or split live intervals are
  173. // returned by appending them to SplitVRegs.
  174. bool RABasic::spillInterferences(const LiveInterval &VirtReg,
  175. MCRegister PhysReg,
  176. SmallVectorImpl<Register> &SplitVRegs) {
  177. // Record each interference and determine if all are spillable before mutating
  178. // either the union or live intervals.
  179. SmallVector<const LiveInterval *, 8> Intfs;
  180. // Collect interferences assigned to any alias of the physical register.
  181. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
  182. LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
  183. for (const auto *Intf : reverse(Q.interferingVRegs())) {
  184. if (!Intf->isSpillable() || Intf->weight() > VirtReg.weight())
  185. return false;
  186. Intfs.push_back(Intf);
  187. }
  188. }
  189. LLVM_DEBUG(dbgs() << "spilling " << printReg(PhysReg, TRI)
  190. << " interferences with " << VirtReg << "\n");
  191. assert(!Intfs.empty() && "expected interference");
  192. // Spill each interfering vreg allocated to PhysReg or an alias.
  193. for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
  194. const LiveInterval &Spill = *Intfs[i];
  195. // Skip duplicates.
  196. if (!VRM->hasPhys(Spill.reg()))
  197. continue;
  198. // Deallocate the interfering vreg by removing it from the union.
  199. // A LiveInterval instance may not be in a union during modification!
  200. Matrix->unassign(Spill);
  201. // Spill the extracted interval.
  202. LiveRangeEdit LRE(&Spill, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
  203. spiller().spill(LRE);
  204. }
  205. return true;
  206. }
  207. // Driver for the register assignment and splitting heuristics.
  208. // Manages iteration over the LiveIntervalUnions.
  209. //
  210. // This is a minimal implementation of register assignment and splitting that
  211. // spills whenever we run out of registers.
  212. //
  213. // selectOrSplit can only be called once per live virtual register. We then do a
  214. // single interference test for each register the correct class until we find an
  215. // available register. So, the number of interference tests in the worst case is
  216. // |vregs| * |machineregs|. And since the number of interference tests is
  217. // minimal, there is no value in caching them outside the scope of
  218. // selectOrSplit().
  219. MCRegister RABasic::selectOrSplit(const LiveInterval &VirtReg,
  220. SmallVectorImpl<Register> &SplitVRegs) {
  221. // Populate a list of physical register spill candidates.
  222. SmallVector<MCRegister, 8> PhysRegSpillCands;
  223. // Check for an available register in this class.
  224. auto Order =
  225. AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
  226. for (MCRegister PhysReg : Order) {
  227. assert(PhysReg.isValid());
  228. // Check for interference in PhysReg
  229. switch (Matrix->checkInterference(VirtReg, PhysReg)) {
  230. case LiveRegMatrix::IK_Free:
  231. // PhysReg is available, allocate it.
  232. return PhysReg;
  233. case LiveRegMatrix::IK_VirtReg:
  234. // Only virtual registers in the way, we may be able to spill them.
  235. PhysRegSpillCands.push_back(PhysReg);
  236. continue;
  237. default:
  238. // RegMask or RegUnit interference.
  239. continue;
  240. }
  241. }
  242. // Try to spill another interfering reg with less spill weight.
  243. for (MCRegister &PhysReg : PhysRegSpillCands) {
  244. if (!spillInterferences(VirtReg, PhysReg, SplitVRegs))
  245. continue;
  246. assert(!Matrix->checkInterference(VirtReg, PhysReg) &&
  247. "Interference after spill.");
  248. // Tell the caller to allocate to this newly freed physical register.
  249. return PhysReg;
  250. }
  251. // No other spill candidates were found, so spill the current VirtReg.
  252. LLVM_DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
  253. if (!VirtReg.isSpillable())
  254. return ~0u;
  255. LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM, this, &DeadRemats);
  256. spiller().spill(LRE);
  257. // The live virtual register requesting allocation was spilled, so tell
  258. // the caller not to allocate anything during this round.
  259. return 0;
  260. }
  261. bool RABasic::runOnMachineFunction(MachineFunction &mf) {
  262. LLVM_DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
  263. << "********** Function: " << mf.getName() << '\n');
  264. MF = &mf;
  265. RegAllocBase::init(getAnalysis<VirtRegMap>(),
  266. getAnalysis<LiveIntervals>(),
  267. getAnalysis<LiveRegMatrix>());
  268. VirtRegAuxInfo VRAI(*MF, *LIS, *VRM, getAnalysis<MachineLoopInfo>(),
  269. getAnalysis<MachineBlockFrequencyInfo>());
  270. VRAI.calculateSpillWeightsAndHints();
  271. SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM, VRAI));
  272. allocatePhysRegs();
  273. postOptimization();
  274. // Diagnostic output before rewriting
  275. LLVM_DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
  276. releaseMemory();
  277. return true;
  278. }
  279. FunctionPass* llvm::createBasicRegisterAllocator() {
  280. return new RABasic();
  281. }
  282. FunctionPass* llvm::createBasicRegisterAllocator(RegClassFilterFunc F) {
  283. return new RABasic(F);
  284. }