Add Register mask support to RABasic.
[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 "LiveRangeEdit.h"
19 #include "RenderMachineFunction.h"
20 #include "Spiller.h"
21 #include "VirtRegMap.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Function.h"
24 #include "llvm/PassAnalysisSupport.h"
25 #include "llvm/CodeGen/CalcSpillWeights.h"
26 #include "llvm/CodeGen/LiveIntervalAnalysis.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   // analyses
68   LiveStacks *LS;
69   RenderMachineFunction *RMF;
70
71   // state
72   std::auto_ptr<Spiller> SpillerInstance;
73   std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
74                       CompSpillWeight> Queue;
75
76   // Scratch space.  Allocated here to avoid repeated malloc calls in
77   // selectOrSplit().
78   BitVector UsableRegs;
79
80 public:
81   RABasic();
82
83   /// Return the pass name.
84   virtual const char* getPassName() const {
85     return "Basic Register Allocator";
86   }
87
88   /// RABasic analysis usage.
89   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
90
91   virtual void releaseMemory();
92
93   virtual Spiller &spiller() { return *SpillerInstance; }
94
95   virtual float getPriority(LiveInterval *LI) { return LI->weight; }
96
97   virtual void enqueue(LiveInterval *LI) {
98     Queue.push(LI);
99   }
100
101   virtual LiveInterval *dequeue() {
102     if (Queue.empty())
103       return 0;
104     LiveInterval *LI = Queue.top();
105     Queue.pop();
106     return LI;
107   }
108
109   virtual unsigned selectOrSplit(LiveInterval &VirtReg,
110                                  SmallVectorImpl<LiveInterval*> &SplitVRegs);
111
112   /// Perform register allocation.
113   virtual bool runOnMachineFunction(MachineFunction &mf);
114
115   // Helper for spilling all live virtual registers currently unified under preg
116   // that interfere with the most recently queried lvr.  Return true if spilling
117   // was successful, and append any new spilled/split intervals to splitLVRs.
118   bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
119                           SmallVectorImpl<LiveInterval*> &SplitVRegs);
120
121   void spillReg(LiveInterval &VirtReg, unsigned PhysReg,
122                 SmallVectorImpl<LiveInterval*> &SplitVRegs);
123
124   static char ID;
125 };
126
127 char RABasic::ID = 0;
128
129 } // end anonymous namespace
130
131 RABasic::RABasic(): MachineFunctionPass(ID) {
132   initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
133   initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
134   initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
135   initializeStrongPHIEliminationPass(*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<SlotIndexes>();
152   AU.addRequired<LiveDebugVariables>();
153   AU.addPreserved<LiveDebugVariables>();
154   if (StrongPHIElim)
155     AU.addRequiredID(StrongPHIEliminationID);
156   AU.addRequiredTransitiveID(RegisterCoalescerPassID);
157   AU.addRequired<CalculateSpillWeights>();
158   AU.addRequired<LiveStacks>();
159   AU.addPreserved<LiveStacks>();
160   AU.addRequiredID(MachineDominatorsID);
161   AU.addPreservedID(MachineDominatorsID);
162   AU.addRequired<MachineLoopInfo>();
163   AU.addPreserved<MachineLoopInfo>();
164   AU.addRequired<VirtRegMap>();
165   AU.addPreserved<VirtRegMap>();
166   DEBUG(AU.addRequired<RenderMachineFunction>());
167   MachineFunctionPass::getAnalysisUsage(AU);
168 }
169
170 void RABasic::releaseMemory() {
171   SpillerInstance.reset(0);
172   RegAllocBase::releaseMemory();
173 }
174
175 // Helper for spillInterferences() that spills all interfering vregs currently
176 // assigned to this physical register.
177 void RABasic::spillReg(LiveInterval& VirtReg, unsigned PhysReg,
178                        SmallVectorImpl<LiveInterval*> &SplitVRegs) {
179   LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
180   assert(Q.seenAllInterferences() && "need collectInterferences()");
181   const SmallVectorImpl<LiveInterval*> &PendingSpills = Q.interferingVRegs();
182
183   for (SmallVectorImpl<LiveInterval*>::const_iterator I = PendingSpills.begin(),
184          E = PendingSpills.end(); I != E; ++I) {
185     LiveInterval &SpilledVReg = **I;
186     DEBUG(dbgs() << "extracting from " <<
187           TRI->getName(PhysReg) << " " << SpilledVReg << '\n');
188
189     // Deallocate the interfering vreg by removing it from the union.
190     // A LiveInterval instance may not be in a union during modification!
191     unassign(SpilledVReg, PhysReg);
192
193     // Spill the extracted interval.
194     LiveRangeEdit LRE(SpilledVReg, SplitVRegs, 0, &PendingSpills);
195     spiller().spill(LRE);
196   }
197   // After extracting segments, the query's results are invalid. But keep the
198   // contents valid until we're done accessing pendingSpills.
199   Q.clear();
200 }
201
202 // Spill or split all live virtual registers currently unified under PhysReg
203 // that interfere with VirtReg. The newly spilled or split live intervals are
204 // returned by appending them to SplitVRegs.
205 bool RABasic::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
206                                  SmallVectorImpl<LiveInterval*> &SplitVRegs) {
207   // Record each interference and determine if all are spillable before mutating
208   // either the union or live intervals.
209   unsigned NumInterferences = 0;
210   // Collect interferences assigned to any alias of the physical register.
211   for (const unsigned *asI = TRI->getOverlaps(PhysReg); *asI; ++asI) {
212     LiveIntervalUnion::Query &QAlias = query(VirtReg, *asI);
213     NumInterferences += QAlias.collectInterferingVRegs();
214     if (QAlias.seenUnspillableVReg()) {
215       return false;
216     }
217   }
218   DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
219         " interferences with " << VirtReg << "\n");
220   assert(NumInterferences > 0 && "expect interference");
221
222   // Spill each interfering vreg allocated to PhysReg or an alias.
223   for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI)
224     spillReg(VirtReg, *AliasI, SplitVRegs);
225   return true;
226 }
227
228 // Driver for the register assignment and splitting heuristics.
229 // Manages iteration over the LiveIntervalUnions.
230 //
231 // This is a minimal implementation of register assignment and splitting that
232 // spills whenever we run out of registers.
233 //
234 // selectOrSplit can only be called once per live virtual register. We then do a
235 // single interference test for each register the correct class until we find an
236 // available register. So, the number of interference tests in the worst case is
237 // |vregs| * |machineregs|. And since the number of interference tests is
238 // minimal, there is no value in caching them outside the scope of
239 // selectOrSplit().
240 unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
241                                 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
242   // Check for register mask interference.  When live ranges cross calls, the
243   // set of usable registers is reduced to the callee-saved ones.
244   bool CrossRegMasks = LIS->checkRegMaskInterference(VirtReg, UsableRegs);
245
246   // Populate a list of physical register spill candidates.
247   SmallVector<unsigned, 8> PhysRegSpillCands;
248
249   // Check for an available register in this class.
250   ArrayRef<unsigned> Order =
251     RegClassInfo.getOrder(MRI->getRegClass(VirtReg.reg));
252   for (ArrayRef<unsigned>::iterator I = Order.begin(), E = Order.end(); I != E;
253        ++I) {
254     unsigned PhysReg = *I;
255
256     // If PhysReg is clobbered by a register mask, it isn't useful for
257     // allocation or spilling.
258     if (CrossRegMasks && !UsableRegs.test(PhysReg))
259       continue;
260
261     // Check interference and as a side effect, intialize queries for this
262     // VirtReg and its aliases.
263     unsigned interfReg = checkPhysRegInterference(VirtReg, PhysReg);
264     if (interfReg == 0) {
265       // Found an available register.
266       return PhysReg;
267     }
268     LiveIntervalUnion::Query &IntfQ = query(VirtReg, interfReg);
269     IntfQ.collectInterferingVRegs(1);
270     LiveInterval *interferingVirtReg = IntfQ.interferingVRegs().front();
271
272     // The current VirtReg must either be spillable, or one of its interferences
273     // must have less spill weight.
274     if (interferingVirtReg->weight < VirtReg.weight ) {
275       PhysRegSpillCands.push_back(PhysReg);
276     }
277   }
278   // Try to spill another interfering reg with less spill weight.
279   for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
280          PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
281
282     if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
283
284     assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
285            "Interference after spill.");
286     // Tell the caller to allocate to this newly freed physical register.
287     return *PhysRegI;
288   }
289
290   // No other spill candidates were found, so spill the current VirtReg.
291   DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
292   if (!VirtReg.isSpillable())
293     return ~0u;
294   LiveRangeEdit LRE(VirtReg, SplitVRegs);
295   spiller().spill(LRE);
296
297   // The live virtual register requesting allocation was spilled, so tell
298   // the caller not to allocate anything during this round.
299   return 0;
300 }
301
302 bool RABasic::runOnMachineFunction(MachineFunction &mf) {
303   DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
304                << "********** Function: "
305                << ((Value*)mf.getFunction())->getName() << '\n');
306
307   MF = &mf;
308   DEBUG(RMF = &getAnalysis<RenderMachineFunction>());
309
310   RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
311   SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
312
313   allocatePhysRegs();
314
315   addMBBLiveIns(MF);
316
317   // Diagnostic output before rewriting
318   DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
319
320   // optional HTML output
321   DEBUG(RMF->renderMachineFunction("After basic register allocation.", VRM));
322
323   // FIXME: Verification currently must run before VirtRegRewriter. We should
324   // make the rewriter a separate pass and override verifyAnalysis instead. When
325   // that happens, verification naturally falls under VerifyMachineCode.
326 #ifndef NDEBUG
327   if (VerifyEnabled) {
328     // Verify accuracy of LiveIntervals. The standard machine code verifier
329     // ensures that each LiveIntervals covers all uses of the virtual reg.
330
331     // FIXME: MachineVerifier is badly broken when using the standard
332     // spiller. Always use -spiller=inline with -verify-regalloc. Even with the
333     // inline spiller, some tests fail to verify because the coalescer does not
334     // always generate verifiable code.
335     MF->verify(this, "In RABasic::verify");
336
337     // Verify that LiveIntervals are partitioned into unions and disjoint within
338     // the unions.
339     verify();
340   }
341 #endif // !NDEBUG
342
343   // Run rewriter
344   VRM->rewrite(LIS->getSlotIndexes());
345
346   // Write out new DBG_VALUE instructions.
347   getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
348
349   // The pass output is in VirtRegMap. Release all the transient data.
350   releaseMemory();
351
352   return true;
353 }
354
355 FunctionPass* llvm::createBasicRegisterAllocator()
356 {
357   return new RABasic();
358 }