Remove spurious typedefs.
[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 "Spiller.h"
35 #include "VirtRegMap.h"
36 #include "RegisterCoalescer.h"
37 #include "llvm/Module.h"
38 #include "llvm/Analysis/AliasAnalysis.h"
39 #include "llvm/CodeGen/CalcSpillWeights.h"
40 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
41 #include "llvm/CodeGen/LiveRangeEdit.h"
42 #include "llvm/CodeGen/LiveStackAnalysis.h"
43 #include "llvm/CodeGen/RegAllocPBQP.h"
44 #include "llvm/CodeGen/MachineDominators.h"
45 #include "llvm/CodeGen/MachineFunctionPass.h"
46 #include "llvm/CodeGen/MachineLoopInfo.h"
47 #include "llvm/CodeGen/MachineRegisterInfo.h"
48 #include "llvm/CodeGen/PBQP/HeuristicSolver.h"
49 #include "llvm/CodeGen/PBQP/Graph.h"
50 #include "llvm/CodeGen/PBQP/Heuristics/Briggs.h"
51 #include "llvm/CodeGen/RegAllocRegistry.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetInstrInfo.h"
55 #include "llvm/Target/TargetMachine.h"
56 #include <limits>
57 #include <memory>
58 #include <set>
59 #include <sstream>
60 #include <vector>
61
62 using namespace llvm;
63
64 static RegisterRegAlloc
65 registerPBQPRepAlloc("pbqp", "PBQP register allocator",
66                        createDefaultPBQPRegisterAllocator);
67
68 static cl::opt<bool>
69 pbqpCoalescing("pbqp-coalescing",
70                 cl::desc("Attempt coalescing during PBQP register allocation."),
71                 cl::init(false), cl::Hidden);
72
73 #ifndef NDEBUG
74 static cl::opt<bool>
75 pbqpDumpGraphs("pbqp-dump-graphs",
76                cl::desc("Dump graphs for each function/round in the compilation unit."),
77                cl::init(false), cl::Hidden);
78 #endif
79
80 namespace {
81
82 ///
83 /// PBQP based allocators solve the register allocation problem by mapping
84 /// register allocation problems to Partitioned Boolean Quadratic
85 /// Programming problems.
86 class RegAllocPBQP : public MachineFunctionPass {
87 public:
88
89   static char ID;
90
91   /// Construct a PBQP register allocator.
92   RegAllocPBQP(std::auto_ptr<PBQPBuilder> b, char *cPassID=0)
93       : MachineFunctionPass(ID), builder(b), customPassID(cPassID) {
94     initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
95     initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
96     initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
97     initializeLiveStacksPass(*PassRegistry::getPassRegistry());
98     initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
99     initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
100   }
101
102   /// Return the pass name.
103   virtual const char* getPassName() const {
104     return "PBQP Register Allocator";
105   }
106
107   /// PBQP analysis usage.
108   virtual void getAnalysisUsage(AnalysisUsage &au) const;
109
110   /// Perform register allocation
111   virtual bool runOnMachineFunction(MachineFunction &MF);
112
113 private:
114
115   typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
116   typedef std::vector<const LiveInterval*> Node2LIMap;
117   typedef std::vector<unsigned> AllowedSet;
118   typedef std::vector<AllowedSet> AllowedSetMap;
119   typedef std::pair<unsigned, unsigned> RegPair;
120   typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
121   typedef std::vector<PBQP::Graph::NodeItr> NodeVector;
122   typedef std::set<unsigned> RegSet;
123
124
125   std::auto_ptr<PBQPBuilder> builder;
126
127   char *customPassID;
128
129   MachineFunction *mf;
130   const TargetMachine *tm;
131   const TargetRegisterInfo *tri;
132   const TargetInstrInfo *tii;
133   const MachineLoopInfo *loopInfo;
134   MachineRegisterInfo *mri;
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   LiveIntervals *LIS = const_cast<LiveIntervals*>(lis);
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 (unsigned Reg = 1, e = tri->getNumRegs(); Reg != e; ++Reg) {
206     if (mri->def_empty(Reg))
207       continue;
208     pregs.insert(Reg);
209     mri->setPhysRegUsed(Reg);
210   }
211
212   BitVector reservedRegs = tri->getReservedRegs(*mf);
213
214   // Iterate over vregs.
215   for (RegSet::const_iterator vregItr = vregs.begin(), vregEnd = vregs.end();
216        vregItr != vregEnd; ++vregItr) {
217     unsigned vreg = *vregItr;
218     const TargetRegisterClass *trc = mri->getRegClass(vreg);
219     LiveInterval *vregLI = &LIS->getInterval(vreg);
220
221     // Record any overlaps with regmask operands.
222     BitVector regMaskOverlaps(tri->getNumRegs());
223     LIS->checkRegMaskInterference(*vregLI, regMaskOverlaps);
224
225     // Compute an initial allowed set for the current vreg.
226     typedef std::vector<unsigned> VRAllowed;
227     VRAllowed vrAllowed;
228     ArrayRef<uint16_t> rawOrder = trc->getRawAllocationOrder(*mf);
229     for (unsigned i = 0; i != rawOrder.size(); ++i) {
230       unsigned preg = rawOrder[i];
231       if (reservedRegs.test(preg))
232         continue;
233
234       // vregLI crosses a regmask operand that clobbers preg.
235       if (!regMaskOverlaps.empty() && !regMaskOverlaps.test(preg))
236         continue;
237
238       // vregLI overlaps fixed regunit interference.
239       if (LIS->trackingRegUnits()) {
240         bool Interference = false;
241         for (MCRegUnitIterator Units(preg, tri); Units.isValid(); ++Units) {
242           if (vregLI->overlaps(LIS->getRegUnit(*Units))) {
243             Interference = true;
244             break;
245           }
246         }
247         if (Interference)
248           continue;
249       }
250
251       // preg is usable for this virtual register.
252       vrAllowed.push_back(preg);
253     }
254
255     RegSet overlappingPRegs;
256
257     // Record physical registers whose ranges overlap.
258     for (RegSet::const_iterator pregItr = pregs.begin(),
259                                 pregEnd = pregs.end();
260          pregItr != pregEnd; ++pregItr) {
261       unsigned preg = *pregItr;
262       if (!LIS->hasInterval(preg))
263         continue;
264       const LiveInterval *pregLI = &LIS->getInterval(preg);
265
266       if (pregLI->empty()) {
267         continue;
268       }
269
270       if (vregLI->overlaps(*pregLI))
271         overlappingPRegs.insert(preg);      
272     }
273
274     for (RegSet::const_iterator pregItr = overlappingPRegs.begin(),
275                                 pregEnd = overlappingPRegs.end();
276          pregItr != pregEnd; ++pregItr) {
277       unsigned preg = *pregItr;
278
279       // Remove the register from the allowed set.
280       VRAllowed::iterator eraseItr =
281         std::find(vrAllowed.begin(), vrAllowed.end(), preg);
282
283       if (eraseItr != vrAllowed.end()) {
284         vrAllowed.erase(eraseItr);
285       }
286
287       // Also remove any aliases.
288       for (MCRegAliasIterator AI(preg, tri, false); AI.isValid(); ++AI) {
289         VRAllowed::iterator eraseItr =
290           std::find(vrAllowed.begin(), vrAllowed.end(), *AI);
291         if (eraseItr != vrAllowed.end()) {
292           vrAllowed.erase(eraseItr);
293         }
294       }
295     }
296
297     // Construct the node.
298     PBQP::Graph::NodeItr node =
299       g.addNode(PBQP::Vector(vrAllowed.size() + 1, 0));
300
301     // Record the mapping and allowed set in the problem.
302     p->recordVReg(vreg, node, vrAllowed.begin(), vrAllowed.end());
303
304     PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
305         vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
306
307     addSpillCosts(g.getNodeCosts(node), spillCost);
308   }
309
310   for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
311          vr1Itr != vrEnd; ++vr1Itr) {
312     unsigned vr1 = *vr1Itr;
313     const LiveInterval &l1 = lis->getInterval(vr1);
314     const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
315
316     for (RegSet::const_iterator vr2Itr = llvm::next(vr1Itr);
317          vr2Itr != vrEnd; ++vr2Itr) {
318       unsigned vr2 = *vr2Itr;
319       const LiveInterval &l2 = lis->getInterval(vr2);
320       const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
321
322       assert(!l2.empty() && "Empty interval in vreg set?");
323       if (l1.overlaps(l2)) {
324         PBQP::Graph::EdgeItr edge =
325           g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
326                     PBQP::Matrix(vr1Allowed.size()+1, vr2Allowed.size()+1, 0));
327
328         addInterferenceCosts(g.getEdgeCosts(edge), vr1Allowed, vr2Allowed, tri);
329       }
330     }
331   }
332
333   return p;
334 }
335
336 void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
337                                 PBQP::PBQPNum spillCost) {
338   costVec[0] = spillCost;
339 }
340
341 void PBQPBuilder::addInterferenceCosts(
342                                     PBQP::Matrix &costMat,
343                                     const PBQPRAProblem::AllowedSet &vr1Allowed,
344                                     const PBQPRAProblem::AllowedSet &vr2Allowed,
345                                     const TargetRegisterInfo *tri) {
346   assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
347   assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
348
349   for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
350     unsigned preg1 = vr1Allowed[i];
351
352     for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
353       unsigned preg2 = vr2Allowed[j];
354
355       if (tri->regsOverlap(preg1, preg2)) {
356         costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
357       }
358     }
359   }
360 }
361
362 std::auto_ptr<PBQPRAProblem> PBQPBuilderWithCoalescing::build(
363                                                 MachineFunction *mf,
364                                                 const LiveIntervals *lis,
365                                                 const MachineLoopInfo *loopInfo,
366                                                 const RegSet &vregs) {
367
368   std::auto_ptr<PBQPRAProblem> p = PBQPBuilder::build(mf, lis, loopInfo, vregs);
369   PBQP::Graph &g = p->getGraph();
370
371   const TargetMachine &tm = mf->getTarget();
372   CoalescerPair cp(*tm.getRegisterInfo());
373
374   // Scan the machine function and add a coalescing cost whenever CoalescerPair
375   // gives the Ok.
376   for (MachineFunction::const_iterator mbbItr = mf->begin(),
377                                        mbbEnd = mf->end();
378        mbbItr != mbbEnd; ++mbbItr) {
379     const MachineBasicBlock *mbb = &*mbbItr;
380
381     for (MachineBasicBlock::const_iterator miItr = mbb->begin(),
382                                            miEnd = mbb->end();
383          miItr != miEnd; ++miItr) {
384       const MachineInstr *mi = &*miItr;
385
386       if (!cp.setRegisters(mi)) {
387         continue; // Not coalescable.
388       }
389
390       if (cp.getSrcReg() == cp.getDstReg()) {
391         continue; // Already coalesced.
392       }
393
394       unsigned dst = cp.getDstReg(),
395                src = cp.getSrcReg();
396
397       const float copyFactor = 0.5; // Cost of copy relative to load. Current
398       // value plucked randomly out of the air.
399
400       PBQP::PBQPNum cBenefit =
401         copyFactor * LiveIntervals::getSpillWeight(false, true,
402                                                    loopInfo->getLoopDepth(mbb));
403
404       if (cp.isPhys()) {
405         if (!lis->isAllocatable(dst)) {
406           continue;
407         }
408
409         const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
410         unsigned pregOpt = 0;
411         while (pregOpt < allowed.size() && allowed[pregOpt] != dst) {
412           ++pregOpt;
413         }
414         if (pregOpt < allowed.size()) {
415           ++pregOpt; // +1 to account for spill option.
416           PBQP::Graph::NodeItr node = p->getNodeForVReg(src);
417           addPhysRegCoalesce(g.getNodeCosts(node), pregOpt, cBenefit);
418         }
419       } else {
420         const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
421         const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
422         PBQP::Graph::NodeItr node1 = p->getNodeForVReg(dst);
423         PBQP::Graph::NodeItr node2 = p->getNodeForVReg(src);
424         PBQP::Graph::EdgeItr edge = g.findEdge(node1, node2);
425         if (edge == g.edgesEnd()) {
426           edge = g.addEdge(node1, node2, PBQP::Matrix(allowed1->size() + 1,
427                                                       allowed2->size() + 1,
428                                                       0));
429         } else {
430           if (g.getEdgeNode1(edge) == node2) {
431             std::swap(node1, node2);
432             std::swap(allowed1, allowed2);
433           }
434         }
435
436         addVirtRegCoalesce(g.getEdgeCosts(edge), *allowed1, *allowed2,
437                            cBenefit);
438       }
439     }
440   }
441
442   return p;
443 }
444
445 void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
446                                                    unsigned pregOption,
447                                                    PBQP::PBQPNum benefit) {
448   costVec[pregOption] += -benefit;
449 }
450
451 void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
452                                     PBQP::Matrix &costMat,
453                                     const PBQPRAProblem::AllowedSet &vr1Allowed,
454                                     const PBQPRAProblem::AllowedSet &vr2Allowed,
455                                     PBQP::PBQPNum benefit) {
456
457   assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
458   assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
459
460   for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
461     unsigned preg1 = vr1Allowed[i];
462     for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
463       unsigned preg2 = vr2Allowed[j];
464
465       if (preg1 == preg2) {
466         costMat[i + 1][j + 1] += -benefit;
467       }
468     }
469   }
470 }
471
472
473 void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
474   au.setPreservesCFG();
475   au.addRequired<AliasAnalysis>();
476   au.addPreserved<AliasAnalysis>();
477   au.addRequired<SlotIndexes>();
478   au.addPreserved<SlotIndexes>();
479   au.addRequired<LiveIntervals>();
480   //au.addRequiredID(SplitCriticalEdgesID);
481   if (customPassID)
482     au.addRequiredID(*customPassID);
483   au.addRequired<CalculateSpillWeights>();
484   au.addRequired<LiveStacks>();
485   au.addPreserved<LiveStacks>();
486   au.addRequired<MachineDominatorTree>();
487   au.addPreserved<MachineDominatorTree>();
488   au.addRequired<MachineLoopInfo>();
489   au.addPreserved<MachineLoopInfo>();
490   au.addRequired<VirtRegMap>();
491   MachineFunctionPass::getAnalysisUsage(au);
492 }
493
494 void RegAllocPBQP::findVRegIntervalsToAlloc() {
495
496   // Iterate over all live ranges.
497   for (unsigned i = 0, e = mri->getNumVirtRegs(); i != e; ++i) {
498     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
499     if (mri->reg_nodbg_empty(Reg))
500       continue;
501     LiveInterval *li = &lis->getInterval(Reg);
502
503     // If this live interval is non-empty we will use pbqp to allocate it.
504     // Empty intervals we allocate in a simple post-processing stage in
505     // finalizeAlloc.
506     if (!li->empty()) {
507       vregsToAlloc.insert(li->reg);
508     } else {
509       emptyIntervalVRegs.insert(li->reg);
510     }
511   }
512 }
513
514 bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
515                                      const PBQP::Solution &solution) {
516   // Set to true if we have any spills
517   bool anotherRoundNeeded = false;
518
519   // Clear the existing allocation.
520   vrm->clearAllVirt();
521
522   const PBQP::Graph &g = problem.getGraph();
523   // Iterate over the nodes mapping the PBQP solution to a register
524   // assignment.
525   for (PBQP::Graph::ConstNodeItr node = g.nodesBegin(),
526                                  nodeEnd = g.nodesEnd();
527        node != nodeEnd; ++node) {
528     unsigned vreg = problem.getVRegForNode(node);
529     unsigned alloc = solution.getSelection(node);
530
531     if (problem.isPRegOption(vreg, alloc)) {
532       unsigned preg = problem.getPRegForOption(vreg, alloc);
533       DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> "
534             << tri->getName(preg) << "\n");
535       assert(preg != 0 && "Invalid preg selected.");
536       vrm->assignVirt2Phys(vreg, preg);
537     } else if (problem.isSpillOption(vreg, alloc)) {
538       vregsToAlloc.erase(vreg);
539       SmallVector<LiveInterval*, 8> newSpills;
540       LiveRangeEdit LRE(&lis->getInterval(vreg), newSpills, *mf, *lis, vrm);
541       spiller->spill(LRE);
542
543       DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> SPILLED (Cost: "
544                    << LRE.getParent().weight << ", New vregs: ");
545
546       // Copy any newly inserted live intervals into the list of regs to
547       // allocate.
548       for (LiveRangeEdit::iterator itr = LRE.begin(), end = LRE.end();
549            itr != end; ++itr) {
550         assert(!(*itr)->empty() && "Empty spill range.");
551         DEBUG(dbgs() << PrintReg((*itr)->reg, tri) << " ");
552         vregsToAlloc.insert((*itr)->reg);
553       }
554
555       DEBUG(dbgs() << ")\n");
556
557       // We need another round if spill intervals were added.
558       anotherRoundNeeded |= !LRE.empty();
559     } else {
560       llvm_unreachable("Unknown allocation option.");
561     }
562   }
563
564   return !anotherRoundNeeded;
565 }
566
567
568 void RegAllocPBQP::finalizeAlloc() const {
569   // First allocate registers for the empty intervals.
570   for (RegSet::const_iterator
571          itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
572          itr != end; ++itr) {
573     LiveInterval *li = &lis->getInterval(*itr);
574
575     unsigned physReg = vrm->getRegAllocPref(li->reg);
576
577     if (physReg == 0) {
578       const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
579       physReg = liRC->getRawAllocationOrder(*mf).front();
580     }
581
582     vrm->assignVirt2Phys(li->reg, physReg);
583   }
584 }
585
586 bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
587
588   mf = &MF;
589   tm = &mf->getTarget();
590   tri = tm->getRegisterInfo();
591   tii = tm->getInstrInfo();
592   mri = &mf->getRegInfo();
593
594   lis = &getAnalysis<LiveIntervals>();
595   lss = &getAnalysis<LiveStacks>();
596   loopInfo = &getAnalysis<MachineLoopInfo>();
597
598   vrm = &getAnalysis<VirtRegMap>();
599   spiller.reset(createInlineSpiller(*this, MF, *vrm));
600
601   mri->freezeReservedRegs(MF);
602
603   DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getFunction()->getName() << "\n");
604
605   // Allocator main loop:
606   //
607   // * Map current regalloc problem to a PBQP problem
608   // * Solve the PBQP problem
609   // * Map the solution back to a register allocation
610   // * Spill if necessary
611   //
612   // This process is continued till no more spills are generated.
613
614   // Find the vreg intervals in need of allocation.
615   findVRegIntervalsToAlloc();
616
617   const Function* func = mf->getFunction();
618   std::string fqn =
619     func->getParent()->getModuleIdentifier() + "." +
620     func->getName().str();
621   (void)fqn;
622
623   // If there are non-empty intervals allocate them using pbqp.
624   if (!vregsToAlloc.empty()) {
625
626     bool pbqpAllocComplete = false;
627     unsigned round = 0;
628
629     while (!pbqpAllocComplete) {
630       DEBUG(dbgs() << "  PBQP Regalloc round " << round << ":\n");
631
632       std::auto_ptr<PBQPRAProblem> problem =
633         builder->build(mf, lis, loopInfo, vregsToAlloc);
634
635 #ifndef NDEBUG
636       if (pbqpDumpGraphs) {
637         std::ostringstream rs;
638         rs << round;
639         std::string graphFileName(fqn + "." + rs.str() + ".pbqpgraph");
640         std::string tmp;
641         raw_fd_ostream os(graphFileName.c_str(), tmp);
642         DEBUG(dbgs() << "Dumping graph for round " << round << " to \""
643               << graphFileName << "\"\n");
644         problem->getGraph().dump(os);
645       }
646 #endif
647
648       PBQP::Solution solution =
649         PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(
650           problem->getGraph());
651
652       pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
653
654       ++round;
655     }
656   }
657
658   // Finalise allocation, allocate empty ranges.
659   finalizeAlloc();
660   vregsToAlloc.clear();
661   emptyIntervalVRegs.clear();
662
663   DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
664
665   return true;
666 }
667
668 FunctionPass* llvm::createPBQPRegisterAllocator(
669                                            std::auto_ptr<PBQPBuilder> builder,
670                                            char *customPassID) {
671   return new RegAllocPBQP(builder, customPassID);
672 }
673
674 FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
675   if (pbqpCoalescing) {
676     return createPBQPRegisterAllocator(
677              std::auto_ptr<PBQPBuilder>(new PBQPBuilderWithCoalescing()));
678   } // else
679   return createPBQPRegisterAllocator(
680            std::auto_ptr<PBQPBuilder>(new PBQPBuilder()));
681 }
682
683 #undef DEBUG_TYPE