Indentation change.
[llvm/avr.git] / lib / CodeGen / RegAllocPBQP.cpp
blobe8b8152b3875f96a0a41ab07f253c6f301d5fab1
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.
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:
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.
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.
30 //===----------------------------------------------------------------------===//
32 #define DEBUG_TYPE "regalloc"
34 #include "PBQP/HeuristicSolver.h"
35 #include "PBQP/SimpleGraph.h"
36 #include "PBQP/Heuristics/Briggs.h"
37 #include "VirtRegMap.h"
38 #include "VirtRegRewriter.h"
39 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
40 #include "llvm/CodeGen/LiveStackAnalysis.h"
41 #include "llvm/CodeGen/MachineFunctionPass.h"
42 #include "llvm/CodeGen/MachineLoopInfo.h"
43 #include "llvm/CodeGen/MachineRegisterInfo.h"
44 #include "llvm/CodeGen/RegAllocRegistry.h"
45 #include "llvm/CodeGen/RegisterCoalescer.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Target/TargetInstrInfo.h"
49 #include "llvm/Target/TargetMachine.h"
50 #include <limits>
51 #include <map>
52 #include <memory>
53 #include <set>
54 #include <vector>
56 using namespace llvm;
58 static RegisterRegAlloc
59 registerPBQPRepAlloc("pbqp", "PBQP register allocator.",
60 llvm::createPBQPRegisterAllocator);
62 namespace {
64 ///
65 /// PBQP based allocators solve the register allocation problem by mapping
66 /// register allocation problems to Partitioned Boolean Quadratic
67 /// Programming problems.
68 class VISIBILITY_HIDDEN PBQPRegAlloc : public MachineFunctionPass {
69 public:
71 static char ID;
73 /// Construct a PBQP register allocator.
74 PBQPRegAlloc() : MachineFunctionPass(&ID) {}
76 /// Return the pass name.
77 virtual const char* getPassName() const {
78 return "PBQP Register Allocator";
81 /// PBQP analysis usage.
82 virtual void getAnalysisUsage(AnalysisUsage &au) const {
83 au.addRequired<LiveIntervals>();
84 //au.addRequiredID(SplitCriticalEdgesID);
85 au.addRequired<RegisterCoalescer>();
86 au.addRequired<LiveStacks>();
87 au.addPreserved<LiveStacks>();
88 au.addRequired<MachineLoopInfo>();
89 au.addPreserved<MachineLoopInfo>();
90 au.addRequired<VirtRegMap>();
91 MachineFunctionPass::getAnalysisUsage(au);
94 /// Perform register allocation
95 virtual bool runOnMachineFunction(MachineFunction &MF);
97 private:
98 typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
99 typedef std::vector<const LiveInterval*> Node2LIMap;
100 typedef std::vector<unsigned> AllowedSet;
101 typedef std::vector<AllowedSet> AllowedSetMap;
102 typedef std::set<unsigned> RegSet;
103 typedef std::pair<unsigned, unsigned> RegPair;
104 typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
106 typedef std::set<LiveInterval*> LiveIntervalSet;
108 MachineFunction *mf;
109 const TargetMachine *tm;
110 const TargetRegisterInfo *tri;
111 const TargetInstrInfo *tii;
112 const MachineLoopInfo *loopInfo;
113 MachineRegisterInfo *mri;
115 LiveIntervals *lis;
116 LiveStacks *lss;
117 VirtRegMap *vrm;
119 LI2NodeMap li2Node;
120 Node2LIMap node2LI;
121 AllowedSetMap allowedSets;
122 LiveIntervalSet vregIntervalsToAlloc,
123 emptyVRegIntervals;
126 /// Builds a PBQP cost vector.
127 template <typename RegContainer>
128 PBQP::Vector buildCostVector(unsigned vReg,
129 const RegContainer &allowed,
130 const CoalesceMap &cealesces,
131 PBQP::PBQPNum spillCost) const;
133 /// \brief Builds a PBQP interference matrix.
135 /// @return Either a pointer to a non-zero PBQP matrix representing the
136 /// allocation option costs, or a null pointer for a zero matrix.
138 /// Expects allowed sets for two interfering LiveIntervals. These allowed
139 /// sets should contain only allocable registers from the LiveInterval's
140 /// register class, with any interfering pre-colored registers removed.
141 template <typename RegContainer>
142 PBQP::Matrix* buildInterferenceMatrix(const RegContainer &allowed1,
143 const RegContainer &allowed2) const;
146 /// Expects allowed sets for two potentially coalescable LiveIntervals,
147 /// and an estimated benefit due to coalescing. The allowed sets should
148 /// contain only allocable registers from the LiveInterval's register
149 /// classes, with any interfering pre-colored registers removed.
150 template <typename RegContainer>
151 PBQP::Matrix* buildCoalescingMatrix(const RegContainer &allowed1,
152 const RegContainer &allowed2,
153 PBQP::PBQPNum cBenefit) const;
155 /// \brief Finds coalescing opportunities and returns them as a map.
157 /// Any entries in the map are guaranteed coalescable, even if their
158 /// corresponding live intervals overlap.
159 CoalesceMap findCoalesces();
161 /// \brief Finds the initial set of vreg intervals to allocate.
162 void findVRegIntervalsToAlloc();
164 /// \brief Constructs a PBQP problem representation of the register
165 /// allocation problem for this function.
167 /// @return a PBQP solver object for the register allocation problem.
168 PBQP::SimpleGraph constructPBQPProblem();
170 /// \brief Adds a stack interval if the given live interval has been
171 /// spilled. Used to support stack slot coloring.
172 void addStackInterval(const LiveInterval *spilled,MachineRegisterInfo* mri);
174 /// \brief Given a solved PBQP problem maps this solution back to a register
175 /// assignment.
176 bool mapPBQPToRegAlloc(const PBQP::Solution &solution);
178 /// \brief Postprocessing before final spilling. Sets basic block "live in"
179 /// variables.
180 void finalizeAlloc() const;
184 char PBQPRegAlloc::ID = 0;
188 template <typename RegContainer>
189 PBQP::Vector PBQPRegAlloc::buildCostVector(unsigned vReg,
190 const RegContainer &allowed,
191 const CoalesceMap &coalesces,
192 PBQP::PBQPNum spillCost) const {
194 typedef typename RegContainer::const_iterator AllowedItr;
196 // Allocate vector. Additional element (0th) used for spill option
197 PBQP::Vector v(allowed.size() + 1, 0);
199 v[0] = spillCost;
201 // Iterate over the allowed registers inserting coalesce benefits if there
202 // are any.
203 unsigned ai = 0;
204 for (AllowedItr itr = allowed.begin(), end = allowed.end();
205 itr != end; ++itr, ++ai) {
207 unsigned pReg = *itr;
209 CoalesceMap::const_iterator cmItr =
210 coalesces.find(RegPair(vReg, pReg));
212 // No coalesce - on to the next preg.
213 if (cmItr == coalesces.end())
214 continue;
216 // We have a coalesce - insert the benefit.
217 v[ai + 1] = -cmItr->second;
220 return v;
223 template <typename RegContainer>
224 PBQP::Matrix* PBQPRegAlloc::buildInterferenceMatrix(
225 const RegContainer &allowed1, const RegContainer &allowed2) const {
227 typedef typename RegContainer::const_iterator RegContainerIterator;
229 // Construct a PBQP matrix representing the cost of allocation options. The
230 // rows and columns correspond to the allocation options for the two live
231 // intervals. Elements will be infinite where corresponding registers alias,
232 // since we cannot allocate aliasing registers to interfering live intervals.
233 // All other elements (non-aliasing combinations) will have zero cost. Note
234 // that the spill option (element 0,0) has zero cost, since we can allocate
235 // both intervals to memory safely (the cost for each individual allocation
236 // to memory is accounted for by the cost vectors for each live interval).
237 PBQP::Matrix *m =
238 new PBQP::Matrix(allowed1.size() + 1, allowed2.size() + 1, 0);
240 // Assume this is a zero matrix until proven otherwise. Zero matrices occur
241 // between interfering live ranges with non-overlapping register sets (e.g.
242 // non-overlapping reg classes, or disjoint sets of allowed regs within the
243 // same class). The term "overlapping" is used advisedly: sets which do not
244 // intersect, but contain registers which alias, will have non-zero matrices.
245 // We optimize zero matrices away to improve solver speed.
246 bool isZeroMatrix = true;
249 // Row index. Starts at 1, since the 0th row is for the spill option, which
250 // is always zero.
251 unsigned ri = 1;
253 // Iterate over allowed sets, insert infinities where required.
254 for (RegContainerIterator a1Itr = allowed1.begin(), a1End = allowed1.end();
255 a1Itr != a1End; ++a1Itr) {
257 // Column index, starts at 1 as for row index.
258 unsigned ci = 1;
259 unsigned reg1 = *a1Itr;
261 for (RegContainerIterator a2Itr = allowed2.begin(), a2End = allowed2.end();
262 a2Itr != a2End; ++a2Itr) {
264 unsigned reg2 = *a2Itr;
266 // If the row/column regs are identical or alias insert an infinity.
267 if ((reg1 == reg2) || tri->areAliases(reg1, reg2)) {
268 (*m)[ri][ci] = std::numeric_limits<PBQP::PBQPNum>::infinity();
269 isZeroMatrix = false;
272 ++ci;
275 ++ri;
278 // If this turns out to be a zero matrix...
279 if (isZeroMatrix) {
280 // free it and return null.
281 delete m;
282 return 0;
285 // ...otherwise return the cost matrix.
286 return m;
289 template <typename RegContainer>
290 PBQP::Matrix* PBQPRegAlloc::buildCoalescingMatrix(
291 const RegContainer &allowed1, const RegContainer &allowed2,
292 PBQP::PBQPNum cBenefit) const {
294 typedef typename RegContainer::const_iterator RegContainerIterator;
296 // Construct a PBQP Matrix representing the benefits of coalescing. As with
297 // interference matrices the rows and columns represent allowed registers
298 // for the LiveIntervals which are (potentially) to be coalesced. The amount
299 // -cBenefit will be placed in any element representing the same register
300 // for both intervals.
301 PBQP::Matrix *m =
302 new PBQP::Matrix(allowed1.size() + 1, allowed2.size() + 1, 0);
304 // Reset costs to zero.
305 m->reset(0);
307 // Assume the matrix is zero till proven otherwise. Zero matrices will be
308 // optimized away as in the interference case.
309 bool isZeroMatrix = true;
311 // Row index. Starts at 1, since the 0th row is for the spill option, which
312 // is always zero.
313 unsigned ri = 1;
315 // Iterate over the allowed sets, insert coalescing benefits where
316 // appropriate.
317 for (RegContainerIterator a1Itr = allowed1.begin(), a1End = allowed1.end();
318 a1Itr != a1End; ++a1Itr) {
320 // Column index, starts at 1 as for row index.
321 unsigned ci = 1;
322 unsigned reg1 = *a1Itr;
324 for (RegContainerIterator a2Itr = allowed2.begin(), a2End = allowed2.end();
325 a2Itr != a2End; ++a2Itr) {
327 // If the row and column represent the same register insert a beneficial
328 // cost to preference this allocation - it would allow us to eliminate a
329 // move instruction.
330 if (reg1 == *a2Itr) {
331 (*m)[ri][ci] = -cBenefit;
332 isZeroMatrix = false;
335 ++ci;
338 ++ri;
341 // If this turns out to be a zero matrix...
342 if (isZeroMatrix) {
343 // ...free it and return null.
344 delete m;
345 return 0;
348 return m;
351 PBQPRegAlloc::CoalesceMap PBQPRegAlloc::findCoalesces() {
353 typedef MachineFunction::const_iterator MFIterator;
354 typedef MachineBasicBlock::const_iterator MBBIterator;
355 typedef LiveInterval::const_vni_iterator VNIIterator;
357 CoalesceMap coalescesFound;
359 // To find coalesces we need to iterate over the function looking for
360 // copy instructions.
361 for (MFIterator bbItr = mf->begin(), bbEnd = mf->end();
362 bbItr != bbEnd; ++bbItr) {
364 const MachineBasicBlock *mbb = &*bbItr;
366 for (MBBIterator iItr = mbb->begin(), iEnd = mbb->end();
367 iItr != iEnd; ++iItr) {
369 const MachineInstr *instr = &*iItr;
370 unsigned srcReg, dstReg, srcSubReg, dstSubReg;
372 // If this isn't a copy then continue to the next instruction.
373 if (!tii->isMoveInstr(*instr, srcReg, dstReg, srcSubReg, dstSubReg))
374 continue;
376 // If the registers are already the same our job is nice and easy.
377 if (dstReg == srcReg)
378 continue;
380 bool srcRegIsPhysical = TargetRegisterInfo::isPhysicalRegister(srcReg),
381 dstRegIsPhysical = TargetRegisterInfo::isPhysicalRegister(dstReg);
383 // If both registers are physical then we can't coalesce.
384 if (srcRegIsPhysical && dstRegIsPhysical)
385 continue;
387 // If it's a copy that includes a virtual register but the source and
388 // destination classes differ then we can't coalesce, so continue with
389 // the next instruction.
390 const TargetRegisterClass *srcRegClass = srcRegIsPhysical ?
391 tri->getPhysicalRegisterRegClass(srcReg) : mri->getRegClass(srcReg);
393 const TargetRegisterClass *dstRegClass = dstRegIsPhysical ?
394 tri->getPhysicalRegisterRegClass(dstReg) : mri->getRegClass(dstReg);
396 if (srcRegClass != dstRegClass)
397 continue;
399 // We also need any physical regs to be allocable, coalescing with
400 // a non-allocable register is invalid.
401 if (srcRegIsPhysical) {
402 if (std::find(srcRegClass->allocation_order_begin(*mf),
403 srcRegClass->allocation_order_end(*mf), srcReg) ==
404 srcRegClass->allocation_order_end(*mf))
405 continue;
408 if (dstRegIsPhysical) {
409 if (std::find(dstRegClass->allocation_order_begin(*mf),
410 dstRegClass->allocation_order_end(*mf), dstReg) ==
411 dstRegClass->allocation_order_end(*mf))
412 continue;
415 // If we've made it here we have a copy with compatible register classes.
416 // We can probably coalesce, but we need to consider overlap.
417 const LiveInterval *srcLI = &lis->getInterval(srcReg),
418 *dstLI = &lis->getInterval(dstReg);
420 if (srcLI->overlaps(*dstLI)) {
421 // Even in the case of an overlap we might still be able to coalesce,
422 // but we need to make sure that no definition of either range occurs
423 // while the other range is live.
425 // Otherwise start by assuming we're ok.
426 bool badDef = false;
428 // Test all defs of the source range.
429 for (VNIIterator
430 vniItr = srcLI->vni_begin(), vniEnd = srcLI->vni_end();
431 vniItr != vniEnd; ++vniItr) {
433 // If we find a def that kills the coalescing opportunity then
434 // record it and break from the loop.
435 if (dstLI->liveAt((*vniItr)->def)) {
436 badDef = true;
437 break;
441 // If we have a bad def give up, continue to the next instruction.
442 if (badDef)
443 continue;
445 // Otherwise test definitions of the destination range.
446 for (VNIIterator
447 vniItr = dstLI->vni_begin(), vniEnd = dstLI->vni_end();
448 vniItr != vniEnd; ++vniItr) {
450 // We want to make sure we skip the copy instruction itself.
451 if ((*vniItr)->getCopy() == instr)
452 continue;
454 if (srcLI->liveAt((*vniItr)->def)) {
455 badDef = true;
456 break;
460 // As before a bad def we give up and continue to the next instr.
461 if (badDef)
462 continue;
465 // If we make it to here then either the ranges didn't overlap, or they
466 // did, but none of their definitions would prevent us from coalescing.
467 // We're good to go with the coalesce.
469 float cBenefit = powf(10.0f, loopInfo->getLoopDepth(mbb)) / 5.0;
471 coalescesFound[RegPair(srcReg, dstReg)] = cBenefit;
472 coalescesFound[RegPair(dstReg, srcReg)] = cBenefit;
477 return coalescesFound;
480 void PBQPRegAlloc::findVRegIntervalsToAlloc() {
482 // Iterate over all live ranges.
483 for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
484 itr != end; ++itr) {
486 // Ignore physical ones.
487 if (TargetRegisterInfo::isPhysicalRegister(itr->first))
488 continue;
490 LiveInterval *li = itr->second;
492 // If this live interval is non-empty we will use pbqp to allocate it.
493 // Empty intervals we allocate in a simple post-processing stage in
494 // finalizeAlloc.
495 if (!li->empty()) {
496 vregIntervalsToAlloc.insert(li);
498 else {
499 emptyVRegIntervals.insert(li);
504 PBQP::SimpleGraph PBQPRegAlloc::constructPBQPProblem() {
506 typedef std::vector<const LiveInterval*> LIVector;
507 typedef std::vector<unsigned> RegVector;
508 typedef std::vector<PBQP::SimpleGraph::NodeIterator> NodeVector;
510 // This will store the physical intervals for easy reference.
511 LIVector physIntervals;
513 // Start by clearing the old node <-> live interval mappings & allowed sets
514 li2Node.clear();
515 node2LI.clear();
516 allowedSets.clear();
518 // Populate physIntervals, update preg use:
519 for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
520 itr != end; ++itr) {
522 if (TargetRegisterInfo::isPhysicalRegister(itr->first)) {
523 physIntervals.push_back(itr->second);
524 mri->setPhysRegUsed(itr->second->reg);
528 // Iterate over vreg intervals, construct live interval <-> node number
529 // mappings.
530 for (LiveIntervalSet::const_iterator
531 itr = vregIntervalsToAlloc.begin(), end = vregIntervalsToAlloc.end();
532 itr != end; ++itr) {
533 const LiveInterval *li = *itr;
535 li2Node[li] = node2LI.size();
536 node2LI.push_back(li);
539 // Get the set of potential coalesces.
540 CoalesceMap coalesces;//(findCoalesces());
542 // Construct a PBQP solver for this problem
543 PBQP::SimpleGraph problem;
544 NodeVector problemNodes(vregIntervalsToAlloc.size());
546 // Resize allowedSets container appropriately.
547 allowedSets.resize(vregIntervalsToAlloc.size());
549 // Iterate over virtual register intervals to compute allowed sets...
550 for (unsigned node = 0; node < node2LI.size(); ++node) {
552 // Grab pointers to the interval and its register class.
553 const LiveInterval *li = node2LI[node];
554 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
556 // Start by assuming all allocable registers in the class are allowed...
557 RegVector liAllowed(liRC->allocation_order_begin(*mf),
558 liRC->allocation_order_end(*mf));
560 // Eliminate the physical registers which overlap with this range, along
561 // with all their aliases.
562 for (LIVector::iterator pItr = physIntervals.begin(),
563 pEnd = physIntervals.end(); pItr != pEnd; ++pItr) {
565 if (!li->overlaps(**pItr))
566 continue;
568 unsigned pReg = (*pItr)->reg;
570 // If we get here then the live intervals overlap, but we're still ok
571 // if they're coalescable.
572 if (coalesces.find(RegPair(li->reg, pReg)) != coalesces.end())
573 continue;
575 // If we get here then we have a genuine exclusion.
577 // Remove the overlapping reg...
578 RegVector::iterator eraseItr =
579 std::find(liAllowed.begin(), liAllowed.end(), pReg);
581 if (eraseItr != liAllowed.end())
582 liAllowed.erase(eraseItr);
584 const unsigned *aliasItr = tri->getAliasSet(pReg);
586 if (aliasItr != 0) {
587 // ...and its aliases.
588 for (; *aliasItr != 0; ++aliasItr) {
589 RegVector::iterator eraseItr =
590 std::find(liAllowed.begin(), liAllowed.end(), *aliasItr);
592 if (eraseItr != liAllowed.end()) {
593 liAllowed.erase(eraseItr);
599 // Copy the allowed set into a member vector for use when constructing cost
600 // vectors & matrices, and mapping PBQP solutions back to assignments.
601 allowedSets[node] = AllowedSet(liAllowed.begin(), liAllowed.end());
603 // Set the spill cost to the interval weight, or epsilon if the
604 // interval weight is zero
605 PBQP::PBQPNum spillCost = (li->weight != 0.0) ?
606 li->weight : std::numeric_limits<PBQP::PBQPNum>::min();
608 // Build a cost vector for this interval.
609 problemNodes[node] =
610 problem.addNode(
611 buildCostVector(li->reg, allowedSets[node], coalesces, spillCost));
616 // Now add the cost matrices...
617 for (unsigned node1 = 0; node1 < node2LI.size(); ++node1) {
618 const LiveInterval *li = node2LI[node1];
620 // Test for live range overlaps and insert interference matrices.
621 for (unsigned node2 = node1 + 1; node2 < node2LI.size(); ++node2) {
622 const LiveInterval *li2 = node2LI[node2];
624 CoalesceMap::const_iterator cmItr =
625 coalesces.find(RegPair(li->reg, li2->reg));
627 PBQP::Matrix *m = 0;
629 if (cmItr != coalesces.end()) {
630 m = buildCoalescingMatrix(allowedSets[node1], allowedSets[node2],
631 cmItr->second);
633 else if (li->overlaps(*li2)) {
634 m = buildInterferenceMatrix(allowedSets[node1], allowedSets[node2]);
637 if (m != 0) {
638 problem.addEdge(problemNodes[node1],
639 problemNodes[node2],
640 *m);
642 delete m;
647 problem.assignNodeIDs();
649 assert(problem.getNumNodes() == allowedSets.size());
650 for (unsigned i = 0; i < allowedSets.size(); ++i) {
651 assert(problem.getNodeItr(i) == problemNodes[i]);
654 std::cerr << "Allocating for " << problem.getNumNodes() << " nodes, "
655 << problem.getNumEdges() << " edges.\n";
657 problem.printDot(std::cerr);
659 // We're done, PBQP problem constructed - return it.
660 return problem;
663 void PBQPRegAlloc::addStackInterval(const LiveInterval *spilled,
664 MachineRegisterInfo* mri) {
665 int stackSlot = vrm->getStackSlot(spilled->reg);
667 if (stackSlot == VirtRegMap::NO_STACK_SLOT)
668 return;
670 const TargetRegisterClass *RC = mri->getRegClass(spilled->reg);
671 LiveInterval &stackInterval = lss->getOrCreateInterval(stackSlot, RC);
673 VNInfo *vni;
674 if (stackInterval.getNumValNums() != 0)
675 vni = stackInterval.getValNumInfo(0);
676 else
677 vni = stackInterval.getNextValue(0, 0, false, lss->getVNInfoAllocator());
679 LiveInterval &rhsInterval = lis->getInterval(spilled->reg);
680 stackInterval.MergeRangesInAsValue(rhsInterval, vni);
683 bool PBQPRegAlloc::mapPBQPToRegAlloc(const PBQP::Solution &solution) {
685 static unsigned round = 0;
686 (void) round;
688 // Set to true if we have any spills
689 bool anotherRoundNeeded = false;
691 // Clear the existing allocation.
692 vrm->clearAllVirt();
694 // Iterate over the nodes mapping the PBQP solution to a register assignment.
695 for (unsigned node = 0; node < node2LI.size(); ++node) {
696 unsigned virtReg = node2LI[node]->reg,
697 allocSelection = solution.getSelection(node);
700 // If the PBQP solution is non-zero it's a physical register...
701 if (allocSelection != 0) {
702 // Get the physical reg, subtracting 1 to account for the spill option.
703 unsigned physReg = allowedSets[node][allocSelection - 1];
705 DOUT << "VREG " << virtReg << " -> " << tri->getName(physReg) << "\n";
707 assert(physReg != 0);
709 // Add to the virt reg map and update the used phys regs.
710 vrm->assignVirt2Phys(virtReg, physReg);
712 // ...Otherwise it's a spill.
713 else {
715 // Make sure we ignore this virtual reg on the next round
716 // of allocation
717 vregIntervalsToAlloc.erase(&lis->getInterval(virtReg));
719 // Insert spill ranges for this live range
720 const LiveInterval *spillInterval = node2LI[node];
721 double oldSpillWeight = spillInterval->weight;
722 SmallVector<LiveInterval*, 8> spillIs;
723 std::vector<LiveInterval*> newSpills =
724 lis->addIntervalsForSpills(*spillInterval, spillIs, loopInfo, *vrm);
725 addStackInterval(spillInterval, mri);
727 DOUT << "VREG " << virtReg << " -> SPILLED (Cost: "
728 << oldSpillWeight << ", New vregs: ";
730 // Copy any newly inserted live intervals into the list of regs to
731 // allocate.
732 for (std::vector<LiveInterval*>::const_iterator
733 itr = newSpills.begin(), end = newSpills.end();
734 itr != end; ++itr) {
736 assert(!(*itr)->empty() && "Empty spill range.");
738 DOUT << (*itr)->reg << " ";
740 vregIntervalsToAlloc.insert(*itr);
743 DOUT << ")\n";
745 // We need another round if spill intervals were added.
746 anotherRoundNeeded |= !newSpills.empty();
750 return !anotherRoundNeeded;
753 void PBQPRegAlloc::finalizeAlloc() const {
754 typedef LiveIntervals::iterator LIIterator;
755 typedef LiveInterval::Ranges::const_iterator LRIterator;
757 // First allocate registers for the empty intervals.
758 for (LiveIntervalSet::const_iterator
759 itr = emptyVRegIntervals.begin(), end = emptyVRegIntervals.end();
760 itr != end; ++itr) {
761 LiveInterval *li = *itr;
763 unsigned physReg = vrm->getRegAllocPref(li->reg);
765 if (physReg == 0) {
766 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
767 physReg = *liRC->allocation_order_begin(*mf);
770 vrm->assignVirt2Phys(li->reg, physReg);
773 // Finally iterate over the basic blocks to compute and set the live-in sets.
774 SmallVector<MachineBasicBlock*, 8> liveInMBBs;
775 MachineBasicBlock *entryMBB = &*mf->begin();
777 for (LIIterator liItr = lis->begin(), liEnd = lis->end();
778 liItr != liEnd; ++liItr) {
780 const LiveInterval *li = liItr->second;
781 unsigned reg = 0;
783 // Get the physical register for this interval
784 if (TargetRegisterInfo::isPhysicalRegister(li->reg)) {
785 reg = li->reg;
787 else if (vrm->isAssignedReg(li->reg)) {
788 reg = vrm->getPhys(li->reg);
790 else {
791 // Ranges which are assigned a stack slot only are ignored.
792 continue;
795 if (reg == 0) {
796 // Filter out zero regs - they're for intervals that were spilled.
797 continue;
800 // Iterate over the ranges of the current interval...
801 for (LRIterator lrItr = li->begin(), lrEnd = li->end();
802 lrItr != lrEnd; ++lrItr) {
804 // Find the set of basic blocks which this range is live into...
805 if (lis->findLiveInMBBs(lrItr->start, lrItr->end, liveInMBBs)) {
806 // And add the physreg for this interval to their live-in sets.
807 for (unsigned i = 0; i < liveInMBBs.size(); ++i) {
808 if (liveInMBBs[i] != entryMBB) {
809 if (!liveInMBBs[i]->isLiveIn(reg)) {
810 liveInMBBs[i]->addLiveIn(reg);
814 liveInMBBs.clear();
821 bool PBQPRegAlloc::runOnMachineFunction(MachineFunction &MF) {
823 mf = &MF;
824 tm = &mf->getTarget();
825 tri = tm->getRegisterInfo();
826 tii = tm->getInstrInfo();
827 mri = &mf->getRegInfo();
829 lis = &getAnalysis<LiveIntervals>();
830 lss = &getAnalysis<LiveStacks>();
831 loopInfo = &getAnalysis<MachineLoopInfo>();
833 vrm = &getAnalysis<VirtRegMap>();
835 DEBUG(errs() << "PBQP2 Register Allocating for " << mf->getFunction()->getName() << "\n");
837 // Allocator main loop:
839 // * Map current regalloc problem to a PBQP problem
840 // * Solve the PBQP problem
841 // * Map the solution back to a register allocation
842 // * Spill if necessary
844 // This process is continued till no more spills are generated.
846 // Find the vreg intervals in need of allocation.
847 findVRegIntervalsToAlloc();
849 // If there aren't any then we're done here.
850 if (vregIntervalsToAlloc.empty() && emptyVRegIntervals.empty())
851 return true;
853 // If there are non-empty intervals allocate them using pbqp.
854 if (!vregIntervalsToAlloc.empty()) {
856 bool pbqpAllocComplete = false;
857 unsigned round = 0;
859 while (!pbqpAllocComplete) {
860 DEBUG(errs() << " PBQP Regalloc round " << round << ":\n");
862 PBQP::SimpleGraph problem = constructPBQPProblem();
863 PBQP::HeuristicSolver<PBQP::Heuristics::Briggs> solver;
864 problem.assignNodeIDs();
865 PBQP::Solution solution = solver.solve(problem);
867 std::cerr << "Solution:\n";
868 for (unsigned i = 0; i < solution.numNodes(); ++i) {
869 std::cerr << " " << i << " -> " << solution.getSelection(i) << "\n";
872 pbqpAllocComplete = mapPBQPToRegAlloc(solution);
874 ++round;
878 // Finalise allocation, allocate empty ranges.
879 finalizeAlloc();
881 vregIntervalsToAlloc.clear();
882 emptyVRegIntervals.clear();
883 li2Node.clear();
884 node2LI.clear();
885 allowedSets.clear();
887 DEBUG(errs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
889 // Run rewriter
890 std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
892 rewriter->runOnMachineFunction(*mf, *vrm, lis);
894 return true;
897 FunctionPass* llvm::createPBQPRegisterAllocator() {
898 return new PBQPRegAlloc();
902 #undef DEBUG_TYPE