RegAllocBasic.cpp 10 KB

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