Moved the PBQP allocator class out of the header and back in to the cpp file to hide...
[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 pbqpBuilder("pbqp-builder",
72              cl::desc("Use new builder system."),
73              cl::init(true), cl::Hidden);
74
75
76 static cl::opt<bool>
77 pbqpPreSplitting("pbqp-pre-splitting",
78                  cl::desc("Pre-split before PBQP register allocation."),
79                  cl::init(false), cl::Hidden);
80
81 namespace {
82
83 ///
84 /// PBQP based allocators solve the register allocation problem by mapping
85 /// register allocation problems to Partitioned Boolean Quadratic
86 /// Programming problems.
87 class RegAllocPBQP : public MachineFunctionPass {
88 public:
89
90   static char ID;
91
92   /// Construct a PBQP register allocator.
93   RegAllocPBQP(std::auto_ptr<PBQPBuilder> b) : MachineFunctionPass(ID), builder(b) {}
94
95   /// Return the pass name.
96   virtual const char* getPassName() const {
97     return "PBQP Register Allocator";
98   }
99
100   /// PBQP analysis usage.
101   virtual void getAnalysisUsage(AnalysisUsage &au) const;
102
103   /// Perform register allocation
104   virtual bool runOnMachineFunction(MachineFunction &MF);
105
106 private:
107
108   typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
109   typedef std::vector<const LiveInterval*> Node2LIMap;
110   typedef std::vector<unsigned> AllowedSet;
111   typedef std::vector<AllowedSet> AllowedSetMap;
112   typedef std::pair<unsigned, unsigned> RegPair;
113   typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
114   typedef std::vector<PBQP::Graph::NodeItr> NodeVector;
115   typedef std::set<unsigned> RegSet;
116
117
118   std::auto_ptr<PBQPBuilder> builder;
119
120   MachineFunction *mf;
121   const TargetMachine *tm;
122   const TargetRegisterInfo *tri;
123   const TargetInstrInfo *tii;
124   const MachineLoopInfo *loopInfo;
125   MachineRegisterInfo *mri;
126   RenderMachineFunction *rmf;
127
128   LiveIntervals *lis;
129   LiveStacks *lss;
130   VirtRegMap *vrm;
131
132   LI2NodeMap li2Node;
133   Node2LIMap node2LI;
134   AllowedSetMap allowedSets;
135   RegSet vregsToAlloc, emptyIntervalVRegs;
136   NodeVector problemNodes;
137
138
139   /// Builds a PBQP cost vector.
140   template <typename RegContainer>
141   PBQP::Vector buildCostVector(unsigned vReg,
142                                const RegContainer &allowed,
143                                const CoalesceMap &cealesces,
144                                PBQP::PBQPNum spillCost) const;
145
146   /// \brief Builds a PBQP interference matrix.
147   ///
148   /// @return Either a pointer to a non-zero PBQP matrix representing the
149   ///         allocation option costs, or a null pointer for a zero matrix.
150   ///
151   /// Expects allowed sets for two interfering LiveIntervals. These allowed
152   /// sets should contain only allocable registers from the LiveInterval's
153   /// register class, with any interfering pre-colored registers removed.
154   template <typename RegContainer>
155   PBQP::Matrix* buildInterferenceMatrix(const RegContainer &allowed1,
156                                         const RegContainer &allowed2) const;
157
158   ///
159   /// Expects allowed sets for two potentially coalescable LiveIntervals,
160   /// and an estimated benefit due to coalescing. The allowed sets should
161   /// contain only allocable registers from the LiveInterval's register
162   /// classes, with any interfering pre-colored registers removed.
163   template <typename RegContainer>
164   PBQP::Matrix* buildCoalescingMatrix(const RegContainer &allowed1,
165                                       const RegContainer &allowed2,
166                                       PBQP::PBQPNum cBenefit) const;
167
168   /// \brief Finds coalescing opportunities and returns them as a map.
169   ///
170   /// Any entries in the map are guaranteed coalescable, even if their
171   /// corresponding live intervals overlap.
172   CoalesceMap findCoalesces();
173
174   /// \brief Finds the initial set of vreg intervals to allocate.
175   void findVRegIntervalsToAlloc();
176
177   /// \brief Constructs a PBQP problem representation of the register
178   /// allocation problem for this function.
179   ///
180   /// Old Construction Process - this functionality has been subsumed
181   /// by PBQPBuilder. This function will only be hanging around for a little
182   /// while until the new system has been fully tested.
183   /// 
184   /// @return a PBQP solver object for the register allocation problem.
185   PBQP::Graph constructPBQPProblemOld();
186
187   /// \brief Adds a stack interval if the given live interval has been
188   /// spilled. Used to support stack slot coloring.
189   void addStackInterval(const LiveInterval *spilled,MachineRegisterInfo* mri);
190
191   /// \brief Given a solved PBQP problem maps this solution back to a register
192   /// assignment.
193   ///
194   /// Old Construction Process - this functionality has been subsumed
195   /// by PBQPBuilder. This function will only be hanging around for a little
196   /// while until the new system has been fully tested.
197   /// 
198   bool mapPBQPToRegAllocOld(const PBQP::Solution &solution);
199
200   /// \brief Given a solved PBQP problem maps this solution back to a register
201   /// assignment.
202   bool mapPBQPToRegAlloc(const PBQPRAProblem &problem,
203                          const PBQP::Solution &solution);
204
205   /// \brief Postprocessing before final spilling. Sets basic block "live in"
206   /// variables.
207   void finalizeAlloc() const;
208
209 };
210
211 char RegAllocPBQP::ID = 0;
212
213 } // End anonymous namespace.
214
215 unsigned PBQPRAProblem::getVRegForNode(PBQP::Graph::ConstNodeItr node) const {
216   Node2VReg::const_iterator vregItr = node2VReg.find(node);
217   assert(vregItr != node2VReg.end() && "No vreg for node.");
218   return vregItr->second;
219 }
220
221 PBQP::Graph::NodeItr PBQPRAProblem::getNodeForVReg(unsigned vreg) const {
222   VReg2Node::const_iterator nodeItr = vreg2Node.find(vreg);
223   assert(nodeItr != vreg2Node.end() && "No node for vreg.");
224   return nodeItr->second;
225   
226 }
227
228 const PBQPRAProblem::AllowedSet&
229   PBQPRAProblem::getAllowedSet(unsigned vreg) const {
230   AllowedSetMap::const_iterator allowedSetItr = allowedSets.find(vreg);
231   assert(allowedSetItr != allowedSets.end() && "No pregs for vreg.");
232   const AllowedSet &allowedSet = allowedSetItr->second;
233   return allowedSet;
234 }
235
236 unsigned PBQPRAProblem::getPRegForOption(unsigned vreg, unsigned option) const {
237   assert(isPRegOption(vreg, option) && "Not a preg option.");
238
239   const AllowedSet& allowedSet = getAllowedSet(vreg);
240   assert(option <= allowedSet.size() && "Option outside allowed set.");
241   return allowedSet[option - 1];
242 }
243
244 std::auto_ptr<PBQPRAProblem> PBQPBuilder::build(MachineFunction *mf,
245                                                 const LiveIntervals *lis,
246                                                 const MachineLoopInfo *loopInfo,
247                                                 const RegSet &vregs) {
248
249   typedef std::vector<const LiveInterval*> LIVector;
250
251   MachineRegisterInfo *mri = &mf->getRegInfo();
252   const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();  
253
254   std::auto_ptr<PBQPRAProblem> p(new PBQPRAProblem());
255   PBQP::Graph &g = p->getGraph();
256   RegSet pregs;
257
258   // Collect the set of preg intervals, record that they're used in the MF.
259   for (LiveIntervals::const_iterator itr = lis->begin(), end = lis->end();
260        itr != end; ++itr) {
261     if (TargetRegisterInfo::isPhysicalRegister(itr->first)) {
262       pregs.insert(itr->first);
263       mri->setPhysRegUsed(itr->first);
264     }
265   }
266
267   BitVector reservedRegs = tri->getReservedRegs(*mf);
268
269   // Iterate over vregs. 
270   for (RegSet::const_iterator vregItr = vregs.begin(), vregEnd = vregs.end();
271        vregItr != vregEnd; ++vregItr) {
272     unsigned vreg = *vregItr;
273     const TargetRegisterClass *trc = mri->getRegClass(vreg);
274     const LiveInterval *vregLI = &lis->getInterval(vreg);
275
276     // Compute an initial allowed set for the current vreg.
277     typedef std::vector<unsigned> VRAllowed;
278     VRAllowed vrAllowed;
279     for (TargetRegisterClass::iterator aoItr = trc->allocation_order_begin(*mf),
280                                        aoEnd = trc->allocation_order_end(*mf);
281          aoItr != aoEnd; ++aoItr) {
282       unsigned preg = *aoItr;
283       if (!reservedRegs.test(preg)) {
284         vrAllowed.push_back(preg);
285       }
286     }
287
288     // Remove any physical registers which overlap.
289     for (RegSet::const_iterator pregItr = pregs.begin(),
290                                 pregEnd = pregs.end();
291          pregItr != pregEnd; ++pregItr) {
292       unsigned preg = *pregItr;
293       const LiveInterval *pregLI = &lis->getInterval(preg);
294
295       if (pregLI->empty())
296         continue;
297
298       if (!vregLI->overlaps(*pregLI))
299         continue;
300
301       // Remove the register from the allowed set.
302       VRAllowed::iterator eraseItr =
303         std::find(vrAllowed.begin(), vrAllowed.end(), preg);
304
305       if (eraseItr != vrAllowed.end()) {
306         vrAllowed.erase(eraseItr);
307       }
308
309       // Also remove any aliases.
310       const unsigned *aliasItr = tri->getAliasSet(preg);
311       if (aliasItr != 0) {
312         for (; *aliasItr != 0; ++aliasItr) {
313           VRAllowed::iterator eraseItr =
314             std::find(vrAllowed.begin(), vrAllowed.end(), *aliasItr);
315
316           if (eraseItr != vrAllowed.end()) {
317             vrAllowed.erase(eraseItr);
318           }
319         }
320       }
321     }
322
323     // Construct the node.
324     PBQP::Graph::NodeItr node = 
325       g.addNode(PBQP::Vector(vrAllowed.size() + 1, 0));
326
327     // Record the mapping and allowed set in the problem.
328     p->recordVReg(vreg, node, vrAllowed.begin(), vrAllowed.end());
329
330     PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
331         vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
332
333     addSpillCosts(g.getNodeCosts(node), spillCost);
334   }
335
336   for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
337          vr1Itr != vrEnd; ++vr1Itr) {
338     unsigned vr1 = *vr1Itr;
339     const LiveInterval &l1 = lis->getInterval(vr1);
340     const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
341
342     for (RegSet::const_iterator vr2Itr = llvm::next(vr1Itr);
343          vr2Itr != vrEnd; ++vr2Itr) {
344       unsigned vr2 = *vr2Itr;
345       const LiveInterval &l2 = lis->getInterval(vr2);
346       const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
347
348       assert(!l2.empty() && "Empty interval in vreg set?");
349       if (l1.overlaps(l2)) {
350         PBQP::Graph::EdgeItr edge =
351           g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
352                     PBQP::Matrix(vr1Allowed.size()+1, vr2Allowed.size()+1, 0));
353
354         addInterferenceCosts(g.getEdgeCosts(edge), vr1Allowed, vr2Allowed, tri);
355       }
356     }
357   }
358
359   return p;
360 }
361
362 void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
363                                 PBQP::PBQPNum spillCost) {
364   costVec[0] = spillCost;
365 }
366
367 void PBQPBuilder::addInterferenceCosts(
368                                     PBQP::Matrix &costMat,
369                                     const PBQPRAProblem::AllowedSet &vr1Allowed,
370                                     const PBQPRAProblem::AllowedSet &vr2Allowed,
371                                     const TargetRegisterInfo *tri) {
372   assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
373   assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
374
375   for (unsigned i = 0; i < vr1Allowed.size(); ++i) {
376     unsigned preg1 = vr1Allowed[i];
377
378     for (unsigned j = 0; j < vr2Allowed.size(); ++j) {
379       unsigned preg2 = vr2Allowed[j];
380
381       if (tri->regsOverlap(preg1, preg2)) {
382         costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
383       }
384     }
385   }
386 }
387
388 std::auto_ptr<PBQPRAProblem> PBQPBuilderWithCoalescing::build(
389                                                 MachineFunction *mf,
390                                                 const LiveIntervals *lis,
391                                                 const MachineLoopInfo *loopInfo,
392                                                 const RegSet &vregs) {
393
394   std::auto_ptr<PBQPRAProblem> p = PBQPBuilder::build(mf, lis, loopInfo, vregs);
395   PBQP::Graph &g = p->getGraph();
396
397   const TargetMachine &tm = mf->getTarget();
398   CoalescerPair cp(*tm.getInstrInfo(), *tm.getRegisterInfo());
399
400   // Scan the machine function and add a coalescing cost whenever CoalescerPair
401   // gives the Ok.
402   for (MachineFunction::const_iterator mbbItr = mf->begin(),
403                                        mbbEnd = mf->end();
404        mbbItr != mbbEnd; ++mbbItr) {
405     const MachineBasicBlock *mbb = &*mbbItr;
406
407     for (MachineBasicBlock::const_iterator miItr = mbb->begin(),
408                                            miEnd = mbb->end();
409          miItr != miEnd; ++miItr) {
410       const MachineInstr *mi = &*miItr;
411
412       if (!cp.setRegisters(mi))
413         continue; // Not coalescable.
414
415       if (cp.getSrcReg() == cp.getDstReg())
416         continue; // Already coalesced.
417
418       unsigned dst = cp.getDstReg(),
419                src = cp.getSrcReg();
420
421       const float copyFactor = 0.5; // Cost of copy relative to load. Current
422       // value plucked randomly out of the air.
423                                       
424       PBQP::PBQPNum cBenefit =
425         copyFactor * LiveIntervals::getSpillWeight(false, true,
426                                                    loopInfo->getLoopDepth(mbb));
427
428       if (cp.isPhys()) {
429         if (!lis->isAllocatable(dst))
430           continue;
431
432         const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
433         unsigned pregOpt = 0;  
434         while (pregOpt < allowed.size() && allowed[pregOpt] != dst)
435           ++pregOpt;
436         if (pregOpt < allowed.size()) {
437           ++pregOpt; // +1 to account for spill option.
438           PBQP::Graph::NodeItr node = p->getNodeForVReg(src);
439           addPhysRegCoalesce(g.getNodeCosts(node), pregOpt, cBenefit);
440         }
441       } else {
442         const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
443         const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
444         PBQP::Graph::NodeItr node1 = p->getNodeForVReg(dst);
445         PBQP::Graph::NodeItr node2 = p->getNodeForVReg(src);
446         PBQP::Graph::EdgeItr edge = g.findEdge(node1, node2);
447         if (edge == g.edgesEnd()) {
448           edge = g.addEdge(node1, node2, PBQP::Matrix(allowed1->size() + 1,
449                                                       allowed2->size() + 1,
450                                                       0));
451         } else {
452           if (g.getEdgeNode1(edge) == node2) {
453             std::swap(node1, node2);
454             std::swap(allowed1, allowed2);
455           }
456         }
457             
458         addVirtRegCoalesce(g.getEdgeCosts(edge), *allowed1, *allowed2,
459                            cBenefit);
460       }
461     }
462   }
463
464   return p;
465 }
466
467 void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
468                                                    unsigned pregOption,
469                                                    PBQP::PBQPNum benefit) {
470   costVec[pregOption] += -benefit;
471 }
472
473 void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
474                                     PBQP::Matrix &costMat,
475                                     const PBQPRAProblem::AllowedSet &vr1Allowed,
476                                     const PBQPRAProblem::AllowedSet &vr2Allowed,
477                                     PBQP::PBQPNum benefit) {
478
479   assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
480   assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
481
482   for (unsigned i = 0; i < vr1Allowed.size(); ++i) {
483     unsigned preg1 = vr1Allowed[i];
484     for (unsigned j = 0; j < vr2Allowed.size(); ++j) {
485       unsigned preg2 = vr2Allowed[j];
486
487       if (preg1 == preg2) {
488         costMat[i + 1][j + 1] += -benefit;
489       } 
490     }
491   }
492 }
493
494
495 void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
496   au.addRequired<SlotIndexes>();
497   au.addPreserved<SlotIndexes>();
498   au.addRequired<LiveIntervals>();
499   //au.addRequiredID(SplitCriticalEdgesID);
500   au.addRequired<RegisterCoalescer>();
501   au.addRequired<CalculateSpillWeights>();
502   au.addRequired<LiveStacks>();
503   au.addPreserved<LiveStacks>();
504   au.addRequired<MachineLoopInfo>();
505   au.addPreserved<MachineLoopInfo>();
506   if (pbqpPreSplitting)
507     au.addRequired<LoopSplitter>();
508   au.addRequired<VirtRegMap>();
509   au.addRequired<RenderMachineFunction>();
510   MachineFunctionPass::getAnalysisUsage(au);
511 }
512
513 template <typename RegContainer>
514 PBQP::Vector RegAllocPBQP::buildCostVector(unsigned vReg,
515                                            const RegContainer &allowed,
516                                            const CoalesceMap &coalesces,
517                                            PBQP::PBQPNum spillCost) const {
518
519   typedef typename RegContainer::const_iterator AllowedItr;
520
521   // Allocate vector. Additional element (0th) used for spill option
522   PBQP::Vector v(allowed.size() + 1, 0);
523
524   v[0] = spillCost;
525
526   // Iterate over the allowed registers inserting coalesce benefits if there
527   // are any.
528   unsigned ai = 0;
529   for (AllowedItr itr = allowed.begin(), end = allowed.end();
530        itr != end; ++itr, ++ai) {
531
532     unsigned pReg = *itr;
533
534     CoalesceMap::const_iterator cmItr =
535       coalesces.find(RegPair(vReg, pReg));
536
537     // No coalesce - on to the next preg.
538     if (cmItr == coalesces.end())
539       continue;
540
541     // We have a coalesce - insert the benefit.
542     v[ai + 1] = -cmItr->second;
543   }
544
545   return v;
546 }
547
548 template <typename RegContainer>
549 PBQP::Matrix* RegAllocPBQP::buildInterferenceMatrix(
550       const RegContainer &allowed1, const RegContainer &allowed2) const {
551
552   typedef typename RegContainer::const_iterator RegContainerIterator;
553
554   // Construct a PBQP matrix representing the cost of allocation options. The
555   // rows and columns correspond to the allocation options for the two live
556   // intervals.  Elements will be infinite where corresponding registers alias,
557   // since we cannot allocate aliasing registers to interfering live intervals.
558   // All other elements (non-aliasing combinations) will have zero cost. Note
559   // that the spill option (element 0,0) has zero cost, since we can allocate
560   // both intervals to memory safely (the cost for each individual allocation
561   // to memory is accounted for by the cost vectors for each live interval).
562   PBQP::Matrix *m =
563     new PBQP::Matrix(allowed1.size() + 1, allowed2.size() + 1, 0);
564
565   // Assume this is a zero matrix until proven otherwise.  Zero matrices occur
566   // between interfering live ranges with non-overlapping register sets (e.g.
567   // non-overlapping reg classes, or disjoint sets of allowed regs within the
568   // same class). The term "overlapping" is used advisedly: sets which do not
569   // intersect, but contain registers which alias, will have non-zero matrices.
570   // We optimize zero matrices away to improve solver speed.
571   bool isZeroMatrix = true;
572
573
574   // Row index. Starts at 1, since the 0th row is for the spill option, which
575   // is always zero.
576   unsigned ri = 1;
577
578   // Iterate over allowed sets, insert infinities where required.
579   for (RegContainerIterator a1Itr = allowed1.begin(), a1End = allowed1.end();
580        a1Itr != a1End; ++a1Itr) {
581
582     // Column index, starts at 1 as for row index.
583     unsigned ci = 1;
584     unsigned reg1 = *a1Itr;
585
586     for (RegContainerIterator a2Itr = allowed2.begin(), a2End = allowed2.end();
587          a2Itr != a2End; ++a2Itr) {
588
589       unsigned reg2 = *a2Itr;
590
591       // If the row/column regs are identical or alias insert an infinity.
592       if (tri->regsOverlap(reg1, reg2)) {
593         (*m)[ri][ci] = std::numeric_limits<PBQP::PBQPNum>::infinity();
594         isZeroMatrix = false;
595       }
596
597       ++ci;
598     }
599
600     ++ri;
601   }
602
603   // If this turns out to be a zero matrix...
604   if (isZeroMatrix) {
605     // free it and return null.
606     delete m;
607     return 0;
608   }
609
610   // ...otherwise return the cost matrix.
611   return m;
612 }
613
614 template <typename RegContainer>
615 PBQP::Matrix* RegAllocPBQP::buildCoalescingMatrix(
616       const RegContainer &allowed1, const RegContainer &allowed2,
617       PBQP::PBQPNum cBenefit) const {
618
619   typedef typename RegContainer::const_iterator RegContainerIterator;
620
621   // Construct a PBQP Matrix representing the benefits of coalescing. As with
622   // interference matrices the rows and columns represent allowed registers
623   // for the LiveIntervals which are (potentially) to be coalesced. The amount
624   // -cBenefit will be placed in any element representing the same register
625   // for both intervals.
626   PBQP::Matrix *m =
627     new PBQP::Matrix(allowed1.size() + 1, allowed2.size() + 1, 0);
628
629   // Reset costs to zero.
630   m->reset(0);
631
632   // Assume the matrix is zero till proven otherwise. Zero matrices will be
633   // optimized away as in the interference case.
634   bool isZeroMatrix = true;
635
636   // Row index. Starts at 1, since the 0th row is for the spill option, which
637   // is always zero.
638   unsigned ri = 1;
639
640   // Iterate over the allowed sets, insert coalescing benefits where
641   // appropriate.
642   for (RegContainerIterator a1Itr = allowed1.begin(), a1End = allowed1.end();
643        a1Itr != a1End; ++a1Itr) {
644
645     // Column index, starts at 1 as for row index.
646     unsigned ci = 1;
647     unsigned reg1 = *a1Itr;
648
649     for (RegContainerIterator a2Itr = allowed2.begin(), a2End = allowed2.end();
650          a2Itr != a2End; ++a2Itr) {
651
652       // If the row and column represent the same register insert a beneficial
653       // cost to preference this allocation - it would allow us to eliminate a
654       // move instruction.
655       if (reg1 == *a2Itr) {
656         (*m)[ri][ci] = -cBenefit;
657         isZeroMatrix = false;
658       }
659
660       ++ci;
661     }
662
663     ++ri;
664   }
665
666   // If this turns out to be a zero matrix...
667   if (isZeroMatrix) {
668     // ...free it and return null.
669     delete m;
670     return 0;
671   }
672
673   return m;
674 }
675
676 RegAllocPBQP::CoalesceMap RegAllocPBQP::findCoalesces() {
677
678   typedef MachineFunction::const_iterator MFIterator;
679   typedef MachineBasicBlock::const_iterator MBBIterator;
680   typedef LiveInterval::const_vni_iterator VNIIterator;
681
682   CoalesceMap coalescesFound;
683
684   // To find coalesces we need to iterate over the function looking for
685   // copy instructions.
686   for (MFIterator bbItr = mf->begin(), bbEnd = mf->end();
687        bbItr != bbEnd; ++bbItr) {
688
689     const MachineBasicBlock *mbb = &*bbItr;
690
691     for (MBBIterator iItr = mbb->begin(), iEnd = mbb->end();
692          iItr != iEnd; ++iItr) {
693
694       const MachineInstr *instr = &*iItr;
695
696       // If this isn't a copy then continue to the next instruction.
697       if (!instr->isCopy())
698         continue;
699
700       unsigned srcReg = instr->getOperand(1).getReg();
701       unsigned dstReg = instr->getOperand(0).getReg();
702
703       // If the registers are already the same our job is nice and easy.
704       if (dstReg == srcReg)
705         continue;
706
707       bool srcRegIsPhysical = TargetRegisterInfo::isPhysicalRegister(srcReg),
708            dstRegIsPhysical = TargetRegisterInfo::isPhysicalRegister(dstReg);
709
710       // If both registers are physical then we can't coalesce.
711       if (srcRegIsPhysical && dstRegIsPhysical)
712         continue;
713
714       // If it's a copy that includes two virtual register but the source and
715       // destination classes differ then we can't coalesce.
716       if (!srcRegIsPhysical && !dstRegIsPhysical &&
717           mri->getRegClass(srcReg) != mri->getRegClass(dstReg))
718         continue;
719
720       // If one is physical and one is virtual, check that the physical is
721       // allocatable in the class of the virtual.
722       if (srcRegIsPhysical && !dstRegIsPhysical) {
723         const TargetRegisterClass *dstRegClass = mri->getRegClass(dstReg);
724         if (std::find(dstRegClass->allocation_order_begin(*mf),
725                       dstRegClass->allocation_order_end(*mf), srcReg) ==
726             dstRegClass->allocation_order_end(*mf))
727           continue;
728       }
729       if (!srcRegIsPhysical && dstRegIsPhysical) {
730         const TargetRegisterClass *srcRegClass = mri->getRegClass(srcReg);
731         if (std::find(srcRegClass->allocation_order_begin(*mf),
732                       srcRegClass->allocation_order_end(*mf), dstReg) ==
733             srcRegClass->allocation_order_end(*mf))
734           continue;
735       }
736
737       // If we've made it here we have a copy with compatible register classes.
738       // We can probably coalesce, but we need to consider overlap.
739       const LiveInterval *srcLI = &lis->getInterval(srcReg),
740                          *dstLI = &lis->getInterval(dstReg);
741
742       if (srcLI->overlaps(*dstLI)) {
743         // Even in the case of an overlap we might still be able to coalesce,
744         // but we need to make sure that no definition of either range occurs
745         // while the other range is live.
746
747         // Otherwise start by assuming we're ok.
748         bool badDef = false;
749
750         // Test all defs of the source range.
751         for (VNIIterator
752                vniItr = srcLI->vni_begin(), vniEnd = srcLI->vni_end();
753                vniItr != vniEnd; ++vniItr) {
754
755           // If we find a poorly defined def we err on the side of caution.
756           if (!(*vniItr)->def.isValid()) {
757             badDef = true;
758             break;
759           }
760
761           // If we find a def that kills the coalescing opportunity then
762           // record it and break from the loop.
763           if (dstLI->liveAt((*vniItr)->def)) {
764             badDef = true;
765             break;
766           }
767         }
768
769         // If we have a bad def give up, continue to the next instruction.
770         if (badDef)
771           continue;
772
773         // Otherwise test definitions of the destination range.
774         for (VNIIterator
775                vniItr = dstLI->vni_begin(), vniEnd = dstLI->vni_end();
776                vniItr != vniEnd; ++vniItr) {
777
778           // We want to make sure we skip the copy instruction itself.
779           if ((*vniItr)->getCopy() == instr)
780             continue;
781
782           if (!(*vniItr)->def.isValid()) {
783             badDef = true;
784             break;
785           }
786
787           if (srcLI->liveAt((*vniItr)->def)) {
788             badDef = true;
789             break;
790           }
791         }
792
793         // As before a bad def we give up and continue to the next instr.
794         if (badDef)
795           continue;
796       }
797
798       // If we make it to here then either the ranges didn't overlap, or they
799       // did, but none of their definitions would prevent us from coalescing.
800       // We're good to go with the coalesce.
801
802       float cBenefit = std::pow(10.0f, (float)loopInfo->getLoopDepth(mbb)) / 5.0;
803
804       coalescesFound[RegPair(srcReg, dstReg)] = cBenefit;
805       coalescesFound[RegPair(dstReg, srcReg)] = cBenefit;
806     }
807
808   }
809
810   return coalescesFound;
811 }
812
813 void RegAllocPBQP::findVRegIntervalsToAlloc() {
814
815   // Iterate over all live ranges.
816   for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
817        itr != end; ++itr) {
818
819     // Ignore physical ones.
820     if (TargetRegisterInfo::isPhysicalRegister(itr->first))
821       continue;
822
823     LiveInterval *li = itr->second;
824
825     // If this live interval is non-empty we will use pbqp to allocate it.
826     // Empty intervals we allocate in a simple post-processing stage in
827     // finalizeAlloc.
828     if (!li->empty()) {
829       vregsToAlloc.insert(li->reg);
830     }
831     else {
832       emptyIntervalVRegs.insert(li->reg);
833     }
834   }
835 }
836
837 PBQP::Graph RegAllocPBQP::constructPBQPProblemOld() {
838
839   typedef std::vector<const LiveInterval*> LIVector;
840   typedef std::vector<unsigned> RegVector;
841
842   // This will store the physical intervals for easy reference.
843   LIVector physIntervals;
844
845   // Start by clearing the old node <-> live interval mappings & allowed sets
846   li2Node.clear();
847   node2LI.clear();
848   allowedSets.clear();
849
850   // Populate physIntervals, update preg use:
851   for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
852        itr != end; ++itr) {
853
854     if (TargetRegisterInfo::isPhysicalRegister(itr->first)) {
855       physIntervals.push_back(itr->second);
856       mri->setPhysRegUsed(itr->second->reg);
857     }
858   }
859
860   // Iterate over vreg intervals, construct live interval <-> node number
861   //  mappings.
862   for (RegSet::const_iterator itr = vregsToAlloc.begin(),
863                               end = vregsToAlloc.end();
864        itr != end; ++itr) {
865     const LiveInterval *li = &lis->getInterval(*itr);
866
867     li2Node[li] = node2LI.size();
868     node2LI.push_back(li);
869   }
870
871   // Get the set of potential coalesces.
872   CoalesceMap coalesces;
873
874   if (pbqpCoalescing) {
875     coalesces = findCoalesces();
876   }
877
878   // Construct a PBQP solver for this problem
879   PBQP::Graph problem;
880   problemNodes.resize(vregsToAlloc.size());
881
882   // Resize allowedSets container appropriately.
883   allowedSets.resize(vregsToAlloc.size());
884
885   BitVector ReservedRegs = tri->getReservedRegs(*mf);
886
887   // Iterate over virtual register intervals to compute allowed sets...
888   for (unsigned node = 0; node < node2LI.size(); ++node) {
889
890     // Grab pointers to the interval and its register class.
891     const LiveInterval *li = node2LI[node];
892     const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
893
894     // Start by assuming all allocable registers in the class are allowed...
895     RegVector liAllowed;
896     TargetRegisterClass::iterator aob = liRC->allocation_order_begin(*mf);
897     TargetRegisterClass::iterator aoe = liRC->allocation_order_end(*mf);
898     for (TargetRegisterClass::iterator it = aob; it != aoe; ++it)
899       if (!ReservedRegs.test(*it))
900         liAllowed.push_back(*it);
901
902     // Eliminate the physical registers which overlap with this range, along
903     // with all their aliases.
904     for (LIVector::iterator pItr = physIntervals.begin(),
905        pEnd = physIntervals.end(); pItr != pEnd; ++pItr) {
906
907       if (!li->overlaps(**pItr))
908         continue;
909
910       unsigned pReg = (*pItr)->reg;
911
912       // If we get here then the live intervals overlap, but we're still ok
913       // if they're coalescable.
914       if (coalesces.find(RegPair(li->reg, pReg)) != coalesces.end()) {
915         DEBUG(dbgs() << "CoalescingOverride: (" << li->reg << ", " << pReg << ")\n");
916         continue;
917       }
918
919       // If we get here then we have a genuine exclusion.
920
921       // Remove the overlapping reg...
922       RegVector::iterator eraseItr =
923         std::find(liAllowed.begin(), liAllowed.end(), pReg);
924
925       if (eraseItr != liAllowed.end())
926         liAllowed.erase(eraseItr);
927
928       const unsigned *aliasItr = tri->getAliasSet(pReg);
929
930       if (aliasItr != 0) {
931         // ...and its aliases.
932         for (; *aliasItr != 0; ++aliasItr) {
933           RegVector::iterator eraseItr =
934             std::find(liAllowed.begin(), liAllowed.end(), *aliasItr);
935
936           if (eraseItr != liAllowed.end()) {
937             liAllowed.erase(eraseItr);
938           }
939         }
940       }
941     }
942
943     // Copy the allowed set into a member vector for use when constructing cost
944     // vectors & matrices, and mapping PBQP solutions back to assignments.
945     allowedSets[node] = AllowedSet(liAllowed.begin(), liAllowed.end());
946
947     // Set the spill cost to the interval weight, or epsilon if the
948     // interval weight is zero
949     PBQP::PBQPNum spillCost = (li->weight != 0.0) ?
950         li->weight : std::numeric_limits<PBQP::PBQPNum>::min();
951
952     // Build a cost vector for this interval.
953     problemNodes[node] =
954       problem.addNode(
955         buildCostVector(li->reg, allowedSets[node], coalesces, spillCost));
956
957   }
958
959
960   // Now add the cost matrices...
961   for (unsigned node1 = 0; node1 < node2LI.size(); ++node1) {
962     const LiveInterval *li = node2LI[node1];
963
964     // Test for live range overlaps and insert interference matrices.
965     for (unsigned node2 = node1 + 1; node2 < node2LI.size(); ++node2) {
966       const LiveInterval *li2 = node2LI[node2];
967
968       CoalesceMap::const_iterator cmItr =
969         coalesces.find(RegPair(li->reg, li2->reg));
970
971       PBQP::Matrix *m = 0;
972
973       if (cmItr != coalesces.end()) {
974         m = buildCoalescingMatrix(allowedSets[node1], allowedSets[node2],
975                                   cmItr->second);
976       }
977       else if (li->overlaps(*li2)) {
978         m = buildInterferenceMatrix(allowedSets[node1], allowedSets[node2]);
979       }
980
981       if (m != 0) {
982         problem.addEdge(problemNodes[node1],
983                         problemNodes[node2],
984                         *m);
985
986         delete m;
987       }
988     }
989   }
990
991   assert(problem.getNumNodes() == allowedSets.size());
992 /*
993   std::cerr << "Allocating for " << problem.getNumNodes() << " nodes, "
994             << problem.getNumEdges() << " edges.\n";
995
996   problem.printDot(std::cerr);
997 */
998   // We're done, PBQP problem constructed - return it.
999   return problem;
1000 }
1001
1002 void RegAllocPBQP::addStackInterval(const LiveInterval *spilled,
1003                                     MachineRegisterInfo* mri) {
1004   int stackSlot = vrm->getStackSlot(spilled->reg);
1005
1006   if (stackSlot == VirtRegMap::NO_STACK_SLOT)
1007     return;
1008
1009   const TargetRegisterClass *RC = mri->getRegClass(spilled->reg);
1010   LiveInterval &stackInterval = lss->getOrCreateInterval(stackSlot, RC);
1011
1012   VNInfo *vni;
1013   if (stackInterval.getNumValNums() != 0)
1014     vni = stackInterval.getValNumInfo(0);
1015   else
1016     vni = stackInterval.getNextValue(
1017       SlotIndex(), 0, false, lss->getVNInfoAllocator());
1018
1019   LiveInterval &rhsInterval = lis->getInterval(spilled->reg);
1020   stackInterval.MergeRangesInAsValue(rhsInterval, vni);
1021 }
1022
1023 bool RegAllocPBQP::mapPBQPToRegAllocOld(const PBQP::Solution &solution) {
1024
1025   // Set to true if we have any spills
1026   bool anotherRoundNeeded = false;
1027
1028   // Clear the existing allocation.
1029   vrm->clearAllVirt();
1030
1031   // Iterate over the nodes mapping the PBQP solution to a register assignment.
1032   for (unsigned node = 0; node < node2LI.size(); ++node) {
1033     unsigned virtReg = node2LI[node]->reg,
1034              allocSelection = solution.getSelection(problemNodes[node]);
1035
1036
1037     // If the PBQP solution is non-zero it's a physical register...
1038     if (allocSelection != 0) {
1039       // Get the physical reg, subtracting 1 to account for the spill option.
1040       unsigned physReg = allowedSets[node][allocSelection - 1];
1041
1042       DEBUG(dbgs() << "VREG " << virtReg << " -> "
1043             << tri->getName(physReg) << " (Option: " << allocSelection << ")\n");
1044
1045       assert(physReg != 0);
1046
1047       // Add to the virt reg map and update the used phys regs.
1048       vrm->assignVirt2Phys(virtReg, physReg);
1049     }
1050     // ...Otherwise it's a spill.
1051     else {
1052
1053       // Make sure we ignore this virtual reg on the next round
1054       // of allocation
1055       vregsToAlloc.erase(virtReg);
1056
1057       // Insert spill ranges for this live range
1058       const LiveInterval *spillInterval = node2LI[node];
1059       double oldSpillWeight = spillInterval->weight;
1060       SmallVector<LiveInterval*, 8> spillIs;
1061       rmf->rememberUseDefs(spillInterval);
1062       std::vector<LiveInterval*> newSpills =
1063         lis->addIntervalsForSpills(*spillInterval, spillIs, loopInfo, *vrm);
1064       addStackInterval(spillInterval, mri);
1065       rmf->rememberSpills(spillInterval, newSpills);
1066
1067       (void) oldSpillWeight;
1068       DEBUG(dbgs() << "VREG " << virtReg << " -> SPILLED (Option: 0, Cost: "
1069                    << oldSpillWeight << ", New vregs: ");
1070
1071       // Copy any newly inserted live intervals into the list of regs to
1072       // allocate.
1073       for (std::vector<LiveInterval*>::const_iterator
1074            itr = newSpills.begin(), end = newSpills.end();
1075            itr != end; ++itr) {
1076
1077         assert(!(*itr)->empty() && "Empty spill range.");
1078
1079         DEBUG(dbgs() << (*itr)->reg << " ");
1080
1081         vregsToAlloc.insert((*itr)->reg);
1082       }
1083
1084       DEBUG(dbgs() << ")\n");
1085
1086       // We need another round if spill intervals were added.
1087       anotherRoundNeeded |= !newSpills.empty();
1088     }
1089   }
1090
1091   return !anotherRoundNeeded;
1092 }
1093
1094 bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
1095                                      const PBQP::Solution &solution) {
1096   // Set to true if we have any spills
1097   bool anotherRoundNeeded = false;
1098
1099   // Clear the existing allocation.
1100   vrm->clearAllVirt();
1101
1102   const PBQP::Graph &g = problem.getGraph();
1103   // Iterate over the nodes mapping the PBQP solution to a register
1104   // assignment.
1105   for (PBQP::Graph::ConstNodeItr node = g.nodesBegin(),
1106                                  nodeEnd = g.nodesEnd();
1107        node != nodeEnd; ++node) {
1108     unsigned vreg = problem.getVRegForNode(node);
1109     unsigned alloc = solution.getSelection(node);
1110
1111     if (problem.isPRegOption(vreg, alloc)) {
1112       unsigned preg = problem.getPRegForOption(vreg, alloc);    
1113       DEBUG(dbgs() << "VREG " << vreg << " -> " << tri->getName(preg) << "\n");
1114       assert(preg != 0 && "Invalid preg selected.");
1115       vrm->assignVirt2Phys(vreg, preg);      
1116     } else if (problem.isSpillOption(vreg, alloc)) {
1117       vregsToAlloc.erase(vreg);
1118       const LiveInterval* spillInterval = &lis->getInterval(vreg);
1119       double oldWeight = spillInterval->weight;
1120       SmallVector<LiveInterval*, 8> spillIs;
1121       rmf->rememberUseDefs(spillInterval);
1122       std::vector<LiveInterval*> newSpills =
1123         lis->addIntervalsForSpills(*spillInterval, spillIs, loopInfo, *vrm);
1124       addStackInterval(spillInterval, mri);
1125       rmf->rememberSpills(spillInterval, newSpills);
1126
1127       (void) oldWeight;
1128       DEBUG(dbgs() << "VREG " << vreg << " -> SPILLED (Cost: "
1129                    << oldWeight << ", New vregs: ");
1130
1131       // Copy any newly inserted live intervals into the list of regs to
1132       // allocate.
1133       for (std::vector<LiveInterval*>::const_iterator
1134            itr = newSpills.begin(), end = newSpills.end();
1135            itr != end; ++itr) {
1136         assert(!(*itr)->empty() && "Empty spill range.");
1137         DEBUG(dbgs() << (*itr)->reg << " ");
1138         vregsToAlloc.insert((*itr)->reg);
1139       }
1140
1141       DEBUG(dbgs() << ")\n");
1142
1143       // We need another round if spill intervals were added.
1144       anotherRoundNeeded |= !newSpills.empty();
1145     } else {
1146       assert(false && "Unknown allocation option.");
1147     }
1148   }
1149
1150   return !anotherRoundNeeded;
1151 }
1152
1153
1154 void RegAllocPBQP::finalizeAlloc() const {
1155   typedef LiveIntervals::iterator LIIterator;
1156   typedef LiveInterval::Ranges::const_iterator LRIterator;
1157
1158   // First allocate registers for the empty intervals.
1159   for (RegSet::const_iterator
1160          itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
1161          itr != end; ++itr) {
1162     LiveInterval *li = &lis->getInterval(*itr);
1163
1164     unsigned physReg = vrm->getRegAllocPref(li->reg);
1165
1166     if (physReg == 0) {
1167       const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
1168       physReg = *liRC->allocation_order_begin(*mf);
1169     }
1170
1171     vrm->assignVirt2Phys(li->reg, physReg);
1172   }
1173
1174   // Finally iterate over the basic blocks to compute and set the live-in sets.
1175   SmallVector<MachineBasicBlock*, 8> liveInMBBs;
1176   MachineBasicBlock *entryMBB = &*mf->begin();
1177
1178   for (LIIterator liItr = lis->begin(), liEnd = lis->end();
1179        liItr != liEnd; ++liItr) {
1180
1181     const LiveInterval *li = liItr->second;
1182     unsigned reg = 0;
1183
1184     // Get the physical register for this interval
1185     if (TargetRegisterInfo::isPhysicalRegister(li->reg)) {
1186       reg = li->reg;
1187     }
1188     else if (vrm->isAssignedReg(li->reg)) {
1189       reg = vrm->getPhys(li->reg);
1190     }
1191     else {
1192       // Ranges which are assigned a stack slot only are ignored.
1193       continue;
1194     }
1195
1196     if (reg == 0) {
1197       // Filter out zero regs - they're for intervals that were spilled.
1198       continue;
1199     }
1200
1201     // Iterate over the ranges of the current interval...
1202     for (LRIterator lrItr = li->begin(), lrEnd = li->end();
1203          lrItr != lrEnd; ++lrItr) {
1204
1205       // Find the set of basic blocks which this range is live into...
1206       if (lis->findLiveInMBBs(lrItr->start, lrItr->end,  liveInMBBs)) {
1207         // And add the physreg for this interval to their live-in sets.
1208         for (unsigned i = 0; i < liveInMBBs.size(); ++i) {
1209           if (liveInMBBs[i] != entryMBB) {
1210             if (!liveInMBBs[i]->isLiveIn(reg)) {
1211               liveInMBBs[i]->addLiveIn(reg);
1212             }
1213           }
1214         }
1215         liveInMBBs.clear();
1216       }
1217     }
1218   }
1219
1220 }
1221
1222 bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
1223
1224   mf = &MF;
1225   tm = &mf->getTarget();
1226   tri = tm->getRegisterInfo();
1227   tii = tm->getInstrInfo();
1228   mri = &mf->getRegInfo(); 
1229
1230   lis = &getAnalysis<LiveIntervals>();
1231   lss = &getAnalysis<LiveStacks>();
1232   loopInfo = &getAnalysis<MachineLoopInfo>();
1233   rmf = &getAnalysis<RenderMachineFunction>();
1234
1235   vrm = &getAnalysis<VirtRegMap>();
1236
1237
1238   DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getFunction()->getName() << "\n");
1239
1240   // Allocator main loop:
1241   //
1242   // * Map current regalloc problem to a PBQP problem
1243   // * Solve the PBQP problem
1244   // * Map the solution back to a register allocation
1245   // * Spill if necessary
1246   //
1247   // This process is continued till no more spills are generated.
1248
1249   // Find the vreg intervals in need of allocation.
1250   findVRegIntervalsToAlloc();
1251
1252   // If there are non-empty intervals allocate them using pbqp.
1253   if (!vregsToAlloc.empty()) {
1254
1255     bool pbqpAllocComplete = false;
1256     unsigned round = 0;
1257
1258     if (!pbqpBuilder) {
1259       while (!pbqpAllocComplete) {
1260         DEBUG(dbgs() << "  PBQP Regalloc round " << round << ":\n");
1261
1262         PBQP::Graph problem = constructPBQPProblemOld();
1263         PBQP::Solution solution =
1264           PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(problem);
1265
1266         pbqpAllocComplete = mapPBQPToRegAllocOld(solution);
1267
1268         ++round;
1269       }
1270     } else {
1271       while (!pbqpAllocComplete) {
1272         DEBUG(dbgs() << "  PBQP Regalloc round " << round << ":\n");
1273
1274         std::auto_ptr<PBQPRAProblem> problem =
1275           builder->build(mf, lis, loopInfo, vregsToAlloc);
1276         PBQP::Solution solution =
1277           PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(
1278             problem->getGraph());
1279
1280         pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
1281
1282         ++round;
1283       }
1284     }
1285   }
1286
1287   // Finalise allocation, allocate empty ranges.
1288   finalizeAlloc();
1289
1290   rmf->renderMachineFunction("After PBQP register allocation.", vrm);
1291
1292   vregsToAlloc.clear();
1293   emptyIntervalVRegs.clear();
1294   li2Node.clear();
1295   node2LI.clear();
1296   allowedSets.clear();
1297   problemNodes.clear();
1298
1299   DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
1300
1301   // Run rewriter
1302   std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
1303
1304   rewriter->runOnMachineFunction(*mf, *vrm, lis);
1305
1306   return true;
1307 }
1308
1309 FunctionPass* llvm::createPBQPRegisterAllocator(
1310                                            std::auto_ptr<PBQPBuilder> builder) {
1311   return new RegAllocPBQP(builder);
1312 }
1313
1314 FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
1315   if (pbqpCoalescing) {
1316     return createPBQPRegisterAllocator(
1317              std::auto_ptr<PBQPBuilder>(new PBQPBuilderWithCoalescing()));
1318   } // else
1319   return createPBQPRegisterAllocator(
1320            std::auto_ptr<PBQPBuilder>(new PBQPBuilder()));
1321 }
1322
1323 #undef DEBUG_TYPE