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