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