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