Guard private fields that are unused in Release builds with #ifndef NDEBUG.
[oota-llvm.git] / lib / CodeGen / RegAllocBasic.cpp
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
15 #define DEBUG_TYPE "regalloc"
16 #include "RegAllocBase.h"
17 #include "LiveDebugVariables.h"
18 #include "RenderMachineFunction.h"
19 #include "Spiller.h"
20 #include "VirtRegMap.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Function.h"
23 #include "llvm/PassAnalysisSupport.h"
24 #include "llvm/CodeGen/CalcSpillWeights.h"
25 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
26 #include "llvm/CodeGen/LiveRangeEdit.h"
27 #include "llvm/CodeGen/LiveStackAnalysis.h"
28 #include "llvm/CodeGen/MachineFunctionPass.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/Passes.h"
33 #include "llvm/CodeGen/RegAllocRegistry.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/raw_ostream.h"
39
40 #include <cstdlib>
41 #include <queue>
42
43 using namespace llvm;
44
45 static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
46                                       createBasicRegisterAllocator);
47
48 namespace {
49   struct CompSpillWeight {
50     bool operator()(LiveInterval *A, LiveInterval *B) const {
51       return A->weight < B->weight;
52     }
53   };
54 }
55
56 namespace {
57 /// RABasic provides a minimal implementation of the basic register allocation
58 /// algorithm. It prioritizes live virtual registers by spill weight and spills
59 /// whenever a register is unavailable. This is not practical in production but
60 /// provides a useful baseline both for measuring other allocators and comparing
61 /// the speed of the basic algorithm against other styles of allocators.
62 class RABasic : public MachineFunctionPass, public RegAllocBase
63 {
64   // context
65   MachineFunction *MF;
66
67 #ifndef NDEBUG
68   // analyses
69   RenderMachineFunction *RMF;
70 #endif
71
72   // state
73   std::auto_ptr<Spiller> SpillerInstance;
74   std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
75                       CompSpillWeight> Queue;
76
77   // Scratch space.  Allocated here to avoid repeated malloc calls in
78   // selectOrSplit().
79   BitVector UsableRegs;
80
81 public:
82   RABasic();
83
84   /// Return the pass name.
85   virtual const char* getPassName() const {
86     return "Basic Register Allocator";
87   }
88
89   /// RABasic analysis usage.
90   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
91
92   virtual void releaseMemory();
93
94   virtual Spiller &spiller() { return *SpillerInstance; }
95
96   virtual float getPriority(LiveInterval *LI) { return LI->weight; }
97
98   virtual void enqueue(LiveInterval *LI) {
99     Queue.push(LI);
100   }
101
102   virtual LiveInterval *dequeue() {
103     if (Queue.empty())
104       return 0;
105     LiveInterval *LI = Queue.top();
106     Queue.pop();
107     return LI;
108   }
109
110   virtual unsigned selectOrSplit(LiveInterval &VirtReg,
111                                  SmallVectorImpl<LiveInterval*> &SplitVRegs);
112
113   /// Perform register allocation.
114   virtual bool runOnMachineFunction(MachineFunction &mf);
115
116   // Helper for spilling all live virtual registers currently unified under preg
117   // that interfere with the most recently queried lvr.  Return true if spilling
118   // was successful, and append any new spilled/split intervals to splitLVRs.
119   bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
120                           SmallVectorImpl<LiveInterval*> &SplitVRegs);
121
122   void spillReg(LiveInterval &VirtReg, unsigned PhysReg,
123                 SmallVectorImpl<LiveInterval*> &SplitVRegs);
124
125   static char ID;
126 };
127
128 char RABasic::ID = 0;
129
130 } // end anonymous namespace
131
132 RABasic::RABasic(): MachineFunctionPass(ID) {
133   initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
134   initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
135   initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
136   initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
137   initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
138   initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
139   initializeLiveStacksPass(*PassRegistry::getPassRegistry());
140   initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
141   initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
142   initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
143   initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
144 }
145
146 void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
147   AU.setPreservesCFG();
148   AU.addRequired<AliasAnalysis>();
149   AU.addPreserved<AliasAnalysis>();
150   AU.addRequired<LiveIntervals>();
151   AU.addPreserved<LiveIntervals>();
152   AU.addPreserved<SlotIndexes>();
153   AU.addRequired<LiveDebugVariables>();
154   AU.addPreserved<LiveDebugVariables>();
155   AU.addRequired<CalculateSpillWeights>();
156   AU.addRequired<LiveStacks>();
157   AU.addPreserved<LiveStacks>();
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   DEBUG(AU.addRequired<RenderMachineFunction>());
165   MachineFunctionPass::getAnalysisUsage(AU);
166 }
167
168 void RABasic::releaseMemory() {
169   SpillerInstance.reset(0);
170   RegAllocBase::releaseMemory();
171 }
172
173 // Helper for spillInterferences() that spills all interfering vregs currently
174 // assigned to this physical register.
175 void RABasic::spillReg(LiveInterval& VirtReg, unsigned PhysReg,
176                        SmallVectorImpl<LiveInterval*> &SplitVRegs) {
177   LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
178   assert(Q.seenAllInterferences() && "need collectInterferences()");
179   const SmallVectorImpl<LiveInterval*> &PendingSpills = Q.interferingVRegs();
180
181   for (SmallVectorImpl<LiveInterval*>::const_iterator I = PendingSpills.begin(),
182          E = PendingSpills.end(); I != E; ++I) {
183     LiveInterval &SpilledVReg = **I;
184     DEBUG(dbgs() << "extracting from " <<
185           TRI->getName(PhysReg) << " " << SpilledVReg << '\n');
186
187     // Deallocate the interfering vreg by removing it from the union.
188     // A LiveInterval instance may not be in a union during modification!
189     unassign(SpilledVReg, PhysReg);
190
191     // Spill the extracted interval.
192     LiveRangeEdit LRE(&SpilledVReg, SplitVRegs, *MF, *LIS, VRM);
193     spiller().spill(LRE);
194   }
195   // After extracting segments, the query's results are invalid. But keep the
196   // contents valid until we're done accessing pendingSpills.
197   Q.clear();
198 }
199
200 // Spill or split all live virtual registers currently unified under PhysReg
201 // that interfere with VirtReg. The newly spilled or split live intervals are
202 // returned by appending them to SplitVRegs.
203 bool RABasic::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
204                                  SmallVectorImpl<LiveInterval*> &SplitVRegs) {
205   // Record each interference and determine if all are spillable before mutating
206   // either the union or live intervals.
207   unsigned NumInterferences = 0;
208   // Collect interferences assigned to any alias of the physical register.
209   for (MCRegAliasIterator AI(PhysReg, TRI, true); AI.isValid(); ++AI) {
210     LiveIntervalUnion::Query &QAlias = query(VirtReg, *AI);
211     NumInterferences += QAlias.collectInterferingVRegs();
212     if (QAlias.seenUnspillableVReg()) {
213       return false;
214     }
215   }
216   DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
217         " interferences with " << VirtReg << "\n");
218   assert(NumInterferences > 0 && "expect interference");
219
220   // Spill each interfering vreg allocated to PhysReg or an alias.
221   for (MCRegAliasIterator AI(PhysReg, TRI, true); AI.isValid(); ++AI)
222     spillReg(VirtReg, *AI, SplitVRegs);
223   return true;
224 }
225
226 // Driver for the register assignment and splitting heuristics.
227 // Manages iteration over the LiveIntervalUnions.
228 //
229 // This is a minimal implementation of register assignment and splitting that
230 // spills whenever we run out of registers.
231 //
232 // selectOrSplit can only be called once per live virtual register. We then do a
233 // single interference test for each register the correct class until we find an
234 // available register. So, the number of interference tests in the worst case is
235 // |vregs| * |machineregs|. And since the number of interference tests is
236 // minimal, there is no value in caching them outside the scope of
237 // selectOrSplit().
238 unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
239                                 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
240   // Check for register mask interference.  When live ranges cross calls, the
241   // set of usable registers is reduced to the callee-saved ones.
242   bool CrossRegMasks = LIS->checkRegMaskInterference(VirtReg, UsableRegs);
243
244   // Populate a list of physical register spill candidates.
245   SmallVector<unsigned, 8> PhysRegSpillCands;
246
247   // Check for an available register in this class.
248   ArrayRef<unsigned> Order =
249     RegClassInfo.getOrder(MRI->getRegClass(VirtReg.reg));
250   for (ArrayRef<unsigned>::iterator I = Order.begin(), E = Order.end(); I != E;
251        ++I) {
252     unsigned PhysReg = *I;
253
254     // If PhysReg is clobbered by a register mask, it isn't useful for
255     // allocation or spilling.
256     if (CrossRegMasks && !UsableRegs.test(PhysReg))
257       continue;
258
259     // Check interference and as a side effect, intialize queries for this
260     // VirtReg and its aliases.
261     unsigned interfReg = checkPhysRegInterference(VirtReg, PhysReg);
262     if (interfReg == 0) {
263       // Found an available register.
264       return PhysReg;
265     }
266     LiveIntervalUnion::Query &IntfQ = query(VirtReg, interfReg);
267     IntfQ.collectInterferingVRegs(1);
268     LiveInterval *interferingVirtReg = IntfQ.interferingVRegs().front();
269
270     // The current VirtReg must either be spillable, or one of its interferences
271     // must have less spill weight.
272     if (interferingVirtReg->weight < VirtReg.weight ) {
273       PhysRegSpillCands.push_back(PhysReg);
274     }
275   }
276   // Try to spill another interfering reg with less spill weight.
277   for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
278          PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
279
280     if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
281
282     assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
283            "Interference after spill.");
284     // Tell the caller to allocate to this newly freed physical register.
285     return *PhysRegI;
286   }
287
288   // No other spill candidates were found, so spill the current VirtReg.
289   DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
290   if (!VirtReg.isSpillable())
291     return ~0u;
292   LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM);
293   spiller().spill(LRE);
294
295   // The live virtual register requesting allocation was spilled, so tell
296   // the caller not to allocate anything during this round.
297   return 0;
298 }
299
300 bool RABasic::runOnMachineFunction(MachineFunction &mf) {
301   DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
302                << "********** Function: "
303                << ((Value*)mf.getFunction())->getName() << '\n');
304
305   MF = &mf;
306   DEBUG(RMF = &getAnalysis<RenderMachineFunction>());
307
308   RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
309   SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
310
311   allocatePhysRegs();
312
313   // Diagnostic output before rewriting
314   DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
315
316   // optional HTML output
317   DEBUG(RMF->renderMachineFunction("After basic register allocation.", VRM));
318
319   releaseMemory();
320   return true;
321 }
322
323 FunctionPass* llvm::createBasicRegisterAllocator()
324 {
325   return new RABasic();
326 }