Switch LiveIntervalUnion from std::set to IntervalMap.
[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 "LiveIntervalUnion.h"
17 #include "RegAllocBase.h"
18 #include "RenderMachineFunction.h"
19 #include "Spiller.h"
20 #include "VirtRegMap.h"
21 #include "VirtRegRewriter.h"
22 #include "llvm/ADT/OwningPtr.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Function.h"
25 #include "llvm/PassAnalysisSupport.h"
26 #include "llvm/CodeGen/CalcSpillWeights.h"
27 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
28 #include "llvm/CodeGen/LiveStackAnalysis.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/MachineLoopInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/Passes.h"
34 #include "llvm/CodeGen/RegAllocRegistry.h"
35 #include "llvm/CodeGen/RegisterCoalescer.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #ifndef NDEBUG
40 #include "llvm/ADT/SparseBitVector.h"
41 #endif
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/raw_ostream.h"
45
46 #include <vector>
47 #include <queue>
48 #include <cstdlib>
49
50 using namespace llvm;
51
52 static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
53                                       createBasicRegisterAllocator);
54
55 // Temporary verification option until we can put verification inside
56 // MachineVerifier.
57 static cl::opt<bool>
58 VerifyRegAlloc("verify-regalloc",
59                cl::desc("Verify live intervals before renaming"));
60
61 namespace {
62
63 class PhysicalRegisterDescription : public AbstractRegisterDescription {
64   const TargetRegisterInfo *TRI;
65 public:
66   PhysicalRegisterDescription(const TargetRegisterInfo *T): TRI(T) {}
67   virtual const char *getName(unsigned Reg) const { return TRI->getName(Reg); }
68 };
69
70 /// RABasic provides a minimal implementation of the basic register allocation
71 /// algorithm. It prioritizes live virtual registers by spill weight and spills
72 /// whenever a register is unavailable. This is not practical in production but
73 /// provides a useful baseline both for measuring other allocators and comparing
74 /// the speed of the basic algorithm against other styles of allocators.
75 class RABasic : public MachineFunctionPass, public RegAllocBase
76 {
77   // context
78   MachineFunction *MF;
79   const TargetMachine *TM;
80   MachineRegisterInfo *MRI;
81
82   BitVector ReservedRegs;
83
84   // analyses
85   LiveStacks *LS;
86   RenderMachineFunction *RMF;
87
88   // state
89   std::auto_ptr<Spiller> SpillerInstance;
90
91 public:
92   RABasic();
93
94   /// Return the pass name.
95   virtual const char* getPassName() const {
96     return "Basic Register Allocator";
97   }
98
99   /// RABasic analysis usage.
100   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
101
102   virtual void releaseMemory();
103
104   virtual Spiller &spiller() { return *SpillerInstance; }
105
106   virtual unsigned selectOrSplit(LiveInterval &VirtReg,
107                                  SmallVectorImpl<LiveInterval*> &SplitVRegs);
108
109   /// Perform register allocation.
110   virtual bool runOnMachineFunction(MachineFunction &mf);
111
112   static char ID;
113
114 private:
115   void addMBBLiveIns();
116 };
117
118 char RABasic::ID = 0;
119
120 } // end anonymous namespace
121
122 RABasic::RABasic(): MachineFunctionPass(ID) {
123   initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
124   initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
125   initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
126   initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
127   initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
128   initializeLiveStacksPass(*PassRegistry::getPassRegistry());
129   initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
130   initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
131   initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
132   initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
133 }
134
135 void RABasic::getAnalysisUsage(AnalysisUsage &AU) const {
136   AU.setPreservesCFG();
137   AU.addRequired<AliasAnalysis>();
138   AU.addPreserved<AliasAnalysis>();
139   AU.addRequired<LiveIntervals>();
140   AU.addPreserved<SlotIndexes>();
141   if (StrongPHIElim)
142     AU.addRequiredID(StrongPHIEliminationID);
143   AU.addRequiredTransitive<RegisterCoalescer>();
144   AU.addRequired<CalculateSpillWeights>();
145   AU.addRequired<LiveStacks>();
146   AU.addPreserved<LiveStacks>();
147   AU.addRequiredID(MachineDominatorsID);
148   AU.addPreservedID(MachineDominatorsID);
149   AU.addRequired<MachineLoopInfo>();
150   AU.addPreserved<MachineLoopInfo>();
151   AU.addRequired<VirtRegMap>();
152   AU.addPreserved<VirtRegMap>();
153   DEBUG(AU.addRequired<RenderMachineFunction>());
154   MachineFunctionPass::getAnalysisUsage(AU);
155 }
156
157 void RABasic::releaseMemory() {
158   SpillerInstance.reset(0);
159   RegAllocBase::releaseMemory();
160 }
161
162 #ifndef NDEBUG
163 // Verify each LiveIntervalUnion.
164 void RegAllocBase::verify() {
165   LiveVirtRegBitSet VisitedVRegs;
166   OwningArrayPtr<LiveVirtRegBitSet>
167     unionVRegs(new LiveVirtRegBitSet[PhysReg2LiveUnion.numRegs()]);
168
169   // Verify disjoint unions.
170   for (unsigned PhysReg = 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++PhysReg) {
171     DEBUG(PhysicalRegisterDescription PRD(TRI);
172           PhysReg2LiveUnion[PhysReg].dump(&PRD));
173     LiveVirtRegBitSet &VRegs = unionVRegs[PhysReg];
174     PhysReg2LiveUnion[PhysReg].verify(VRegs);
175     // Union + intersection test could be done efficiently in one pass, but
176     // don't add a method to SparseBitVector unless we really need it.
177     assert(!VisitedVRegs.intersects(VRegs) && "vreg in multiple unions");
178     VisitedVRegs |= VRegs;
179   }
180
181   // Verify vreg coverage.
182   for (LiveIntervals::iterator liItr = LIS->begin(), liEnd = LIS->end();
183        liItr != liEnd; ++liItr) {
184     unsigned reg = liItr->first;
185     if (TargetRegisterInfo::isPhysicalRegister(reg)) continue;
186     if (!VRM->hasPhys(reg)) continue; // spilled?
187     unsigned PhysReg = VRM->getPhys(reg);
188     if (!unionVRegs[PhysReg].test(reg)) {
189       dbgs() << "LiveVirtReg " << reg << " not in union " <<
190         TRI->getName(PhysReg) << "\n";
191       llvm_unreachable("unallocated live vreg");
192     }
193   }
194   // FIXME: I'm not sure how to verify spilled intervals.
195 }
196 #endif //!NDEBUG
197
198 //===----------------------------------------------------------------------===//
199 //                         RegAllocBase Implementation
200 //===----------------------------------------------------------------------===//
201
202 // Instantiate a LiveIntervalUnion for each physical register.
203 void RegAllocBase::LiveUnionArray::init(LiveIntervalUnion::Allocator &allocator,
204                                         unsigned NRegs) {
205   NumRegs = NRegs;
206   Array =
207     static_cast<LiveIntervalUnion*>(malloc(sizeof(LiveIntervalUnion)*NRegs));
208   for (unsigned r = 0; r != NRegs; ++r)
209     new(Array + r) LiveIntervalUnion(r, allocator);
210 }
211
212 void RegAllocBase::init(const TargetRegisterInfo &tri, VirtRegMap &vrm,
213                         LiveIntervals &lis) {
214   TRI = &tri;
215   VRM = &vrm;
216   LIS = &lis;
217   PhysReg2LiveUnion.init(UnionAllocator, TRI->getNumRegs());
218   // Cache an interferece query for each physical reg
219   Queries.reset(new LiveIntervalUnion::Query[PhysReg2LiveUnion.numRegs()]);
220 }
221
222 void RegAllocBase::LiveUnionArray::clear() {
223   if (!Array)
224     return;
225   for (unsigned r = 0; r != NumRegs; ++r)
226     Array[r].~LiveIntervalUnion();
227   free(Array);
228   NumRegs =  0;
229   Array = 0;
230 }
231
232 void RegAllocBase::releaseMemory() {
233   PhysReg2LiveUnion.clear();
234 }
235
236 namespace llvm {
237 /// This class defines a queue of live virtual registers prioritized by spill
238 /// weight. The heaviest vreg is popped first.
239 ///
240 /// Currently, this is trivial wrapper that gives us an opaque type in the
241 /// header, but we may later give it a virtual interface for register allocators
242 /// to override the priority queue comparator.
243 class LiveVirtRegQueue {
244   typedef std::priority_queue
245     <LiveInterval*, std::vector<LiveInterval*>, LessSpillWeightPriority>
246     PriorityQ;
247   PriorityQ PQ;
248
249 public:
250   // Is the queue empty?
251   bool empty() { return PQ.empty(); }
252
253   // Get the highest priority lvr (top + pop)
254   LiveInterval *get() {
255     LiveInterval *VirtReg = PQ.top();
256     PQ.pop();
257     return VirtReg;
258   }
259   // Add this lvr to the queue
260   void push(LiveInterval *VirtReg) {
261     PQ.push(VirtReg);
262   }
263 };
264 } // end namespace llvm
265
266 // Visit all the live virtual registers. If they are already assigned to a
267 // physical register, unify them with the corresponding LiveIntervalUnion,
268 // otherwise push them on the priority queue for later assignment.
269 void RegAllocBase::seedLiveVirtRegs(LiveVirtRegQueue &VirtRegQ) {
270   for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end(); I != E; ++I) {
271     unsigned RegNum = I->first;
272     LiveInterval &VirtReg = *I->second;
273     if (TargetRegisterInfo::isPhysicalRegister(RegNum)) {
274       PhysReg2LiveUnion[RegNum].unify(VirtReg);
275     }
276     else {
277       VirtRegQ.push(&VirtReg);
278     }
279   }
280 }
281
282 // Top-level driver to manage the queue of unassigned VirtRegs and call the
283 // selectOrSplit implementation.
284 void RegAllocBase::allocatePhysRegs() {
285
286   // Push each vreg onto a queue or "precolor" by adding it to a physreg union.
287   LiveVirtRegQueue VirtRegQ;
288   seedLiveVirtRegs(VirtRegQ);
289
290   // Continue assigning vregs one at a time to available physical registers.
291   while (!VirtRegQ.empty()) {
292     // Pop the highest priority vreg.
293     LiveInterval *VirtReg = VirtRegQ.get();
294
295     // selectOrSplit requests the allocator to return an available physical
296     // register if possible and populate a list of new live intervals that
297     // result from splitting.
298     typedef SmallVector<LiveInterval*, 4> VirtRegVec;
299     VirtRegVec SplitVRegs;
300     unsigned AvailablePhysReg = selectOrSplit(*VirtReg, SplitVRegs);
301
302     if (AvailablePhysReg) {
303       DEBUG(dbgs() << "allocating: " << TRI->getName(AvailablePhysReg) <<
304             " " << *VirtReg << '\n');
305       assert(!VRM->hasPhys(VirtReg->reg) && "duplicate vreg in union");
306       VRM->assignVirt2Phys(VirtReg->reg, AvailablePhysReg);
307       PhysReg2LiveUnion[AvailablePhysReg].unify(*VirtReg);
308     }
309     for (VirtRegVec::iterator I = SplitVRegs.begin(), E = SplitVRegs.end();
310          I != E; ++I) {
311       LiveInterval* SplitVirtReg = *I;
312       if (SplitVirtReg->empty()) continue;
313       DEBUG(dbgs() << "queuing new interval: " << *SplitVirtReg << "\n");
314       assert(TargetRegisterInfo::isVirtualRegister(SplitVirtReg->reg) &&
315              "expect split value in virtual register");
316       VirtRegQ.push(SplitVirtReg);
317     }
318   }
319 }
320
321 // Check if this live virtual register interferes with a physical register. If
322 // not, then check for interference on each register that aliases with the
323 // physical register. Return the interfering register.
324 unsigned RegAllocBase::checkPhysRegInterference(LiveInterval &VirtReg,
325                                                 unsigned PhysReg) {
326   if (query(VirtReg, PhysReg).checkInterference())
327     return PhysReg;
328   for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI) {
329     if (query(VirtReg, *AliasI).checkInterference())
330       return *AliasI;
331   }
332   return 0;
333 }
334
335 // Helper for spillInteferences() that spills all interfering vregs currently
336 // assigned to this physical register.
337 void RegAllocBase::spillReg(LiveInterval& VirtReg, unsigned PhysReg,
338                             SmallVectorImpl<LiveInterval*> &SplitVRegs) {
339   LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg);
340   assert(Q.seenAllInterferences() && "need collectInterferences()");
341   const SmallVectorImpl<LiveInterval*> &PendingSpills = Q.interferingVRegs();
342
343   for (SmallVectorImpl<LiveInterval*>::const_iterator I = PendingSpills.begin(),
344          E = PendingSpills.end(); I != E; ++I) {
345     LiveInterval &SpilledVReg = **I;
346     DEBUG(dbgs() << "extracting from " <<
347           TRI->getName(PhysReg) << " " << SpilledVReg << '\n');
348
349     // Deallocate the interfering vreg by removing it from the union.
350     // A LiveInterval instance may not be in a union during modification!
351     PhysReg2LiveUnion[PhysReg].extract(SpilledVReg);
352
353     // Clear the vreg assignment.
354     VRM->clearVirt(SpilledVReg.reg);
355
356     // Spill the extracted interval.
357     spiller().spill(&SpilledVReg, SplitVRegs, PendingSpills);
358   }
359   // After extracting segments, the query's results are invalid. But keep the
360   // contents valid until we're done accessing pendingSpills.
361   Q.clear();
362 }
363
364 // Spill or split all live virtual registers currently unified under PhysReg
365 // that interfere with VirtReg. The newly spilled or split live intervals are
366 // returned by appending them to SplitVRegs.
367 bool
368 RegAllocBase::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
369                                  SmallVectorImpl<LiveInterval*> &SplitVRegs) {
370   // Record each interference and determine if all are spillable before mutating
371   // either the union or live intervals.
372
373   // Collect interferences assigned to the requested physical register.
374   LiveIntervalUnion::Query &QPreg = query(VirtReg, PhysReg);
375   unsigned NumInterferences = QPreg.collectInterferingVRegs();
376   if (QPreg.seenUnspillableVReg()) {
377     return false;
378   }
379   // Collect interferences assigned to any alias of the physical register.
380   for (const unsigned *asI = TRI->getAliasSet(PhysReg); *asI; ++asI) {
381     LiveIntervalUnion::Query &QAlias = query(VirtReg, *asI);
382     NumInterferences += QAlias.collectInterferingVRegs();
383     if (QAlias.seenUnspillableVReg()) {
384       return false;
385     }
386   }
387   DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) <<
388         " interferences with " << VirtReg << "\n");
389   assert(NumInterferences > 0 && "expect interference");
390
391   // Spill each interfering vreg allocated to PhysReg or an alias.
392   spillReg(VirtReg, PhysReg, SplitVRegs);
393   for (const unsigned *AliasI = TRI->getAliasSet(PhysReg); *AliasI; ++AliasI)
394     spillReg(VirtReg, *AliasI, SplitVRegs);
395   return true;
396 }
397
398 //===----------------------------------------------------------------------===//
399 //                         RABasic Implementation
400 //===----------------------------------------------------------------------===//
401
402 // Driver for the register assignment and splitting heuristics.
403 // Manages iteration over the LiveIntervalUnions.
404 //
405 // This is a minimal implementation of register assignment and splitting that
406 // spills whenever we run out of registers.
407 //
408 // selectOrSplit can only be called once per live virtual register. We then do a
409 // single interference test for each register the correct class until we find an
410 // available register. So, the number of interference tests in the worst case is
411 // |vregs| * |machineregs|. And since the number of interference tests is
412 // minimal, there is no value in caching them outside the scope of
413 // selectOrSplit().
414 unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
415                                 SmallVectorImpl<LiveInterval*> &SplitVRegs) {
416   // Populate a list of physical register spill candidates.
417   SmallVector<unsigned, 8> PhysRegSpillCands;
418
419   // Check for an available register in this class.
420   const TargetRegisterClass *TRC = MRI->getRegClass(VirtReg.reg);
421   DEBUG(dbgs() << "RegClass: " << TRC->getName() << ' ');
422
423   for (TargetRegisterClass::iterator I = TRC->allocation_order_begin(*MF),
424          E = TRC->allocation_order_end(*MF);
425        I != E; ++I) {
426
427     unsigned PhysReg = *I;
428     if (ReservedRegs.test(PhysReg)) continue;
429
430     // Check interference and as a side effect, intialize queries for this
431     // VirtReg and its aliases.
432     unsigned interfReg = checkPhysRegInterference(VirtReg, PhysReg);
433     if (interfReg == 0) {
434       // Found an available register.
435       return PhysReg;
436     }
437     LiveInterval *interferingVirtReg =
438       Queries[interfReg].firstInterference().liveUnionPos().value();
439
440     // The current VirtReg must either spillable, or one of its interferences
441     // must have less spill weight.
442     if (interferingVirtReg->weight < VirtReg.weight ) {
443       PhysRegSpillCands.push_back(PhysReg);
444     }
445   }
446   // Try to spill another interfering reg with less spill weight.
447   //
448   // FIXME: RAGreedy will sort this list by spill weight.
449   for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(),
450          PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) {
451
452     if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue;
453
454     assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 &&
455            "Interference after spill.");
456     // Tell the caller to allocate to this newly freed physical register.
457     return *PhysRegI;
458   }
459   // No other spill candidates were found, so spill the current VirtReg.
460   DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
461   SmallVector<LiveInterval*, 1> pendingSpills;
462
463   spiller().spill(&VirtReg, SplitVRegs, pendingSpills);
464
465   // The live virtual register requesting allocation was spilled, so tell
466   // the caller not to allocate anything during this round.
467   return 0;
468 }
469
470 // Add newly allocated physical registers to the MBB live in sets.
471 void RABasic::addMBBLiveIns() {
472   typedef SmallVector<MachineBasicBlock*, 8> MBBVec;
473   MBBVec liveInMBBs;
474   MachineBasicBlock &entryMBB = *MF->begin();
475
476   for (unsigned PhysReg = 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++PhysReg) {
477     LiveIntervalUnion &LiveUnion = PhysReg2LiveUnion[PhysReg];
478
479     for (LiveIntervalUnion::SegmentIter SI = LiveUnion.begin(),
480            SegEnd = LiveUnion.end();
481          SI != SegEnd; ++SI) {
482
483       // Find the set of basic blocks which this range is live into...
484       liveInMBBs.clear();
485       if (!LIS->findLiveInMBBs(SI.start(), SI.stop(), liveInMBBs)) continue;
486
487       // And add the physreg for this interval to their live-in sets.
488       for (MBBVec::iterator I = liveInMBBs.begin(), E = liveInMBBs.end();
489            I != E; ++I) {
490         MachineBasicBlock *MBB = *I;
491         if (MBB == &entryMBB) continue;
492         if (MBB->isLiveIn(PhysReg)) continue;
493         MBB->addLiveIn(PhysReg);
494       }
495     }
496   }
497 }
498
499 bool RABasic::runOnMachineFunction(MachineFunction &mf) {
500   DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
501                << "********** Function: "
502                << ((Value*)mf.getFunction())->getName() << '\n');
503
504   MF = &mf;
505   TM = &mf.getTarget();
506   MRI = &mf.getRegInfo();
507
508   DEBUG(RMF = &getAnalysis<RenderMachineFunction>());
509
510   const TargetRegisterInfo *TRI = TM->getRegisterInfo();
511   RegAllocBase::init(*TRI, getAnalysis<VirtRegMap>(),
512                      getAnalysis<LiveIntervals>());
513
514   ReservedRegs = TRI->getReservedRegs(*MF);
515
516   SpillerInstance.reset(createSpiller(*this, *MF, *VRM));
517
518   allocatePhysRegs();
519
520   addMBBLiveIns();
521
522   // Diagnostic output before rewriting
523   DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n");
524
525   // optional HTML output
526   DEBUG(RMF->renderMachineFunction("After basic register allocation.", VRM));
527
528   // FIXME: Verification currently must run before VirtRegRewriter. We should
529   // make the rewriter a separate pass and override verifyAnalysis instead. When
530   // that happens, verification naturally falls under VerifyMachineCode.
531 #ifndef NDEBUG
532   if (VerifyRegAlloc) {
533     // Verify accuracy of LiveIntervals. The standard machine code verifier
534     // ensures that each LiveIntervals covers all uses of the virtual reg.
535
536     // FIXME: MachineVerifier is badly broken when using the standard
537     // spiller. Always use -spiller=inline with -verify-regalloc. Even with the
538     // inline spiller, some tests fail to verify because the coalescer does not
539     // always generate verifiable code.
540     MF->verify(this);
541
542     // Verify that LiveIntervals are partitioned into unions and disjoint within
543     // the unions.
544     verify();
545   }
546 #endif // !NDEBUG
547
548   // Run rewriter
549   std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
550   rewriter->runOnMachineFunction(*MF, *VRM, LIS);
551
552   // The pass output is in VirtRegMap. Release all the transient data.
553   releaseMemory();
554
555   return true;
556 }
557
558 FunctionPass* llvm::createBasicRegisterAllocator()
559 {
560   return new RABasic();
561 }