Switch PBQP to VRM's trivial rewriter.
[oota-llvm.git] / lib / CodeGen / RegAllocPBQP.cpp
1 //===------ RegAllocPBQP.cpp ---- PBQP Register Allocator -------*- C++ -*-===//
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 contains a Partitioned Boolean Quadratic Programming (PBQP) based
11 // register allocator for LLVM. This allocator works by constructing a PBQP
12 // problem representing the register allocation problem under consideration,
13 // solving this using a PBQP solver, and mapping the solution back to a
14 // register assignment. If any variables are selected for spilling then spill
15 // code is inserted and the process repeated.
16 //
17 // The PBQP solver (pbqp.c) provided for this allocator uses a heuristic tuned
18 // for register allocation. For more information on PBQP for register
19 // allocation, see the following papers:
20 //
21 //   (1) Hames, L. and Scholz, B. 2006. Nearly optimal register allocation with
22 //   PBQP. In Proceedings of the 7th Joint Modular Languages Conference
23 //   (JMLC'06). LNCS, vol. 4228. Springer, New York, NY, USA. 346-361.
24 //
25 //   (2) Scholz, B., Eckstein, E. 2002. Register allocation for irregular
26 //   architectures. In Proceedings of the Joint Conference on Languages,
27 //   Compilers and Tools for Embedded Systems (LCTES'02), ACM Press, New York,
28 //   NY, USA, 139-148.
29 //
30 //===----------------------------------------------------------------------===//
31
32 #define DEBUG_TYPE "regalloc"
33
34 #include "LiveRangeEdit.h"
35 #include "RenderMachineFunction.h"
36 #include "Spiller.h"
37 #include "Splitter.h"
38 #include "VirtRegMap.h"
39 #include "RegisterCoalescer.h"
40 #include "llvm/CodeGen/CalcSpillWeights.h"
41 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
42 #include "llvm/CodeGen/LiveStackAnalysis.h"
43 #include "llvm/CodeGen/RegAllocPBQP.h"
44 #include "llvm/CodeGen/MachineFunctionPass.h"
45 #include "llvm/CodeGen/MachineLoopInfo.h"
46 #include "llvm/CodeGen/MachineRegisterInfo.h"
47 #include "llvm/CodeGen/PBQP/HeuristicSolver.h"
48 #include "llvm/CodeGen/PBQP/Graph.h"
49 #include "llvm/CodeGen/PBQP/Heuristics/Briggs.h"
50 #include "llvm/CodeGen/RegAllocRegistry.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetInstrInfo.h"
54 #include "llvm/Target/TargetMachine.h"
55 #include <limits>
56 #include <memory>
57 #include <set>
58 #include <vector>
59
60 using namespace llvm;
61
62 static RegisterRegAlloc
63 registerPBQPRepAlloc("pbqp", "PBQP register allocator",
64                        createDefaultPBQPRegisterAllocator);
65
66 static cl::opt<bool>
67 pbqpCoalescing("pbqp-coalescing",
68                 cl::desc("Attempt coalescing during PBQP register allocation."),
69                 cl::init(false), cl::Hidden);
70
71 static cl::opt<bool>
72 pbqpPreSplitting("pbqp-pre-splitting",
73                  cl::desc("Pre-split before PBQP register allocation."),
74                  cl::init(false), cl::Hidden);
75
76 namespace {
77
78 ///
79 /// PBQP based allocators solve the register allocation problem by mapping
80 /// register allocation problems to Partitioned Boolean Quadratic
81 /// Programming problems.
82 class RegAllocPBQP : public MachineFunctionPass {
83 public:
84
85   static char ID;
86
87   /// Construct a PBQP register allocator.
88   RegAllocPBQP(std::auto_ptr<PBQPBuilder> b, char *cPassID=0)
89       : MachineFunctionPass(ID), builder(b), customPassID(cPassID) {
90     initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
91     initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
92     initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
93     initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
94     initializeLiveStacksPass(*PassRegistry::getPassRegistry());
95     initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
96     initializeLoopSplitterPass(*PassRegistry::getPassRegistry());
97     initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
98     initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
99   }
100
101   /// Return the pass name.
102   virtual const char* getPassName() const {
103     return "PBQP Register Allocator";
104   }
105
106   /// PBQP analysis usage.
107   virtual void getAnalysisUsage(AnalysisUsage &au) const;
108
109   /// Perform register allocation
110   virtual bool runOnMachineFunction(MachineFunction &MF);
111
112 private:
113
114   typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
115   typedef std::vector<const LiveInterval*> Node2LIMap;
116   typedef std::vector<unsigned> AllowedSet;
117   typedef std::vector<AllowedSet> AllowedSetMap;
118   typedef std::pair<unsigned, unsigned> RegPair;
119   typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
120   typedef std::vector<PBQP::Graph::NodeItr> NodeVector;
121   typedef std::set<unsigned> RegSet;
122
123
124   std::auto_ptr<PBQPBuilder> builder;
125
126   char *customPassID;
127
128   MachineFunction *mf;
129   const TargetMachine *tm;
130   const TargetRegisterInfo *tri;
131   const TargetInstrInfo *tii;
132   const MachineLoopInfo *loopInfo;
133   MachineRegisterInfo *mri;
134   RenderMachineFunction *rmf;
135
136   std::auto_ptr<Spiller> spiller;
137   LiveIntervals *lis;
138   LiveStacks *lss;
139   VirtRegMap *vrm;
140
141   RegSet vregsToAlloc, emptyIntervalVRegs;
142
143   /// \brief Finds the initial set of vreg intervals to allocate.
144   void findVRegIntervalsToAlloc();
145
146   /// \brief Given a solved PBQP problem maps this solution back to a register
147   /// assignment.
148   bool mapPBQPToRegAlloc(const PBQPRAProblem &problem,
149                          const PBQP::Solution &solution);
150
151   /// \brief Postprocessing before final spilling. Sets basic block "live in"
152   /// variables.
153   void finalizeAlloc() const;
154
155 };
156
157 char RegAllocPBQP::ID = 0;
158
159 } // End anonymous namespace.
160
161 unsigned PBQPRAProblem::getVRegForNode(PBQP::Graph::ConstNodeItr node) const {
162   Node2VReg::const_iterator vregItr = node2VReg.find(node);
163   assert(vregItr != node2VReg.end() && "No vreg for node.");
164   return vregItr->second;
165 }
166
167 PBQP::Graph::NodeItr PBQPRAProblem::getNodeForVReg(unsigned vreg) const {
168   VReg2Node::const_iterator nodeItr = vreg2Node.find(vreg);
169   assert(nodeItr != vreg2Node.end() && "No node for vreg.");
170   return nodeItr->second;
171   
172 }
173
174 const PBQPRAProblem::AllowedSet&
175   PBQPRAProblem::getAllowedSet(unsigned vreg) const {
176   AllowedSetMap::const_iterator allowedSetItr = allowedSets.find(vreg);
177   assert(allowedSetItr != allowedSets.end() && "No pregs for vreg.");
178   const AllowedSet &allowedSet = allowedSetItr->second;
179   return allowedSet;
180 }
181
182 unsigned PBQPRAProblem::getPRegForOption(unsigned vreg, unsigned option) const {
183   assert(isPRegOption(vreg, option) && "Not a preg option.");
184
185   const AllowedSet& allowedSet = getAllowedSet(vreg);
186   assert(option <= allowedSet.size() && "Option outside allowed set.");
187   return allowedSet[option - 1];
188 }
189
190 std::auto_ptr<PBQPRAProblem> PBQPBuilder::build(MachineFunction *mf,
191                                                 const LiveIntervals *lis,
192                                                 const MachineLoopInfo *loopInfo,
193                                                 const RegSet &vregs) {
194
195   typedef std::vector<const LiveInterval*> LIVector;
196
197   MachineRegisterInfo *mri = &mf->getRegInfo();
198   const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();  
199
200   std::auto_ptr<PBQPRAProblem> p(new PBQPRAProblem());
201   PBQP::Graph &g = p->getGraph();
202   RegSet pregs;
203
204   // Collect the set of preg intervals, record that they're used in the MF.
205   for (LiveIntervals::const_iterator itr = lis->begin(), end = lis->end();
206        itr != end; ++itr) {
207     if (TargetRegisterInfo::isPhysicalRegister(itr->first)) {
208       pregs.insert(itr->first);
209       mri->setPhysRegUsed(itr->first);
210     }
211   }
212
213   BitVector reservedRegs = tri->getReservedRegs(*mf);
214
215   // Iterate over vregs. 
216   for (RegSet::const_iterator vregItr = vregs.begin(), vregEnd = vregs.end();
217        vregItr != vregEnd; ++vregItr) {
218     unsigned vreg = *vregItr;
219     const TargetRegisterClass *trc = mri->getRegClass(vreg);
220     const LiveInterval *vregLI = &lis->getInterval(vreg);
221
222     // Compute an initial allowed set for the current vreg.
223     typedef std::vector<unsigned> VRAllowed;
224     VRAllowed vrAllowed;
225     ArrayRef<unsigned> rawOrder = trc->getRawAllocationOrder(*mf);
226     for (unsigned i = 0; i != rawOrder.size(); ++i) {
227       unsigned preg = rawOrder[i];
228       if (!reservedRegs.test(preg)) {
229         vrAllowed.push_back(preg);
230       }
231     }
232
233     // Remove any physical registers which overlap.
234     for (RegSet::const_iterator pregItr = pregs.begin(),
235                                 pregEnd = pregs.end();
236          pregItr != pregEnd; ++pregItr) {
237       unsigned preg = *pregItr;
238       const LiveInterval *pregLI = &lis->getInterval(preg);
239
240       if (pregLI->empty()) {
241         continue;
242       }
243
244       if (!vregLI->overlaps(*pregLI)) {
245         continue;
246       }
247
248       // Remove the register from the allowed set.
249       VRAllowed::iterator eraseItr =
250         std::find(vrAllowed.begin(), vrAllowed.end(), preg);
251
252       if (eraseItr != vrAllowed.end()) {
253         vrAllowed.erase(eraseItr);
254       }
255
256       // Also remove any aliases.
257       const unsigned *aliasItr = tri->getAliasSet(preg);
258       if (aliasItr != 0) {
259         for (; *aliasItr != 0; ++aliasItr) {
260           VRAllowed::iterator eraseItr =
261             std::find(vrAllowed.begin(), vrAllowed.end(), *aliasItr);
262
263           if (eraseItr != vrAllowed.end()) {
264             vrAllowed.erase(eraseItr);
265           }
266         }
267       }
268     }
269
270     // Construct the node.
271     PBQP::Graph::NodeItr node = 
272       g.addNode(PBQP::Vector(vrAllowed.size() + 1, 0));
273
274     // Record the mapping and allowed set in the problem.
275     p->recordVReg(vreg, node, vrAllowed.begin(), vrAllowed.end());
276
277     PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
278         vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
279
280     addSpillCosts(g.getNodeCosts(node), spillCost);
281   }
282
283   for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
284          vr1Itr != vrEnd; ++vr1Itr) {
285     unsigned vr1 = *vr1Itr;
286     const LiveInterval &l1 = lis->getInterval(vr1);
287     const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
288
289     for (RegSet::const_iterator vr2Itr = llvm::next(vr1Itr);
290          vr2Itr != vrEnd; ++vr2Itr) {
291       unsigned vr2 = *vr2Itr;
292       const LiveInterval &l2 = lis->getInterval(vr2);
293       const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
294
295       assert(!l2.empty() && "Empty interval in vreg set?");
296       if (l1.overlaps(l2)) {
297         PBQP::Graph::EdgeItr edge =
298           g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
299                     PBQP::Matrix(vr1Allowed.size()+1, vr2Allowed.size()+1, 0));
300
301         addInterferenceCosts(g.getEdgeCosts(edge), vr1Allowed, vr2Allowed, tri);
302       }
303     }
304   }
305
306   return p;
307 }
308
309 void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
310                                 PBQP::PBQPNum spillCost) {
311   costVec[0] = spillCost;
312 }
313
314 void PBQPBuilder::addInterferenceCosts(
315                                     PBQP::Matrix &costMat,
316                                     const PBQPRAProblem::AllowedSet &vr1Allowed,
317                                     const PBQPRAProblem::AllowedSet &vr2Allowed,
318                                     const TargetRegisterInfo *tri) {
319   assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
320   assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
321
322   for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
323     unsigned preg1 = vr1Allowed[i];
324
325     for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
326       unsigned preg2 = vr2Allowed[j];
327
328       if (tri->regsOverlap(preg1, preg2)) {
329         costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
330       }
331     }
332   }
333 }
334
335 std::auto_ptr<PBQPRAProblem> PBQPBuilderWithCoalescing::build(
336                                                 MachineFunction *mf,
337                                                 const LiveIntervals *lis,
338                                                 const MachineLoopInfo *loopInfo,
339                                                 const RegSet &vregs) {
340
341   std::auto_ptr<PBQPRAProblem> p = PBQPBuilder::build(mf, lis, loopInfo, vregs);
342   PBQP::Graph &g = p->getGraph();
343
344   const TargetMachine &tm = mf->getTarget();
345   CoalescerPair cp(*tm.getInstrInfo(), *tm.getRegisterInfo());
346
347   // Scan the machine function and add a coalescing cost whenever CoalescerPair
348   // gives the Ok.
349   for (MachineFunction::const_iterator mbbItr = mf->begin(),
350                                        mbbEnd = mf->end();
351        mbbItr != mbbEnd; ++mbbItr) {
352     const MachineBasicBlock *mbb = &*mbbItr;
353
354     for (MachineBasicBlock::const_iterator miItr = mbb->begin(),
355                                            miEnd = mbb->end();
356          miItr != miEnd; ++miItr) {
357       const MachineInstr *mi = &*miItr;
358
359       if (!cp.setRegisters(mi)) {
360         continue; // Not coalescable.
361       }
362
363       if (cp.getSrcReg() == cp.getDstReg()) {
364         continue; // Already coalesced.
365       }
366
367       unsigned dst = cp.getDstReg(),
368                src = cp.getSrcReg();
369
370       const float copyFactor = 0.5; // Cost of copy relative to load. Current
371       // value plucked randomly out of the air.
372                                       
373       PBQP::PBQPNum cBenefit =
374         copyFactor * LiveIntervals::getSpillWeight(false, true,
375                                                    loopInfo->getLoopDepth(mbb));
376
377       if (cp.isPhys()) {
378         if (!lis->isAllocatable(dst)) {
379           continue;
380         }
381
382         const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
383         unsigned pregOpt = 0;  
384         while (pregOpt < allowed.size() && allowed[pregOpt] != dst) {
385           ++pregOpt;
386         }
387         if (pregOpt < allowed.size()) {
388           ++pregOpt; // +1 to account for spill option.
389           PBQP::Graph::NodeItr node = p->getNodeForVReg(src);
390           addPhysRegCoalesce(g.getNodeCosts(node), pregOpt, cBenefit);
391         }
392       } else {
393         const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
394         const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
395         PBQP::Graph::NodeItr node1 = p->getNodeForVReg(dst);
396         PBQP::Graph::NodeItr node2 = p->getNodeForVReg(src);
397         PBQP::Graph::EdgeItr edge = g.findEdge(node1, node2);
398         if (edge == g.edgesEnd()) {
399           edge = g.addEdge(node1, node2, PBQP::Matrix(allowed1->size() + 1,
400                                                       allowed2->size() + 1,
401                                                       0));
402         } else {
403           if (g.getEdgeNode1(edge) == node2) {
404             std::swap(node1, node2);
405             std::swap(allowed1, allowed2);
406           }
407         }
408             
409         addVirtRegCoalesce(g.getEdgeCosts(edge), *allowed1, *allowed2,
410                            cBenefit);
411       }
412     }
413   }
414
415   return p;
416 }
417
418 void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
419                                                    unsigned pregOption,
420                                                    PBQP::PBQPNum benefit) {
421   costVec[pregOption] += -benefit;
422 }
423
424 void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
425                                     PBQP::Matrix &costMat,
426                                     const PBQPRAProblem::AllowedSet &vr1Allowed,
427                                     const PBQPRAProblem::AllowedSet &vr2Allowed,
428                                     PBQP::PBQPNum benefit) {
429
430   assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
431   assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
432
433   for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
434     unsigned preg1 = vr1Allowed[i];
435     for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
436       unsigned preg2 = vr2Allowed[j];
437
438       if (preg1 == preg2) {
439         costMat[i + 1][j + 1] += -benefit;
440       } 
441     }
442   }
443 }
444
445
446 void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
447   au.addRequired<SlotIndexes>();
448   au.addPreserved<SlotIndexes>();
449   au.addRequired<LiveIntervals>();
450   //au.addRequiredID(SplitCriticalEdgesID);
451   au.addRequiredID(RegisterCoalescerPassID);
452   if (customPassID)
453     au.addRequiredID(*customPassID);
454   au.addRequired<CalculateSpillWeights>();
455   au.addRequired<LiveStacks>();
456   au.addPreserved<LiveStacks>();
457   au.addRequired<MachineLoopInfo>();
458   au.addPreserved<MachineLoopInfo>();
459   if (pbqpPreSplitting)
460     au.addRequired<LoopSplitter>();
461   au.addRequired<VirtRegMap>();
462   au.addRequired<RenderMachineFunction>();
463   MachineFunctionPass::getAnalysisUsage(au);
464 }
465
466 void RegAllocPBQP::findVRegIntervalsToAlloc() {
467
468   // Iterate over all live ranges.
469   for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
470        itr != end; ++itr) {
471
472     // Ignore physical ones.
473     if (TargetRegisterInfo::isPhysicalRegister(itr->first))
474       continue;
475
476     LiveInterval *li = itr->second;
477
478     // If this live interval is non-empty we will use pbqp to allocate it.
479     // Empty intervals we allocate in a simple post-processing stage in
480     // finalizeAlloc.
481     if (!li->empty()) {
482       vregsToAlloc.insert(li->reg);
483     } else {
484       emptyIntervalVRegs.insert(li->reg);
485     }
486   }
487 }
488
489 bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
490                                      const PBQP::Solution &solution) {
491   // Set to true if we have any spills
492   bool anotherRoundNeeded = false;
493
494   // Clear the existing allocation.
495   vrm->clearAllVirt();
496
497   const PBQP::Graph &g = problem.getGraph();
498   // Iterate over the nodes mapping the PBQP solution to a register
499   // assignment.
500   for (PBQP::Graph::ConstNodeItr node = g.nodesBegin(),
501                                  nodeEnd = g.nodesEnd();
502        node != nodeEnd; ++node) {
503     unsigned vreg = problem.getVRegForNode(node);
504     unsigned alloc = solution.getSelection(node);
505
506     if (problem.isPRegOption(vreg, alloc)) {
507       unsigned preg = problem.getPRegForOption(vreg, alloc);    
508       DEBUG(dbgs() << "VREG " << vreg << " -> " << tri->getName(preg) << "\n");
509       assert(preg != 0 && "Invalid preg selected.");
510       vrm->assignVirt2Phys(vreg, preg);      
511     } else if (problem.isSpillOption(vreg, alloc)) {
512       vregsToAlloc.erase(vreg);
513       SmallVector<LiveInterval*, 8> newSpills;
514       LiveRangeEdit LRE(lis->getInterval(vreg), newSpills);
515       spiller->spill(LRE);
516
517       DEBUG(dbgs() << "VREG " << vreg << " -> SPILLED (Cost: "
518                    << LRE.getParent().weight << ", New vregs: ");
519
520       // Copy any newly inserted live intervals into the list of regs to
521       // allocate.
522       for (LiveRangeEdit::iterator itr = LRE.begin(), end = LRE.end();
523            itr != end; ++itr) {
524         assert(!(*itr)->empty() && "Empty spill range.");
525         DEBUG(dbgs() << (*itr)->reg << " ");
526         vregsToAlloc.insert((*itr)->reg);
527       }
528
529       DEBUG(dbgs() << ")\n");
530
531       // We need another round if spill intervals were added.
532       anotherRoundNeeded |= !LRE.empty();
533     } else {
534       assert(false && "Unknown allocation option.");
535     }
536   }
537
538   return !anotherRoundNeeded;
539 }
540
541
542 void RegAllocPBQP::finalizeAlloc() const {
543   typedef LiveIntervals::iterator LIIterator;
544   typedef LiveInterval::Ranges::const_iterator LRIterator;
545
546   // First allocate registers for the empty intervals.
547   for (RegSet::const_iterator
548          itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
549          itr != end; ++itr) {
550     LiveInterval *li = &lis->getInterval(*itr);
551
552     unsigned physReg = vrm->getRegAllocPref(li->reg);
553
554     if (physReg == 0) {
555       const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
556       physReg = liRC->getRawAllocationOrder(*mf).front();
557     }
558
559     vrm->assignVirt2Phys(li->reg, physReg);
560   }
561
562   // Finally iterate over the basic blocks to compute and set the live-in sets.
563   SmallVector<MachineBasicBlock*, 8> liveInMBBs;
564   MachineBasicBlock *entryMBB = &*mf->begin();
565
566   for (LIIterator liItr = lis->begin(), liEnd = lis->end();
567        liItr != liEnd; ++liItr) {
568
569     const LiveInterval *li = liItr->second;
570     unsigned reg = 0;
571
572     // Get the physical register for this interval
573     if (TargetRegisterInfo::isPhysicalRegister(li->reg)) {
574       reg = li->reg;
575     } else if (vrm->isAssignedReg(li->reg)) {
576       reg = vrm->getPhys(li->reg);
577     } else {
578       // Ranges which are assigned a stack slot only are ignored.
579       continue;
580     }
581
582     if (reg == 0) {
583       // Filter out zero regs - they're for intervals that were spilled.
584       continue;
585     }
586
587     // Iterate over the ranges of the current interval...
588     for (LRIterator lrItr = li->begin(), lrEnd = li->end();
589          lrItr != lrEnd; ++lrItr) {
590
591       // Find the set of basic blocks which this range is live into...
592       if (lis->findLiveInMBBs(lrItr->start, lrItr->end,  liveInMBBs)) {
593         // And add the physreg for this interval to their live-in sets.
594         for (unsigned i = 0; i != liveInMBBs.size(); ++i) {
595           if (liveInMBBs[i] != entryMBB) {
596             if (!liveInMBBs[i]->isLiveIn(reg)) {
597               liveInMBBs[i]->addLiveIn(reg);
598             }
599           }
600         }
601         liveInMBBs.clear();
602       }
603     }
604   }
605
606 }
607
608 bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
609
610   mf = &MF;
611   tm = &mf->getTarget();
612   tri = tm->getRegisterInfo();
613   tii = tm->getInstrInfo();
614   mri = &mf->getRegInfo(); 
615
616   lis = &getAnalysis<LiveIntervals>();
617   lss = &getAnalysis<LiveStacks>();
618   loopInfo = &getAnalysis<MachineLoopInfo>();
619   rmf = &getAnalysis<RenderMachineFunction>();
620
621   vrm = &getAnalysis<VirtRegMap>();
622   spiller.reset(createInlineSpiller(*this, MF, *vrm));
623
624
625   DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getFunction()->getName() << "\n");
626
627   // Allocator main loop:
628   //
629   // * Map current regalloc problem to a PBQP problem
630   // * Solve the PBQP problem
631   // * Map the solution back to a register allocation
632   // * Spill if necessary
633   //
634   // This process is continued till no more spills are generated.
635
636   // Find the vreg intervals in need of allocation.
637   findVRegIntervalsToAlloc();
638
639   // If there are non-empty intervals allocate them using pbqp.
640   if (!vregsToAlloc.empty()) {
641
642     bool pbqpAllocComplete = false;
643     unsigned round = 0;
644
645     while (!pbqpAllocComplete) {
646       DEBUG(dbgs() << "  PBQP Regalloc round " << round << ":\n");
647
648       std::auto_ptr<PBQPRAProblem> problem =
649         builder->build(mf, lis, loopInfo, vregsToAlloc);
650       PBQP::Solution solution =
651         PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(
652           problem->getGraph());
653
654       pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
655
656       ++round;
657     }
658   }
659
660   // Finalise allocation, allocate empty ranges.
661   finalizeAlloc();
662
663   rmf->renderMachineFunction("After PBQP register allocation.", vrm);
664
665   vregsToAlloc.clear();
666   emptyIntervalVRegs.clear();
667
668   DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
669
670   // Run rewriter
671   vrm->rewrite(lis->getSlotIndexes());
672
673   return true;
674 }
675
676 FunctionPass* llvm::createPBQPRegisterAllocator(
677                                            std::auto_ptr<PBQPBuilder> builder,
678                                            char *customPassID) {
679   return new RegAllocPBQP(builder, customPassID);
680 }
681
682 FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
683   if (pbqpCoalescing) {
684     return createPBQPRegisterAllocator(
685              std::auto_ptr<PBQPBuilder>(new PBQPBuilderWithCoalescing()));
686   } // else
687   return createPBQPRegisterAllocator(
688            std::auto_ptr<PBQPBuilder>(new PBQPBuilder()));
689 }
690
691 #undef DEBUG_TYPE