Home | History | Annotate | Download | only in CodeGen
      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 "llvm/CodeGen/RegAllocPBQP.h"
     35 #include "RegisterCoalescer.h"
     36 #include "Spiller.h"
     37 #include "llvm/Analysis/AliasAnalysis.h"
     38 #include "llvm/CodeGen/CalcSpillWeights.h"
     39 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
     40 #include "llvm/CodeGen/LiveRangeEdit.h"
     41 #include "llvm/CodeGen/LiveStackAnalysis.h"
     42 #include "llvm/CodeGen/MachineDominators.h"
     43 #include "llvm/CodeGen/MachineFunctionPass.h"
     44 #include "llvm/CodeGen/MachineLoopInfo.h"
     45 #include "llvm/CodeGen/MachineRegisterInfo.h"
     46 #include "llvm/CodeGen/PBQP/Graph.h"
     47 #include "llvm/CodeGen/PBQP/HeuristicSolver.h"
     48 #include "llvm/CodeGen/PBQP/Heuristics/Briggs.h"
     49 #include "llvm/CodeGen/RegAllocRegistry.h"
     50 #include "llvm/CodeGen/VirtRegMap.h"
     51 #include "llvm/IR/Module.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::set<unsigned> RegSet;
    122 
    123 
    124   std::auto_ptr<PBQPBuilder> builder;
    125 
    126   char *customPassID;
    127 
    128   MachineFunction *mf;
    129   const TargetMachine *tm;
    130   const TargetRegisterInfo *tri;
    131   const TargetInstrInfo *tii;
    132   const MachineLoopInfo *loopInfo;
    133   MachineRegisterInfo *mri;
    134 
    135   std::auto_ptr<Spiller> spiller;
    136   LiveIntervals *lis;
    137   LiveStacks *lss;
    138   VirtRegMap *vrm;
    139 
    140   RegSet vregsToAlloc, emptyIntervalVRegs;
    141 
    142   /// \brief Finds the initial set of vreg intervals to allocate.
    143   void findVRegIntervalsToAlloc();
    144 
    145   /// \brief Given a solved PBQP problem maps this solution back to a register
    146   /// assignment.
    147   bool mapPBQPToRegAlloc(const PBQPRAProblem &problem,
    148                          const PBQP::Solution &solution);
    149 
    150   /// \brief Postprocessing before final spilling. Sets basic block "live in"
    151   /// variables.
    152   void finalizeAlloc() const;
    153 
    154 };
    155 
    156 char RegAllocPBQP::ID = 0;
    157 
    158 } // End anonymous namespace.
    159 
    160 unsigned PBQPRAProblem::getVRegForNode(PBQP::Graph::ConstNodeItr node) const {
    161   Node2VReg::const_iterator vregItr = node2VReg.find(node);
    162   assert(vregItr != node2VReg.end() && "No vreg for node.");
    163   return vregItr->second;
    164 }
    165 
    166 PBQP::Graph::NodeItr PBQPRAProblem::getNodeForVReg(unsigned vreg) const {
    167   VReg2Node::const_iterator nodeItr = vreg2Node.find(vreg);
    168   assert(nodeItr != vreg2Node.end() && "No node for vreg.");
    169   return nodeItr->second;
    170 
    171 }
    172 
    173 const PBQPRAProblem::AllowedSet&
    174   PBQPRAProblem::getAllowedSet(unsigned vreg) const {
    175   AllowedSetMap::const_iterator allowedSetItr = allowedSets.find(vreg);
    176   assert(allowedSetItr != allowedSets.end() && "No pregs for vreg.");
    177   const AllowedSet &allowedSet = allowedSetItr->second;
    178   return allowedSet;
    179 }
    180 
    181 unsigned PBQPRAProblem::getPRegForOption(unsigned vreg, unsigned option) const {
    182   assert(isPRegOption(vreg, option) && "Not a preg option.");
    183 
    184   const AllowedSet& allowedSet = getAllowedSet(vreg);
    185   assert(option <= allowedSet.size() && "Option outside allowed set.");
    186   return allowedSet[option - 1];
    187 }
    188 
    189 std::auto_ptr<PBQPRAProblem> PBQPBuilder::build(MachineFunction *mf,
    190                                                 const LiveIntervals *lis,
    191                                                 const MachineLoopInfo *loopInfo,
    192                                                 const RegSet &vregs) {
    193 
    194   LiveIntervals *LIS = const_cast<LiveIntervals*>(lis);
    195   MachineRegisterInfo *mri = &mf->getRegInfo();
    196   const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();
    197 
    198   std::auto_ptr<PBQPRAProblem> p(new PBQPRAProblem());
    199   PBQP::Graph &g = p->getGraph();
    200   RegSet pregs;
    201 
    202   // Collect the set of preg intervals, record that they're used in the MF.
    203   for (unsigned Reg = 1, e = tri->getNumRegs(); Reg != e; ++Reg) {
    204     if (mri->def_empty(Reg))
    205       continue;
    206     pregs.insert(Reg);
    207     mri->setPhysRegUsed(Reg);
    208   }
    209 
    210   // Iterate over vregs.
    211   for (RegSet::const_iterator vregItr = vregs.begin(), vregEnd = vregs.end();
    212        vregItr != vregEnd; ++vregItr) {
    213     unsigned vreg = *vregItr;
    214     const TargetRegisterClass *trc = mri->getRegClass(vreg);
    215     LiveInterval *vregLI = &LIS->getInterval(vreg);
    216 
    217     // Record any overlaps with regmask operands.
    218     BitVector regMaskOverlaps;
    219     LIS->checkRegMaskInterference(*vregLI, regMaskOverlaps);
    220 
    221     // Compute an initial allowed set for the current vreg.
    222     typedef std::vector<unsigned> VRAllowed;
    223     VRAllowed vrAllowed;
    224     ArrayRef<uint16_t> rawOrder = trc->getRawAllocationOrder(*mf);
    225     for (unsigned i = 0; i != rawOrder.size(); ++i) {
    226       unsigned preg = rawOrder[i];
    227       if (mri->isReserved(preg))
    228         continue;
    229 
    230       // vregLI crosses a regmask operand that clobbers preg.
    231       if (!regMaskOverlaps.empty() && !regMaskOverlaps.test(preg))
    232         continue;
    233 
    234       // vregLI overlaps fixed regunit interference.
    235       bool Interference = false;
    236       for (MCRegUnitIterator Units(preg, tri); Units.isValid(); ++Units) {
    237         if (vregLI->overlaps(LIS->getRegUnit(*Units))) {
    238           Interference = true;
    239           break;
    240         }
    241       }
    242       if (Interference)
    243         continue;
    244 
    245       // preg is usable for this virtual register.
    246       vrAllowed.push_back(preg);
    247     }
    248 
    249     // Construct the node.
    250     PBQP::Graph::NodeItr node =
    251       g.addNode(PBQP::Vector(vrAllowed.size() + 1, 0));
    252 
    253     // Record the mapping and allowed set in the problem.
    254     p->recordVReg(vreg, node, vrAllowed.begin(), vrAllowed.end());
    255 
    256     PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
    257         vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
    258 
    259     addSpillCosts(g.getNodeCosts(node), spillCost);
    260   }
    261 
    262   for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
    263          vr1Itr != vrEnd; ++vr1Itr) {
    264     unsigned vr1 = *vr1Itr;
    265     const LiveInterval &l1 = lis->getInterval(vr1);
    266     const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
    267 
    268     for (RegSet::const_iterator vr2Itr = llvm::next(vr1Itr);
    269          vr2Itr != vrEnd; ++vr2Itr) {
    270       unsigned vr2 = *vr2Itr;
    271       const LiveInterval &l2 = lis->getInterval(vr2);
    272       const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
    273 
    274       assert(!l2.empty() && "Empty interval in vreg set?");
    275       if (l1.overlaps(l2)) {
    276         PBQP::Graph::EdgeItr edge =
    277           g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
    278                     PBQP::Matrix(vr1Allowed.size()+1, vr2Allowed.size()+1, 0));
    279 
    280         addInterferenceCosts(g.getEdgeCosts(edge), vr1Allowed, vr2Allowed, tri);
    281       }
    282     }
    283   }
    284 
    285   return p;
    286 }
    287 
    288 void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
    289                                 PBQP::PBQPNum spillCost) {
    290   costVec[0] = spillCost;
    291 }
    292 
    293 void PBQPBuilder::addInterferenceCosts(
    294                                     PBQP::Matrix &costMat,
    295                                     const PBQPRAProblem::AllowedSet &vr1Allowed,
    296                                     const PBQPRAProblem::AllowedSet &vr2Allowed,
    297                                     const TargetRegisterInfo *tri) {
    298   assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
    299   assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
    300 
    301   for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
    302     unsigned preg1 = vr1Allowed[i];
    303 
    304     for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
    305       unsigned preg2 = vr2Allowed[j];
    306 
    307       if (tri->regsOverlap(preg1, preg2)) {
    308         costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
    309       }
    310     }
    311   }
    312 }
    313 
    314 std::auto_ptr<PBQPRAProblem> PBQPBuilderWithCoalescing::build(
    315                                                 MachineFunction *mf,
    316                                                 const LiveIntervals *lis,
    317                                                 const MachineLoopInfo *loopInfo,
    318                                                 const RegSet &vregs) {
    319 
    320   std::auto_ptr<PBQPRAProblem> p = PBQPBuilder::build(mf, lis, loopInfo, vregs);
    321   PBQP::Graph &g = p->getGraph();
    322 
    323   const TargetMachine &tm = mf->getTarget();
    324   CoalescerPair cp(*tm.getRegisterInfo());
    325 
    326   // Scan the machine function and add a coalescing cost whenever CoalescerPair
    327   // gives the Ok.
    328   for (MachineFunction::const_iterator mbbItr = mf->begin(),
    329                                        mbbEnd = mf->end();
    330        mbbItr != mbbEnd; ++mbbItr) {
    331     const MachineBasicBlock *mbb = &*mbbItr;
    332 
    333     for (MachineBasicBlock::const_iterator miItr = mbb->begin(),
    334                                            miEnd = mbb->end();
    335          miItr != miEnd; ++miItr) {
    336       const MachineInstr *mi = &*miItr;
    337 
    338       if (!cp.setRegisters(mi)) {
    339         continue; // Not coalescable.
    340       }
    341 
    342       if (cp.getSrcReg() == cp.getDstReg()) {
    343         continue; // Already coalesced.
    344       }
    345 
    346       unsigned dst = cp.getDstReg(),
    347                src = cp.getSrcReg();
    348 
    349       const float copyFactor = 0.5; // Cost of copy relative to load. Current
    350       // value plucked randomly out of the air.
    351 
    352       PBQP::PBQPNum cBenefit =
    353         copyFactor * LiveIntervals::getSpillWeight(false, true,
    354                                                    loopInfo->getLoopDepth(mbb));
    355 
    356       if (cp.isPhys()) {
    357         if (!mf->getRegInfo().isAllocatable(dst)) {
    358           continue;
    359         }
    360 
    361         const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
    362         unsigned pregOpt = 0;
    363         while (pregOpt < allowed.size() && allowed[pregOpt] != dst) {
    364           ++pregOpt;
    365         }
    366         if (pregOpt < allowed.size()) {
    367           ++pregOpt; // +1 to account for spill option.
    368           PBQP::Graph::NodeItr node = p->getNodeForVReg(src);
    369           addPhysRegCoalesce(g.getNodeCosts(node), pregOpt, cBenefit);
    370         }
    371       } else {
    372         const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
    373         const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
    374         PBQP::Graph::NodeItr node1 = p->getNodeForVReg(dst);
    375         PBQP::Graph::NodeItr node2 = p->getNodeForVReg(src);
    376         PBQP::Graph::EdgeItr edge = g.findEdge(node1, node2);
    377         if (edge == g.edgesEnd()) {
    378           edge = g.addEdge(node1, node2, PBQP::Matrix(allowed1->size() + 1,
    379                                                       allowed2->size() + 1,
    380                                                       0));
    381         } else {
    382           if (g.getEdgeNode1(edge) == node2) {
    383             std::swap(node1, node2);
    384             std::swap(allowed1, allowed2);
    385           }
    386         }
    387 
    388         addVirtRegCoalesce(g.getEdgeCosts(edge), *allowed1, *allowed2,
    389                            cBenefit);
    390       }
    391     }
    392   }
    393 
    394   return p;
    395 }
    396 
    397 void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
    398                                                    unsigned pregOption,
    399                                                    PBQP::PBQPNum benefit) {
    400   costVec[pregOption] += -benefit;
    401 }
    402 
    403 void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
    404                                     PBQP::Matrix &costMat,
    405                                     const PBQPRAProblem::AllowedSet &vr1Allowed,
    406                                     const PBQPRAProblem::AllowedSet &vr2Allowed,
    407                                     PBQP::PBQPNum benefit) {
    408 
    409   assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
    410   assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
    411 
    412   for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
    413     unsigned preg1 = vr1Allowed[i];
    414     for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
    415       unsigned preg2 = vr2Allowed[j];
    416 
    417       if (preg1 == preg2) {
    418         costMat[i + 1][j + 1] += -benefit;
    419       }
    420     }
    421   }
    422 }
    423 
    424 
    425 void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
    426   au.setPreservesCFG();
    427   au.addRequired<AliasAnalysis>();
    428   au.addPreserved<AliasAnalysis>();
    429   au.addRequired<SlotIndexes>();
    430   au.addPreserved<SlotIndexes>();
    431   au.addRequired<LiveIntervals>();
    432   au.addPreserved<LiveIntervals>();
    433   //au.addRequiredID(SplitCriticalEdgesID);
    434   if (customPassID)
    435     au.addRequiredID(*customPassID);
    436   au.addRequired<CalculateSpillWeights>();
    437   au.addRequired<LiveStacks>();
    438   au.addPreserved<LiveStacks>();
    439   au.addRequired<MachineDominatorTree>();
    440   au.addPreserved<MachineDominatorTree>();
    441   au.addRequired<MachineLoopInfo>();
    442   au.addPreserved<MachineLoopInfo>();
    443   au.addRequired<VirtRegMap>();
    444   au.addPreserved<VirtRegMap>();
    445   MachineFunctionPass::getAnalysisUsage(au);
    446 }
    447 
    448 void RegAllocPBQP::findVRegIntervalsToAlloc() {
    449 
    450   // Iterate over all live ranges.
    451   for (unsigned i = 0, e = mri->getNumVirtRegs(); i != e; ++i) {
    452     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
    453     if (mri->reg_nodbg_empty(Reg))
    454       continue;
    455     LiveInterval *li = &lis->getInterval(Reg);
    456 
    457     // If this live interval is non-empty we will use pbqp to allocate it.
    458     // Empty intervals we allocate in a simple post-processing stage in
    459     // finalizeAlloc.
    460     if (!li->empty()) {
    461       vregsToAlloc.insert(li->reg);
    462     } else {
    463       emptyIntervalVRegs.insert(li->reg);
    464     }
    465   }
    466 }
    467 
    468 bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
    469                                      const PBQP::Solution &solution) {
    470   // Set to true if we have any spills
    471   bool anotherRoundNeeded = false;
    472 
    473   // Clear the existing allocation.
    474   vrm->clearAllVirt();
    475 
    476   const PBQP::Graph &g = problem.getGraph();
    477   // Iterate over the nodes mapping the PBQP solution to a register
    478   // assignment.
    479   for (PBQP::Graph::ConstNodeItr node = g.nodesBegin(),
    480                                  nodeEnd = g.nodesEnd();
    481        node != nodeEnd; ++node) {
    482     unsigned vreg = problem.getVRegForNode(node);
    483     unsigned alloc = solution.getSelection(node);
    484 
    485     if (problem.isPRegOption(vreg, alloc)) {
    486       unsigned preg = problem.getPRegForOption(vreg, alloc);
    487       DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> "
    488             << tri->getName(preg) << "\n");
    489       assert(preg != 0 && "Invalid preg selected.");
    490       vrm->assignVirt2Phys(vreg, preg);
    491     } else if (problem.isSpillOption(vreg, alloc)) {
    492       vregsToAlloc.erase(vreg);
    493       SmallVector<LiveInterval*, 8> newSpills;
    494       LiveRangeEdit LRE(&lis->getInterval(vreg), newSpills, *mf, *lis, vrm);
    495       spiller->spill(LRE);
    496 
    497       DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> SPILLED (Cost: "
    498                    << LRE.getParent().weight << ", New vregs: ");
    499 
    500       // Copy any newly inserted live intervals into the list of regs to
    501       // allocate.
    502       for (LiveRangeEdit::iterator itr = LRE.begin(), end = LRE.end();
    503            itr != end; ++itr) {
    504         assert(!(*itr)->empty() && "Empty spill range.");
    505         DEBUG(dbgs() << PrintReg((*itr)->reg, tri) << " ");
    506         vregsToAlloc.insert((*itr)->reg);
    507       }
    508 
    509       DEBUG(dbgs() << ")\n");
    510 
    511       // We need another round if spill intervals were added.
    512       anotherRoundNeeded |= !LRE.empty();
    513     } else {
    514       llvm_unreachable("Unknown allocation option.");
    515     }
    516   }
    517 
    518   return !anotherRoundNeeded;
    519 }
    520 
    521 
    522 void RegAllocPBQP::finalizeAlloc() const {
    523   // First allocate registers for the empty intervals.
    524   for (RegSet::const_iterator
    525          itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
    526          itr != end; ++itr) {
    527     LiveInterval *li = &lis->getInterval(*itr);
    528 
    529     unsigned physReg = mri->getSimpleHint(li->reg);
    530 
    531     if (physReg == 0) {
    532       const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
    533       physReg = liRC->getRawAllocationOrder(*mf).front();
    534     }
    535 
    536     vrm->assignVirt2Phys(li->reg, physReg);
    537   }
    538 }
    539 
    540 bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
    541 
    542   mf = &MF;
    543   tm = &mf->getTarget();
    544   tri = tm->getRegisterInfo();
    545   tii = tm->getInstrInfo();
    546   mri = &mf->getRegInfo();
    547 
    548   lis = &getAnalysis<LiveIntervals>();
    549   lss = &getAnalysis<LiveStacks>();
    550   loopInfo = &getAnalysis<MachineLoopInfo>();
    551 
    552   vrm = &getAnalysis<VirtRegMap>();
    553   spiller.reset(createInlineSpiller(*this, MF, *vrm));
    554 
    555   mri->freezeReservedRegs(MF);
    556 
    557   DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getName() << "\n");
    558 
    559   // Allocator main loop:
    560   //
    561   // * Map current regalloc problem to a PBQP problem
    562   // * Solve the PBQP problem
    563   // * Map the solution back to a register allocation
    564   // * Spill if necessary
    565   //
    566   // This process is continued till no more spills are generated.
    567 
    568   // Find the vreg intervals in need of allocation.
    569   findVRegIntervalsToAlloc();
    570 
    571 #ifndef NDEBUG
    572   const Function* func = mf->getFunction();
    573   std::string fqn =
    574     func->getParent()->getModuleIdentifier() + "." +
    575     func->getName().str();
    576 #endif
    577 
    578   // If there are non-empty intervals allocate them using pbqp.
    579   if (!vregsToAlloc.empty()) {
    580 
    581     bool pbqpAllocComplete = false;
    582     unsigned round = 0;
    583 
    584     while (!pbqpAllocComplete) {
    585       DEBUG(dbgs() << "  PBQP Regalloc round " << round << ":\n");
    586 
    587       std::auto_ptr<PBQPRAProblem> problem =
    588         builder->build(mf, lis, loopInfo, vregsToAlloc);
    589 
    590 #ifndef NDEBUG
    591       if (pbqpDumpGraphs) {
    592         std::ostringstream rs;
    593         rs << round;
    594         std::string graphFileName(fqn + "." + rs.str() + ".pbqpgraph");
    595         std::string tmp;
    596         raw_fd_ostream os(graphFileName.c_str(), tmp);
    597         DEBUG(dbgs() << "Dumping graph for round " << round << " to \""
    598               << graphFileName << "\"\n");
    599         problem->getGraph().dump(os);
    600       }
    601 #endif
    602 
    603       PBQP::Solution solution =
    604         PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(
    605           problem->getGraph());
    606 
    607       pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
    608 
    609       ++round;
    610     }
    611   }
    612 
    613   // Finalise allocation, allocate empty ranges.
    614   finalizeAlloc();
    615   vregsToAlloc.clear();
    616   emptyIntervalVRegs.clear();
    617 
    618   DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
    619 
    620   return true;
    621 }
    622 
    623 FunctionPass* llvm::createPBQPRegisterAllocator(
    624                                            std::auto_ptr<PBQPBuilder> builder,
    625                                            char *customPassID) {
    626   return new RegAllocPBQP(builder, customPassID);
    627 }
    628 
    629 FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
    630   if (pbqpCoalescing) {
    631     return createPBQPRegisterAllocator(
    632              std::auto_ptr<PBQPBuilder>(new PBQPBuilderWithCoalescing()));
    633   } // else
    634   return createPBQPRegisterAllocator(
    635            std::auto_ptr<PBQPBuilder>(new PBQPBuilder()));
    636 }
    637 
    638 #undef DEBUG_TYPE
    639