RegAllocPBQP.cpp revision 1feb5854aeeda897e9318c8193d187673c8576b8
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/ADT/OwningPtr.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/MachineBlockFrequencyInfo.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/Graph.h"
49#include "llvm/CodeGen/PBQP/HeuristicSolver.h"
50#include "llvm/CodeGen/PBQP/Heuristics/Briggs.h"
51#include "llvm/CodeGen/RegAllocRegistry.h"
52#include "llvm/CodeGen/VirtRegMap.h"
53#include "llvm/IR/Module.h"
54#include "llvm/Support/Debug.h"
55#include "llvm/Support/raw_ostream.h"
56#include "llvm/Target/TargetInstrInfo.h"
57#include "llvm/Target/TargetMachine.h"
58#include <limits>
59#include <memory>
60#include <set>
61#include <sstream>
62#include <vector>
63
64using namespace llvm;
65
66static RegisterRegAlloc
67registerPBQPRepAlloc("pbqp", "PBQP register allocator",
68                       createDefaultPBQPRegisterAllocator);
69
70static cl::opt<bool>
71pbqpCoalescing("pbqp-coalescing",
72                cl::desc("Attempt coalescing during PBQP register allocation."),
73                cl::init(false), cl::Hidden);
74
75#ifndef NDEBUG
76static cl::opt<bool>
77pbqpDumpGraphs("pbqp-dump-graphs",
78               cl::desc("Dump graphs for each function/round in the compilation unit."),
79               cl::init(false), cl::Hidden);
80#endif
81
82namespace {
83
84///
85/// PBQP based allocators solve the register allocation problem by mapping
86/// register allocation problems to Partitioned Boolean Quadratic
87/// Programming problems.
88class RegAllocPBQP : public MachineFunctionPass {
89public:
90
91  static char ID;
92
93  /// Construct a PBQP register allocator.
94  RegAllocPBQP(OwningPtr<PBQPBuilder> &b, char *cPassID=0)
95      : MachineFunctionPass(ID), builder(b.take()), customPassID(cPassID) {
96    initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
97    initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
98    initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
99    initializeLiveStacksPass(*PassRegistry::getPassRegistry());
100    initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
101  }
102
103  /// Return the pass name.
104  virtual const char* getPassName() const {
105    return "PBQP Register Allocator";
106  }
107
108  /// PBQP analysis usage.
109  virtual void getAnalysisUsage(AnalysisUsage &au) const;
110
111  /// Perform register allocation
112  virtual bool runOnMachineFunction(MachineFunction &MF);
113
114private:
115
116  typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
117  typedef std::vector<const LiveInterval*> Node2LIMap;
118  typedef std::vector<unsigned> AllowedSet;
119  typedef std::vector<AllowedSet> AllowedSetMap;
120  typedef std::pair<unsigned, unsigned> RegPair;
121  typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
122  typedef std::set<unsigned> RegSet;
123
124
125  OwningPtr<PBQPBuilder> builder;
126
127  char *customPassID;
128
129  MachineFunction *mf;
130  const TargetMachine *tm;
131  const TargetRegisterInfo *tri;
132  const TargetInstrInfo *tii;
133  MachineRegisterInfo *mri;
134  const MachineBlockFrequencyInfo *mbfi;
135
136  OwningPtr<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
157char RegAllocPBQP::ID = 0;
158
159} // End anonymous namespace.
160
161unsigned 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
167PBQP::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
174const 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
182unsigned 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
190PBQPRAProblem *PBQPBuilder::build(MachineFunction *mf, const LiveIntervals *lis,
191                                  const MachineBlockFrequencyInfo *mbfi,
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  OwningPtr<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.take();
286}
287
288void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
289                                PBQP::PBQPNum spillCost) {
290  costVec[0] = spillCost;
291}
292
293void 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
314PBQPRAProblem *PBQPBuilderWithCoalescing::build(MachineFunction *mf,
315                                                const LiveIntervals *lis,
316                                                const MachineBlockFrequencyInfo *mbfi,
317                                                const RegSet &vregs) {
318
319  OwningPtr<PBQPRAProblem> p(PBQPBuilder::build(mf, lis, mbfi, vregs));
320  PBQP::Graph &g = p->getGraph();
321
322  const TargetMachine &tm = mf->getTarget();
323  CoalescerPair cp(*tm.getRegisterInfo());
324
325  // Scan the machine function and add a coalescing cost whenever CoalescerPair
326  // gives the Ok.
327  for (MachineFunction::const_iterator mbbItr = mf->begin(),
328                                       mbbEnd = mf->end();
329       mbbItr != mbbEnd; ++mbbItr) {
330    const MachineBasicBlock *mbb = &*mbbItr;
331
332    for (MachineBasicBlock::const_iterator miItr = mbb->begin(),
333                                           miEnd = mbb->end();
334         miItr != miEnd; ++miItr) {
335      const MachineInstr *mi = &*miItr;
336
337      if (!cp.setRegisters(mi)) {
338        continue; // Not coalescable.
339      }
340
341      if (cp.getSrcReg() == cp.getDstReg()) {
342        continue; // Already coalesced.
343      }
344
345      unsigned dst = cp.getDstReg(),
346               src = cp.getSrcReg();
347
348      const float copyFactor = 0.5; // Cost of copy relative to load. Current
349      // value plucked randomly out of the air.
350
351      PBQP::PBQPNum cBenefit =
352        copyFactor * LiveIntervals::getSpillWeight(false, true,
353                                                   mbfi->getBlockFreq(mbb));
354
355      if (cp.isPhys()) {
356        if (!mf->getRegInfo().isAllocatable(dst)) {
357          continue;
358        }
359
360        const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
361        unsigned pregOpt = 0;
362        while (pregOpt < allowed.size() && allowed[pregOpt] != dst) {
363          ++pregOpt;
364        }
365        if (pregOpt < allowed.size()) {
366          ++pregOpt; // +1 to account for spill option.
367          PBQP::Graph::NodeItr node = p->getNodeForVReg(src);
368          addPhysRegCoalesce(g.getNodeCosts(node), pregOpt, cBenefit);
369        }
370      } else {
371        const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
372        const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
373        PBQP::Graph::NodeItr node1 = p->getNodeForVReg(dst);
374        PBQP::Graph::NodeItr node2 = p->getNodeForVReg(src);
375        PBQP::Graph::EdgeItr edge = g.findEdge(node1, node2);
376        if (edge == g.edgesEnd()) {
377          edge = g.addEdge(node1, node2, PBQP::Matrix(allowed1->size() + 1,
378                                                      allowed2->size() + 1,
379                                                      0));
380        } else {
381          if (g.getEdgeNode1(edge) == node2) {
382            std::swap(node1, node2);
383            std::swap(allowed1, allowed2);
384          }
385        }
386
387        addVirtRegCoalesce(g.getEdgeCosts(edge), *allowed1, *allowed2,
388                           cBenefit);
389      }
390    }
391  }
392
393  return p.take();
394}
395
396void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
397                                                   unsigned pregOption,
398                                                   PBQP::PBQPNum benefit) {
399  costVec[pregOption] += -benefit;
400}
401
402void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
403                                    PBQP::Matrix &costMat,
404                                    const PBQPRAProblem::AllowedSet &vr1Allowed,
405                                    const PBQPRAProblem::AllowedSet &vr2Allowed,
406                                    PBQP::PBQPNum benefit) {
407
408  assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
409  assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
410
411  for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
412    unsigned preg1 = vr1Allowed[i];
413    for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
414      unsigned preg2 = vr2Allowed[j];
415
416      if (preg1 == preg2) {
417        costMat[i + 1][j + 1] += -benefit;
418      }
419    }
420  }
421}
422
423
424void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
425  au.setPreservesCFG();
426  au.addRequired<AliasAnalysis>();
427  au.addPreserved<AliasAnalysis>();
428  au.addRequired<SlotIndexes>();
429  au.addPreserved<SlotIndexes>();
430  au.addRequired<LiveIntervals>();
431  au.addPreserved<LiveIntervals>();
432  //au.addRequiredID(SplitCriticalEdgesID);
433  if (customPassID)
434    au.addRequiredID(*customPassID);
435  au.addRequired<CalculateSpillWeights>();
436  au.addRequired<LiveStacks>();
437  au.addPreserved<LiveStacks>();
438  au.addRequired<MachineBlockFrequencyInfo>();
439  au.addPreserved<MachineBlockFrequencyInfo>();
440  au.addRequired<MachineLoopInfo>();
441  au.addPreserved<MachineLoopInfo>();
442  au.addRequired<MachineDominatorTree>();
443  au.addPreserved<MachineDominatorTree>();
444  au.addRequired<VirtRegMap>();
445  au.addPreserved<VirtRegMap>();
446  MachineFunctionPass::getAnalysisUsage(au);
447}
448
449void RegAllocPBQP::findVRegIntervalsToAlloc() {
450
451  // Iterate over all live ranges.
452  for (unsigned i = 0, e = mri->getNumVirtRegs(); i != e; ++i) {
453    unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
454    if (mri->reg_nodbg_empty(Reg))
455      continue;
456    LiveInterval *li = &lis->getInterval(Reg);
457
458    // If this live interval is non-empty we will use pbqp to allocate it.
459    // Empty intervals we allocate in a simple post-processing stage in
460    // finalizeAlloc.
461    if (!li->empty()) {
462      vregsToAlloc.insert(li->reg);
463    } else {
464      emptyIntervalVRegs.insert(li->reg);
465    }
466  }
467}
468
469bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
470                                     const PBQP::Solution &solution) {
471  // Set to true if we have any spills
472  bool anotherRoundNeeded = false;
473
474  // Clear the existing allocation.
475  vrm->clearAllVirt();
476
477  const PBQP::Graph &g = problem.getGraph();
478  // Iterate over the nodes mapping the PBQP solution to a register
479  // assignment.
480  for (PBQP::Graph::ConstNodeItr node = g.nodesBegin(),
481                                 nodeEnd = g.nodesEnd();
482       node != nodeEnd; ++node) {
483    unsigned vreg = problem.getVRegForNode(node);
484    unsigned alloc = solution.getSelection(node);
485
486    if (problem.isPRegOption(vreg, alloc)) {
487      unsigned preg = problem.getPRegForOption(vreg, alloc);
488      DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> "
489            << tri->getName(preg) << "\n");
490      assert(preg != 0 && "Invalid preg selected.");
491      vrm->assignVirt2Phys(vreg, preg);
492    } else if (problem.isSpillOption(vreg, alloc)) {
493      vregsToAlloc.erase(vreg);
494      SmallVector<unsigned, 8> newSpills;
495      LiveRangeEdit LRE(&lis->getInterval(vreg), newSpills, *mf, *lis, vrm);
496      spiller->spill(LRE);
497
498      DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> SPILLED (Cost: "
499                   << LRE.getParent().weight << ", New vregs: ");
500
501      // Copy any newly inserted live intervals into the list of regs to
502      // allocate.
503      for (LiveRangeEdit::iterator itr = LRE.begin(), end = LRE.end();
504           itr != end; ++itr) {
505        LiveInterval &li = lis->getInterval(*itr);
506        assert(!li.empty() && "Empty spill range.");
507        DEBUG(dbgs() << PrintReg(li.reg, tri) << " ");
508        vregsToAlloc.insert(li.reg);
509      }
510
511      DEBUG(dbgs() << ")\n");
512
513      // We need another round if spill intervals were added.
514      anotherRoundNeeded |= !LRE.empty();
515    } else {
516      llvm_unreachable("Unknown allocation option.");
517    }
518  }
519
520  return !anotherRoundNeeded;
521}
522
523
524void RegAllocPBQP::finalizeAlloc() const {
525  // First allocate registers for the empty intervals.
526  for (RegSet::const_iterator
527         itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
528         itr != end; ++itr) {
529    LiveInterval *li = &lis->getInterval(*itr);
530
531    unsigned physReg = mri->getSimpleHint(li->reg);
532
533    if (physReg == 0) {
534      const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
535      physReg = liRC->getRawAllocationOrder(*mf).front();
536    }
537
538    vrm->assignVirt2Phys(li->reg, physReg);
539  }
540}
541
542bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
543
544  mf = &MF;
545  tm = &mf->getTarget();
546  tri = tm->getRegisterInfo();
547  tii = tm->getInstrInfo();
548  mri = &mf->getRegInfo();
549
550  lis = &getAnalysis<LiveIntervals>();
551  lss = &getAnalysis<LiveStacks>();
552  mbfi = &getAnalysis<MachineBlockFrequencyInfo>();
553
554  vrm = &getAnalysis<VirtRegMap>();
555  spiller.reset(createInlineSpiller(*this, MF, *vrm));
556
557  mri->freezeReservedRegs(MF);
558
559  DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getName() << "\n");
560
561  // Allocator main loop:
562  //
563  // * Map current regalloc problem to a PBQP problem
564  // * Solve the PBQP problem
565  // * Map the solution back to a register allocation
566  // * Spill if necessary
567  //
568  // This process is continued till no more spills are generated.
569
570  // Find the vreg intervals in need of allocation.
571  findVRegIntervalsToAlloc();
572
573#ifndef NDEBUG
574  const Function* func = mf->getFunction();
575  std::string fqn =
576    func->getParent()->getModuleIdentifier() + "." +
577    func->getName().str();
578#endif
579
580  // If there are non-empty intervals allocate them using pbqp.
581  if (!vregsToAlloc.empty()) {
582
583    bool pbqpAllocComplete = false;
584    unsigned round = 0;
585
586    while (!pbqpAllocComplete) {
587      DEBUG(dbgs() << "  PBQP Regalloc round " << round << ":\n");
588
589      OwningPtr<PBQPRAProblem> problem(
590        builder->build(mf, lis, mbfi, vregsToAlloc));
591
592#ifndef NDEBUG
593      if (pbqpDumpGraphs) {
594        std::ostringstream rs;
595        rs << round;
596        std::string graphFileName(fqn + "." + rs.str() + ".pbqpgraph");
597        std::string tmp;
598        raw_fd_ostream os(graphFileName.c_str(), tmp);
599        DEBUG(dbgs() << "Dumping graph for round " << round << " to \""
600              << graphFileName << "\"\n");
601        problem->getGraph().dump(os);
602      }
603#endif
604
605      PBQP::Solution solution =
606        PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(
607          problem->getGraph());
608
609      pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
610
611      ++round;
612    }
613  }
614
615  // Finalise allocation, allocate empty ranges.
616  finalizeAlloc();
617  vregsToAlloc.clear();
618  emptyIntervalVRegs.clear();
619
620  DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
621
622  return true;
623}
624
625FunctionPass* llvm::createPBQPRegisterAllocator(
626                                           OwningPtr<PBQPBuilder> &builder,
627                                           char *customPassID) {
628  return new RegAllocPBQP(builder, customPassID);
629}
630
631FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
632  OwningPtr<PBQPBuilder> Builder;
633  if (pbqpCoalescing)
634    Builder.reset(new PBQPBuilderWithCoalescing());
635  else
636    Builder.reset(new PBQPBuilder());
637  return createPBQPRegisterAllocator(Builder);
638}
639
640#undef DEBUG_TYPE
641