1 //===------ RegAllocPBQP.cpp ---- PBQP Register Allocator -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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,
30 //===----------------------------------------------------------------------===//
32 #define DEBUG_TYPE "regalloc"
34 #include "RenderMachineFunction.h"
36 #include "VirtRegMap.h"
37 #include "VirtRegRewriter.h"
38 #include "llvm/CodeGen/CalcSpillWeights.h"
39 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
40 #include "llvm/CodeGen/LiveStackAnalysis.h"
41 #include "llvm/CodeGen/RegAllocPBQP.h"
42 #include "llvm/CodeGen/MachineFunctionPass.h"
43 #include "llvm/CodeGen/MachineLoopInfo.h"
44 #include "llvm/CodeGen/MachineRegisterInfo.h"
45 #include "llvm/CodeGen/PBQP/HeuristicSolver.h"
46 #include "llvm/CodeGen/PBQP/Graph.h"
47 #include "llvm/CodeGen/PBQP/Heuristics/Briggs.h"
48 #include "llvm/CodeGen/RegAllocRegistry.h"
49 #include "llvm/CodeGen/RegisterCoalescer.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/Target/TargetInstrInfo.h"
53 #include "llvm/Target/TargetMachine.h"
61 static RegisterRegAlloc
62 registerPBQPRepAlloc("pbqp", "PBQP register allocator",
63 createDefaultPBQPRegisterAllocator);
66 pbqpCoalescing("pbqp-coalescing",
67 cl::desc("Attempt coalescing during PBQP register allocation."),
68 cl::init(false), cl::Hidden);
71 pbqpBuilder("pbqp-builder",
72 cl::desc("Use new builder system."),
73 cl::init(true), cl::Hidden);
77 pbqpPreSplitting("pbqp-pre-splitting",
78 cl::desc("Pre-split before PBQP register allocation."),
79 cl::init(false), cl::Hidden);
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 {
92 /// Construct a PBQP register allocator.
93 RegAllocPBQP(std::auto_ptr<PBQPBuilder> b) : MachineFunctionPass(ID), builder(b) {}
95 /// Return the pass name.
96 virtual const char* getPassName() const {
97 return "PBQP Register Allocator";
100 /// PBQP analysis usage.
101 virtual void getAnalysisUsage(AnalysisUsage &au) const;
103 /// Perform register allocation
104 virtual bool runOnMachineFunction(MachineFunction &MF);
108 typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
109 typedef std::vector<const LiveInterval*> Node2LIMap;
110 typedef std::vector<unsigned> AllowedSet;
111 typedef std::vector<AllowedSet> AllowedSetMap;
112 typedef std::pair<unsigned, unsigned> RegPair;
113 typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
114 typedef std::vector<PBQP::Graph::NodeItr> NodeVector;
115 typedef std::set<unsigned> RegSet;
118 std::auto_ptr<PBQPBuilder> builder;
121 const TargetMachine *tm;
122 const TargetRegisterInfo *tri;
123 const TargetInstrInfo *tii;
124 const MachineLoopInfo *loopInfo;
125 MachineRegisterInfo *mri;
126 RenderMachineFunction *rmf;
134 AllowedSetMap allowedSets;
135 RegSet vregsToAlloc, emptyIntervalVRegs;
136 NodeVector problemNodes;
139 /// Builds a PBQP cost vector.
140 template <typename RegContainer>
141 PBQP::Vector buildCostVector(unsigned vReg,
142 const RegContainer &allowed,
143 const CoalesceMap &cealesces,
144 PBQP::PBQPNum spillCost) const;
146 /// \brief Builds a PBQP interference matrix.
148 /// @return Either a pointer to a non-zero PBQP matrix representing the
149 /// allocation option costs, or a null pointer for a zero matrix.
151 /// Expects allowed sets for two interfering LiveIntervals. These allowed
152 /// sets should contain only allocable registers from the LiveInterval's
153 /// register class, with any interfering pre-colored registers removed.
154 template <typename RegContainer>
155 PBQP::Matrix* buildInterferenceMatrix(const RegContainer &allowed1,
156 const RegContainer &allowed2) const;
159 /// Expects allowed sets for two potentially coalescable LiveIntervals,
160 /// and an estimated benefit due to coalescing. The allowed sets should
161 /// contain only allocable registers from the LiveInterval's register
162 /// classes, with any interfering pre-colored registers removed.
163 template <typename RegContainer>
164 PBQP::Matrix* buildCoalescingMatrix(const RegContainer &allowed1,
165 const RegContainer &allowed2,
166 PBQP::PBQPNum cBenefit) const;
168 /// \brief Finds coalescing opportunities and returns them as a map.
170 /// Any entries in the map are guaranteed coalescable, even if their
171 /// corresponding live intervals overlap.
172 CoalesceMap findCoalesces();
174 /// \brief Finds the initial set of vreg intervals to allocate.
175 void findVRegIntervalsToAlloc();
177 /// \brief Constructs a PBQP problem representation of the register
178 /// allocation problem for this function.
180 /// Old Construction Process - this functionality has been subsumed
181 /// by PBQPBuilder. This function will only be hanging around for a little
182 /// while until the new system has been fully tested.
184 /// @return a PBQP solver object for the register allocation problem.
185 PBQP::Graph constructPBQPProblemOld();
187 /// \brief Adds a stack interval if the given live interval has been
188 /// spilled. Used to support stack slot coloring.
189 void addStackInterval(const LiveInterval *spilled,MachineRegisterInfo* mri);
191 /// \brief Given a solved PBQP problem maps this solution back to a register
194 /// Old Construction Process - this functionality has been subsumed
195 /// by PBQPBuilder. This function will only be hanging around for a little
196 /// while until the new system has been fully tested.
198 bool mapPBQPToRegAllocOld(const PBQP::Solution &solution);
200 /// \brief Given a solved PBQP problem maps this solution back to a register
202 bool mapPBQPToRegAlloc(const PBQPRAProblem &problem,
203 const PBQP::Solution &solution);
205 /// \brief Postprocessing before final spilling. Sets basic block "live in"
207 void finalizeAlloc() const;
211 char RegAllocPBQP::ID = 0;
213 } // End anonymous namespace.
215 unsigned PBQPRAProblem::getVRegForNode(PBQP::Graph::ConstNodeItr node) const {
216 Node2VReg::const_iterator vregItr = node2VReg.find(node);
217 assert(vregItr != node2VReg.end() && "No vreg for node.");
218 return vregItr->second;
221 PBQP::Graph::NodeItr PBQPRAProblem::getNodeForVReg(unsigned vreg) const {
222 VReg2Node::const_iterator nodeItr = vreg2Node.find(vreg);
223 assert(nodeItr != vreg2Node.end() && "No node for vreg.");
224 return nodeItr->second;
228 const PBQPRAProblem::AllowedSet&
229 PBQPRAProblem::getAllowedSet(unsigned vreg) const {
230 AllowedSetMap::const_iterator allowedSetItr = allowedSets.find(vreg);
231 assert(allowedSetItr != allowedSets.end() && "No pregs for vreg.");
232 const AllowedSet &allowedSet = allowedSetItr->second;
236 unsigned PBQPRAProblem::getPRegForOption(unsigned vreg, unsigned option) const {
237 assert(isPRegOption(vreg, option) && "Not a preg option.");
239 const AllowedSet& allowedSet = getAllowedSet(vreg);
240 assert(option <= allowedSet.size() && "Option outside allowed set.");
241 return allowedSet[option - 1];
244 std::auto_ptr<PBQPRAProblem> PBQPBuilder::build(MachineFunction *mf,
245 const LiveIntervals *lis,
246 const MachineLoopInfo *loopInfo,
247 const RegSet &vregs) {
249 typedef std::vector<const LiveInterval*> LIVector;
251 MachineRegisterInfo *mri = &mf->getRegInfo();
252 const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();
254 std::auto_ptr<PBQPRAProblem> p(new PBQPRAProblem());
255 PBQP::Graph &g = p->getGraph();
258 // Collect the set of preg intervals, record that they're used in the MF.
259 for (LiveIntervals::const_iterator itr = lis->begin(), end = lis->end();
261 if (TargetRegisterInfo::isPhysicalRegister(itr->first)) {
262 pregs.insert(itr->first);
263 mri->setPhysRegUsed(itr->first);
267 BitVector reservedRegs = tri->getReservedRegs(*mf);
269 // Iterate over vregs.
270 for (RegSet::const_iterator vregItr = vregs.begin(), vregEnd = vregs.end();
271 vregItr != vregEnd; ++vregItr) {
272 unsigned vreg = *vregItr;
273 const TargetRegisterClass *trc = mri->getRegClass(vreg);
274 const LiveInterval *vregLI = &lis->getInterval(vreg);
276 // Compute an initial allowed set for the current vreg.
277 typedef std::vector<unsigned> VRAllowed;
279 for (TargetRegisterClass::iterator aoItr = trc->allocation_order_begin(*mf),
280 aoEnd = trc->allocation_order_end(*mf);
281 aoItr != aoEnd; ++aoItr) {
282 unsigned preg = *aoItr;
283 if (!reservedRegs.test(preg)) {
284 vrAllowed.push_back(preg);
288 // Remove any physical registers which overlap.
289 for (RegSet::const_iterator pregItr = pregs.begin(),
290 pregEnd = pregs.end();
291 pregItr != pregEnd; ++pregItr) {
292 unsigned preg = *pregItr;
293 const LiveInterval *pregLI = &lis->getInterval(preg);
298 if (!vregLI->overlaps(*pregLI))
301 // Remove the register from the allowed set.
302 VRAllowed::iterator eraseItr =
303 std::find(vrAllowed.begin(), vrAllowed.end(), preg);
305 if (eraseItr != vrAllowed.end()) {
306 vrAllowed.erase(eraseItr);
309 // Also remove any aliases.
310 const unsigned *aliasItr = tri->getAliasSet(preg);
312 for (; *aliasItr != 0; ++aliasItr) {
313 VRAllowed::iterator eraseItr =
314 std::find(vrAllowed.begin(), vrAllowed.end(), *aliasItr);
316 if (eraseItr != vrAllowed.end()) {
317 vrAllowed.erase(eraseItr);
323 // Construct the node.
324 PBQP::Graph::NodeItr node =
325 g.addNode(PBQP::Vector(vrAllowed.size() + 1, 0));
327 // Record the mapping and allowed set in the problem.
328 p->recordVReg(vreg, node, vrAllowed.begin(), vrAllowed.end());
330 PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
331 vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
333 addSpillCosts(g.getNodeCosts(node), spillCost);
336 for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
337 vr1Itr != vrEnd; ++vr1Itr) {
338 unsigned vr1 = *vr1Itr;
339 const LiveInterval &l1 = lis->getInterval(vr1);
340 const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
342 for (RegSet::const_iterator vr2Itr = llvm::next(vr1Itr);
343 vr2Itr != vrEnd; ++vr2Itr) {
344 unsigned vr2 = *vr2Itr;
345 const LiveInterval &l2 = lis->getInterval(vr2);
346 const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
348 assert(!l2.empty() && "Empty interval in vreg set?");
349 if (l1.overlaps(l2)) {
350 PBQP::Graph::EdgeItr edge =
351 g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
352 PBQP::Matrix(vr1Allowed.size()+1, vr2Allowed.size()+1, 0));
354 addInterferenceCosts(g.getEdgeCosts(edge), vr1Allowed, vr2Allowed, tri);
362 void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
363 PBQP::PBQPNum spillCost) {
364 costVec[0] = spillCost;
367 void PBQPBuilder::addInterferenceCosts(
368 PBQP::Matrix &costMat,
369 const PBQPRAProblem::AllowedSet &vr1Allowed,
370 const PBQPRAProblem::AllowedSet &vr2Allowed,
371 const TargetRegisterInfo *tri) {
372 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
373 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
375 for (unsigned i = 0; i < vr1Allowed.size(); ++i) {
376 unsigned preg1 = vr1Allowed[i];
378 for (unsigned j = 0; j < vr2Allowed.size(); ++j) {
379 unsigned preg2 = vr2Allowed[j];
381 if (tri->regsOverlap(preg1, preg2)) {
382 costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
388 std::auto_ptr<PBQPRAProblem> PBQPBuilderWithCoalescing::build(
390 const LiveIntervals *lis,
391 const MachineLoopInfo *loopInfo,
392 const RegSet &vregs) {
394 std::auto_ptr<PBQPRAProblem> p = PBQPBuilder::build(mf, lis, loopInfo, vregs);
395 PBQP::Graph &g = p->getGraph();
397 const TargetMachine &tm = mf->getTarget();
398 CoalescerPair cp(*tm.getInstrInfo(), *tm.getRegisterInfo());
400 // Scan the machine function and add a coalescing cost whenever CoalescerPair
402 for (MachineFunction::const_iterator mbbItr = mf->begin(),
404 mbbItr != mbbEnd; ++mbbItr) {
405 const MachineBasicBlock *mbb = &*mbbItr;
407 for (MachineBasicBlock::const_iterator miItr = mbb->begin(),
409 miItr != miEnd; ++miItr) {
410 const MachineInstr *mi = &*miItr;
412 if (!cp.setRegisters(mi))
413 continue; // Not coalescable.
415 if (cp.getSrcReg() == cp.getDstReg())
416 continue; // Already coalesced.
418 unsigned dst = cp.getDstReg(),
419 src = cp.getSrcReg();
421 const float copyFactor = 0.5; // Cost of copy relative to load. Current
422 // value plucked randomly out of the air.
424 PBQP::PBQPNum cBenefit =
425 copyFactor * LiveIntervals::getSpillWeight(false, true,
426 loopInfo->getLoopDepth(mbb));
429 if (!lis->isAllocatable(dst))
432 const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
433 unsigned pregOpt = 0;
434 while (pregOpt < allowed.size() && allowed[pregOpt] != dst)
436 if (pregOpt < allowed.size()) {
437 ++pregOpt; // +1 to account for spill option.
438 PBQP::Graph::NodeItr node = p->getNodeForVReg(src);
439 addPhysRegCoalesce(g.getNodeCosts(node), pregOpt, cBenefit);
442 const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
443 const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
444 PBQP::Graph::NodeItr node1 = p->getNodeForVReg(dst);
445 PBQP::Graph::NodeItr node2 = p->getNodeForVReg(src);
446 PBQP::Graph::EdgeItr edge = g.findEdge(node1, node2);
447 if (edge == g.edgesEnd()) {
448 edge = g.addEdge(node1, node2, PBQP::Matrix(allowed1->size() + 1,
449 allowed2->size() + 1,
452 if (g.getEdgeNode1(edge) == node2) {
453 std::swap(node1, node2);
454 std::swap(allowed1, allowed2);
458 addVirtRegCoalesce(g.getEdgeCosts(edge), *allowed1, *allowed2,
467 void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
469 PBQP::PBQPNum benefit) {
470 costVec[pregOption] += -benefit;
473 void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
474 PBQP::Matrix &costMat,
475 const PBQPRAProblem::AllowedSet &vr1Allowed,
476 const PBQPRAProblem::AllowedSet &vr2Allowed,
477 PBQP::PBQPNum benefit) {
479 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
480 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
482 for (unsigned i = 0; i < vr1Allowed.size(); ++i) {
483 unsigned preg1 = vr1Allowed[i];
484 for (unsigned j = 0; j < vr2Allowed.size(); ++j) {
485 unsigned preg2 = vr2Allowed[j];
487 if (preg1 == preg2) {
488 costMat[i + 1][j + 1] += -benefit;
495 void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
496 au.addRequired<SlotIndexes>();
497 au.addPreserved<SlotIndexes>();
498 au.addRequired<LiveIntervals>();
499 //au.addRequiredID(SplitCriticalEdgesID);
500 au.addRequired<RegisterCoalescer>();
501 au.addRequired<CalculateSpillWeights>();
502 au.addRequired<LiveStacks>();
503 au.addPreserved<LiveStacks>();
504 au.addRequired<MachineLoopInfo>();
505 au.addPreserved<MachineLoopInfo>();
506 if (pbqpPreSplitting)
507 au.addRequired<LoopSplitter>();
508 au.addRequired<VirtRegMap>();
509 au.addRequired<RenderMachineFunction>();
510 MachineFunctionPass::getAnalysisUsage(au);
513 template <typename RegContainer>
514 PBQP::Vector RegAllocPBQP::buildCostVector(unsigned vReg,
515 const RegContainer &allowed,
516 const CoalesceMap &coalesces,
517 PBQP::PBQPNum spillCost) const {
519 typedef typename RegContainer::const_iterator AllowedItr;
521 // Allocate vector. Additional element (0th) used for spill option
522 PBQP::Vector v(allowed.size() + 1, 0);
526 // Iterate over the allowed registers inserting coalesce benefits if there
529 for (AllowedItr itr = allowed.begin(), end = allowed.end();
530 itr != end; ++itr, ++ai) {
532 unsigned pReg = *itr;
534 CoalesceMap::const_iterator cmItr =
535 coalesces.find(RegPair(vReg, pReg));
537 // No coalesce - on to the next preg.
538 if (cmItr == coalesces.end())
541 // We have a coalesce - insert the benefit.
542 v[ai + 1] = -cmItr->second;
548 template <typename RegContainer>
549 PBQP::Matrix* RegAllocPBQP::buildInterferenceMatrix(
550 const RegContainer &allowed1, const RegContainer &allowed2) const {
552 typedef typename RegContainer::const_iterator RegContainerIterator;
554 // Construct a PBQP matrix representing the cost of allocation options. The
555 // rows and columns correspond to the allocation options for the two live
556 // intervals. Elements will be infinite where corresponding registers alias,
557 // since we cannot allocate aliasing registers to interfering live intervals.
558 // All other elements (non-aliasing combinations) will have zero cost. Note
559 // that the spill option (element 0,0) has zero cost, since we can allocate
560 // both intervals to memory safely (the cost for each individual allocation
561 // to memory is accounted for by the cost vectors for each live interval).
563 new PBQP::Matrix(allowed1.size() + 1, allowed2.size() + 1, 0);
565 // Assume this is a zero matrix until proven otherwise. Zero matrices occur
566 // between interfering live ranges with non-overlapping register sets (e.g.
567 // non-overlapping reg classes, or disjoint sets of allowed regs within the
568 // same class). The term "overlapping" is used advisedly: sets which do not
569 // intersect, but contain registers which alias, will have non-zero matrices.
570 // We optimize zero matrices away to improve solver speed.
571 bool isZeroMatrix = true;
574 // Row index. Starts at 1, since the 0th row is for the spill option, which
578 // Iterate over allowed sets, insert infinities where required.
579 for (RegContainerIterator a1Itr = allowed1.begin(), a1End = allowed1.end();
580 a1Itr != a1End; ++a1Itr) {
582 // Column index, starts at 1 as for row index.
584 unsigned reg1 = *a1Itr;
586 for (RegContainerIterator a2Itr = allowed2.begin(), a2End = allowed2.end();
587 a2Itr != a2End; ++a2Itr) {
589 unsigned reg2 = *a2Itr;
591 // If the row/column regs are identical or alias insert an infinity.
592 if (tri->regsOverlap(reg1, reg2)) {
593 (*m)[ri][ci] = std::numeric_limits<PBQP::PBQPNum>::infinity();
594 isZeroMatrix = false;
603 // If this turns out to be a zero matrix...
605 // free it and return null.
610 // ...otherwise return the cost matrix.
614 template <typename RegContainer>
615 PBQP::Matrix* RegAllocPBQP::buildCoalescingMatrix(
616 const RegContainer &allowed1, const RegContainer &allowed2,
617 PBQP::PBQPNum cBenefit) const {
619 typedef typename RegContainer::const_iterator RegContainerIterator;
621 // Construct a PBQP Matrix representing the benefits of coalescing. As with
622 // interference matrices the rows and columns represent allowed registers
623 // for the LiveIntervals which are (potentially) to be coalesced. The amount
624 // -cBenefit will be placed in any element representing the same register
625 // for both intervals.
627 new PBQP::Matrix(allowed1.size() + 1, allowed2.size() + 1, 0);
629 // Reset costs to zero.
632 // Assume the matrix is zero till proven otherwise. Zero matrices will be
633 // optimized away as in the interference case.
634 bool isZeroMatrix = true;
636 // Row index. Starts at 1, since the 0th row is for the spill option, which
640 // Iterate over the allowed sets, insert coalescing benefits where
642 for (RegContainerIterator a1Itr = allowed1.begin(), a1End = allowed1.end();
643 a1Itr != a1End; ++a1Itr) {
645 // Column index, starts at 1 as for row index.
647 unsigned reg1 = *a1Itr;
649 for (RegContainerIterator a2Itr = allowed2.begin(), a2End = allowed2.end();
650 a2Itr != a2End; ++a2Itr) {
652 // If the row and column represent the same register insert a beneficial
653 // cost to preference this allocation - it would allow us to eliminate a
655 if (reg1 == *a2Itr) {
656 (*m)[ri][ci] = -cBenefit;
657 isZeroMatrix = false;
666 // If this turns out to be a zero matrix...
668 // ...free it and return null.
676 RegAllocPBQP::CoalesceMap RegAllocPBQP::findCoalesces() {
678 typedef MachineFunction::const_iterator MFIterator;
679 typedef MachineBasicBlock::const_iterator MBBIterator;
680 typedef LiveInterval::const_vni_iterator VNIIterator;
682 CoalesceMap coalescesFound;
684 // To find coalesces we need to iterate over the function looking for
685 // copy instructions.
686 for (MFIterator bbItr = mf->begin(), bbEnd = mf->end();
687 bbItr != bbEnd; ++bbItr) {
689 const MachineBasicBlock *mbb = &*bbItr;
691 for (MBBIterator iItr = mbb->begin(), iEnd = mbb->end();
692 iItr != iEnd; ++iItr) {
694 const MachineInstr *instr = &*iItr;
696 // If this isn't a copy then continue to the next instruction.
697 if (!instr->isCopy())
700 unsigned srcReg = instr->getOperand(1).getReg();
701 unsigned dstReg = instr->getOperand(0).getReg();
703 // If the registers are already the same our job is nice and easy.
704 if (dstReg == srcReg)
707 bool srcRegIsPhysical = TargetRegisterInfo::isPhysicalRegister(srcReg),
708 dstRegIsPhysical = TargetRegisterInfo::isPhysicalRegister(dstReg);
710 // If both registers are physical then we can't coalesce.
711 if (srcRegIsPhysical && dstRegIsPhysical)
714 // If it's a copy that includes two virtual register but the source and
715 // destination classes differ then we can't coalesce.
716 if (!srcRegIsPhysical && !dstRegIsPhysical &&
717 mri->getRegClass(srcReg) != mri->getRegClass(dstReg))
720 // If one is physical and one is virtual, check that the physical is
721 // allocatable in the class of the virtual.
722 if (srcRegIsPhysical && !dstRegIsPhysical) {
723 const TargetRegisterClass *dstRegClass = mri->getRegClass(dstReg);
724 if (std::find(dstRegClass->allocation_order_begin(*mf),
725 dstRegClass->allocation_order_end(*mf), srcReg) ==
726 dstRegClass->allocation_order_end(*mf))
729 if (!srcRegIsPhysical && dstRegIsPhysical) {
730 const TargetRegisterClass *srcRegClass = mri->getRegClass(srcReg);
731 if (std::find(srcRegClass->allocation_order_begin(*mf),
732 srcRegClass->allocation_order_end(*mf), dstReg) ==
733 srcRegClass->allocation_order_end(*mf))
737 // If we've made it here we have a copy with compatible register classes.
738 // We can probably coalesce, but we need to consider overlap.
739 const LiveInterval *srcLI = &lis->getInterval(srcReg),
740 *dstLI = &lis->getInterval(dstReg);
742 if (srcLI->overlaps(*dstLI)) {
743 // Even in the case of an overlap we might still be able to coalesce,
744 // but we need to make sure that no definition of either range occurs
745 // while the other range is live.
747 // Otherwise start by assuming we're ok.
750 // Test all defs of the source range.
752 vniItr = srcLI->vni_begin(), vniEnd = srcLI->vni_end();
753 vniItr != vniEnd; ++vniItr) {
755 // If we find a poorly defined def we err on the side of caution.
756 if (!(*vniItr)->def.isValid()) {
761 // If we find a def that kills the coalescing opportunity then
762 // record it and break from the loop.
763 if (dstLI->liveAt((*vniItr)->def)) {
769 // If we have a bad def give up, continue to the next instruction.
773 // Otherwise test definitions of the destination range.
775 vniItr = dstLI->vni_begin(), vniEnd = dstLI->vni_end();
776 vniItr != vniEnd; ++vniItr) {
778 // We want to make sure we skip the copy instruction itself.
779 if ((*vniItr)->getCopy() == instr)
782 if (!(*vniItr)->def.isValid()) {
787 if (srcLI->liveAt((*vniItr)->def)) {
793 // As before a bad def we give up and continue to the next instr.
798 // If we make it to here then either the ranges didn't overlap, or they
799 // did, but none of their definitions would prevent us from coalescing.
800 // We're good to go with the coalesce.
802 float cBenefit = std::pow(10.0f, (float)loopInfo->getLoopDepth(mbb)) / 5.0;
804 coalescesFound[RegPair(srcReg, dstReg)] = cBenefit;
805 coalescesFound[RegPair(dstReg, srcReg)] = cBenefit;
810 return coalescesFound;
813 void RegAllocPBQP::findVRegIntervalsToAlloc() {
815 // Iterate over all live ranges.
816 for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
819 // Ignore physical ones.
820 if (TargetRegisterInfo::isPhysicalRegister(itr->first))
823 LiveInterval *li = itr->second;
825 // If this live interval is non-empty we will use pbqp to allocate it.
826 // Empty intervals we allocate in a simple post-processing stage in
829 vregsToAlloc.insert(li->reg);
832 emptyIntervalVRegs.insert(li->reg);
837 PBQP::Graph RegAllocPBQP::constructPBQPProblemOld() {
839 typedef std::vector<const LiveInterval*> LIVector;
840 typedef std::vector<unsigned> RegVector;
842 // This will store the physical intervals for easy reference.
843 LIVector physIntervals;
845 // Start by clearing the old node <-> live interval mappings & allowed sets
850 // Populate physIntervals, update preg use:
851 for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
854 if (TargetRegisterInfo::isPhysicalRegister(itr->first)) {
855 physIntervals.push_back(itr->second);
856 mri->setPhysRegUsed(itr->second->reg);
860 // Iterate over vreg intervals, construct live interval <-> node number
862 for (RegSet::const_iterator itr = vregsToAlloc.begin(),
863 end = vregsToAlloc.end();
865 const LiveInterval *li = &lis->getInterval(*itr);
867 li2Node[li] = node2LI.size();
868 node2LI.push_back(li);
871 // Get the set of potential coalesces.
872 CoalesceMap coalesces;
874 if (pbqpCoalescing) {
875 coalesces = findCoalesces();
878 // Construct a PBQP solver for this problem
880 problemNodes.resize(vregsToAlloc.size());
882 // Resize allowedSets container appropriately.
883 allowedSets.resize(vregsToAlloc.size());
885 BitVector ReservedRegs = tri->getReservedRegs(*mf);
887 // Iterate over virtual register intervals to compute allowed sets...
888 for (unsigned node = 0; node < node2LI.size(); ++node) {
890 // Grab pointers to the interval and its register class.
891 const LiveInterval *li = node2LI[node];
892 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
894 // Start by assuming all allocable registers in the class are allowed...
896 TargetRegisterClass::iterator aob = liRC->allocation_order_begin(*mf);
897 TargetRegisterClass::iterator aoe = liRC->allocation_order_end(*mf);
898 for (TargetRegisterClass::iterator it = aob; it != aoe; ++it)
899 if (!ReservedRegs.test(*it))
900 liAllowed.push_back(*it);
902 // Eliminate the physical registers which overlap with this range, along
903 // with all their aliases.
904 for (LIVector::iterator pItr = physIntervals.begin(),
905 pEnd = physIntervals.end(); pItr != pEnd; ++pItr) {
907 if (!li->overlaps(**pItr))
910 unsigned pReg = (*pItr)->reg;
912 // If we get here then the live intervals overlap, but we're still ok
913 // if they're coalescable.
914 if (coalesces.find(RegPair(li->reg, pReg)) != coalesces.end()) {
915 DEBUG(dbgs() << "CoalescingOverride: (" << li->reg << ", " << pReg << ")\n");
919 // If we get here then we have a genuine exclusion.
921 // Remove the overlapping reg...
922 RegVector::iterator eraseItr =
923 std::find(liAllowed.begin(), liAllowed.end(), pReg);
925 if (eraseItr != liAllowed.end())
926 liAllowed.erase(eraseItr);
928 const unsigned *aliasItr = tri->getAliasSet(pReg);
931 // ...and its aliases.
932 for (; *aliasItr != 0; ++aliasItr) {
933 RegVector::iterator eraseItr =
934 std::find(liAllowed.begin(), liAllowed.end(), *aliasItr);
936 if (eraseItr != liAllowed.end()) {
937 liAllowed.erase(eraseItr);
943 // Copy the allowed set into a member vector for use when constructing cost
944 // vectors & matrices, and mapping PBQP solutions back to assignments.
945 allowedSets[node] = AllowedSet(liAllowed.begin(), liAllowed.end());
947 // Set the spill cost to the interval weight, or epsilon if the
948 // interval weight is zero
949 PBQP::PBQPNum spillCost = (li->weight != 0.0) ?
950 li->weight : std::numeric_limits<PBQP::PBQPNum>::min();
952 // Build a cost vector for this interval.
955 buildCostVector(li->reg, allowedSets[node], coalesces, spillCost));
960 // Now add the cost matrices...
961 for (unsigned node1 = 0; node1 < node2LI.size(); ++node1) {
962 const LiveInterval *li = node2LI[node1];
964 // Test for live range overlaps and insert interference matrices.
965 for (unsigned node2 = node1 + 1; node2 < node2LI.size(); ++node2) {
966 const LiveInterval *li2 = node2LI[node2];
968 CoalesceMap::const_iterator cmItr =
969 coalesces.find(RegPair(li->reg, li2->reg));
973 if (cmItr != coalesces.end()) {
974 m = buildCoalescingMatrix(allowedSets[node1], allowedSets[node2],
977 else if (li->overlaps(*li2)) {
978 m = buildInterferenceMatrix(allowedSets[node1], allowedSets[node2]);
982 problem.addEdge(problemNodes[node1],
991 assert(problem.getNumNodes() == allowedSets.size());
993 std::cerr << "Allocating for " << problem.getNumNodes() << " nodes, "
994 << problem.getNumEdges() << " edges.\n";
996 problem.printDot(std::cerr);
998 // We're done, PBQP problem constructed - return it.
1002 void RegAllocPBQP::addStackInterval(const LiveInterval *spilled,
1003 MachineRegisterInfo* mri) {
1004 int stackSlot = vrm->getStackSlot(spilled->reg);
1006 if (stackSlot == VirtRegMap::NO_STACK_SLOT)
1009 const TargetRegisterClass *RC = mri->getRegClass(spilled->reg);
1010 LiveInterval &stackInterval = lss->getOrCreateInterval(stackSlot, RC);
1013 if (stackInterval.getNumValNums() != 0)
1014 vni = stackInterval.getValNumInfo(0);
1016 vni = stackInterval.getNextValue(
1017 SlotIndex(), 0, lss->getVNInfoAllocator());
1019 LiveInterval &rhsInterval = lis->getInterval(spilled->reg);
1020 stackInterval.MergeRangesInAsValue(rhsInterval, vni);
1023 bool RegAllocPBQP::mapPBQPToRegAllocOld(const PBQP::Solution &solution) {
1025 // Set to true if we have any spills
1026 bool anotherRoundNeeded = false;
1028 // Clear the existing allocation.
1029 vrm->clearAllVirt();
1031 // Iterate over the nodes mapping the PBQP solution to a register assignment.
1032 for (unsigned node = 0; node < node2LI.size(); ++node) {
1033 unsigned virtReg = node2LI[node]->reg,
1034 allocSelection = solution.getSelection(problemNodes[node]);
1037 // If the PBQP solution is non-zero it's a physical register...
1038 if (allocSelection != 0) {
1039 // Get the physical reg, subtracting 1 to account for the spill option.
1040 unsigned physReg = allowedSets[node][allocSelection - 1];
1042 DEBUG(dbgs() << "VREG " << virtReg << " -> "
1043 << tri->getName(physReg) << " (Option: " << allocSelection << ")\n");
1045 assert(physReg != 0);
1047 // Add to the virt reg map and update the used phys regs.
1048 vrm->assignVirt2Phys(virtReg, physReg);
1050 // ...Otherwise it's a spill.
1053 // Make sure we ignore this virtual reg on the next round
1055 vregsToAlloc.erase(virtReg);
1057 // Insert spill ranges for this live range
1058 const LiveInterval *spillInterval = node2LI[node];
1059 double oldSpillWeight = spillInterval->weight;
1060 SmallVector<LiveInterval*, 8> spillIs;
1061 rmf->rememberUseDefs(spillInterval);
1062 std::vector<LiveInterval*> newSpills =
1063 lis->addIntervalsForSpills(*spillInterval, spillIs, loopInfo, *vrm);
1064 addStackInterval(spillInterval, mri);
1065 rmf->rememberSpills(spillInterval, newSpills);
1067 (void) oldSpillWeight;
1068 DEBUG(dbgs() << "VREG " << virtReg << " -> SPILLED (Option: 0, Cost: "
1069 << oldSpillWeight << ", New vregs: ");
1071 // Copy any newly inserted live intervals into the list of regs to
1073 for (std::vector<LiveInterval*>::const_iterator
1074 itr = newSpills.begin(), end = newSpills.end();
1075 itr != end; ++itr) {
1077 assert(!(*itr)->empty() && "Empty spill range.");
1079 DEBUG(dbgs() << (*itr)->reg << " ");
1081 vregsToAlloc.insert((*itr)->reg);
1084 DEBUG(dbgs() << ")\n");
1086 // We need another round if spill intervals were added.
1087 anotherRoundNeeded |= !newSpills.empty();
1091 return !anotherRoundNeeded;
1094 bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
1095 const PBQP::Solution &solution) {
1096 // Set to true if we have any spills
1097 bool anotherRoundNeeded = false;
1099 // Clear the existing allocation.
1100 vrm->clearAllVirt();
1102 const PBQP::Graph &g = problem.getGraph();
1103 // Iterate over the nodes mapping the PBQP solution to a register
1105 for (PBQP::Graph::ConstNodeItr node = g.nodesBegin(),
1106 nodeEnd = g.nodesEnd();
1107 node != nodeEnd; ++node) {
1108 unsigned vreg = problem.getVRegForNode(node);
1109 unsigned alloc = solution.getSelection(node);
1111 if (problem.isPRegOption(vreg, alloc)) {
1112 unsigned preg = problem.getPRegForOption(vreg, alloc);
1113 DEBUG(dbgs() << "VREG " << vreg << " -> " << tri->getName(preg) << "\n");
1114 assert(preg != 0 && "Invalid preg selected.");
1115 vrm->assignVirt2Phys(vreg, preg);
1116 } else if (problem.isSpillOption(vreg, alloc)) {
1117 vregsToAlloc.erase(vreg);
1118 const LiveInterval* spillInterval = &lis->getInterval(vreg);
1119 double oldWeight = spillInterval->weight;
1120 SmallVector<LiveInterval*, 8> spillIs;
1121 rmf->rememberUseDefs(spillInterval);
1122 std::vector<LiveInterval*> newSpills =
1123 lis->addIntervalsForSpills(*spillInterval, spillIs, loopInfo, *vrm);
1124 addStackInterval(spillInterval, mri);
1125 rmf->rememberSpills(spillInterval, newSpills);
1128 DEBUG(dbgs() << "VREG " << vreg << " -> SPILLED (Cost: "
1129 << oldWeight << ", New vregs: ");
1131 // Copy any newly inserted live intervals into the list of regs to
1133 for (std::vector<LiveInterval*>::const_iterator
1134 itr = newSpills.begin(), end = newSpills.end();
1135 itr != end; ++itr) {
1136 assert(!(*itr)->empty() && "Empty spill range.");
1137 DEBUG(dbgs() << (*itr)->reg << " ");
1138 vregsToAlloc.insert((*itr)->reg);
1141 DEBUG(dbgs() << ")\n");
1143 // We need another round if spill intervals were added.
1144 anotherRoundNeeded |= !newSpills.empty();
1146 assert(false && "Unknown allocation option.");
1150 return !anotherRoundNeeded;
1154 void RegAllocPBQP::finalizeAlloc() const {
1155 typedef LiveIntervals::iterator LIIterator;
1156 typedef LiveInterval::Ranges::const_iterator LRIterator;
1158 // First allocate registers for the empty intervals.
1159 for (RegSet::const_iterator
1160 itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
1161 itr != end; ++itr) {
1162 LiveInterval *li = &lis->getInterval(*itr);
1164 unsigned physReg = vrm->getRegAllocPref(li->reg);
1167 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
1168 physReg = *liRC->allocation_order_begin(*mf);
1171 vrm->assignVirt2Phys(li->reg, physReg);
1174 // Finally iterate over the basic blocks to compute and set the live-in sets.
1175 SmallVector<MachineBasicBlock*, 8> liveInMBBs;
1176 MachineBasicBlock *entryMBB = &*mf->begin();
1178 for (LIIterator liItr = lis->begin(), liEnd = lis->end();
1179 liItr != liEnd; ++liItr) {
1181 const LiveInterval *li = liItr->second;
1184 // Get the physical register for this interval
1185 if (TargetRegisterInfo::isPhysicalRegister(li->reg)) {
1188 else if (vrm->isAssignedReg(li->reg)) {
1189 reg = vrm->getPhys(li->reg);
1192 // Ranges which are assigned a stack slot only are ignored.
1197 // Filter out zero regs - they're for intervals that were spilled.
1201 // Iterate over the ranges of the current interval...
1202 for (LRIterator lrItr = li->begin(), lrEnd = li->end();
1203 lrItr != lrEnd; ++lrItr) {
1205 // Find the set of basic blocks which this range is live into...
1206 if (lis->findLiveInMBBs(lrItr->start, lrItr->end, liveInMBBs)) {
1207 // And add the physreg for this interval to their live-in sets.
1208 for (unsigned i = 0; i < liveInMBBs.size(); ++i) {
1209 if (liveInMBBs[i] != entryMBB) {
1210 if (!liveInMBBs[i]->isLiveIn(reg)) {
1211 liveInMBBs[i]->addLiveIn(reg);
1222 bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
1225 tm = &mf->getTarget();
1226 tri = tm->getRegisterInfo();
1227 tii = tm->getInstrInfo();
1228 mri = &mf->getRegInfo();
1230 lis = &getAnalysis<LiveIntervals>();
1231 lss = &getAnalysis<LiveStacks>();
1232 loopInfo = &getAnalysis<MachineLoopInfo>();
1233 rmf = &getAnalysis<RenderMachineFunction>();
1235 vrm = &getAnalysis<VirtRegMap>();
1238 DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getFunction()->getName() << "\n");
1240 // Allocator main loop:
1242 // * Map current regalloc problem to a PBQP problem
1243 // * Solve the PBQP problem
1244 // * Map the solution back to a register allocation
1245 // * Spill if necessary
1247 // This process is continued till no more spills are generated.
1249 // Find the vreg intervals in need of allocation.
1250 findVRegIntervalsToAlloc();
1252 // If there are non-empty intervals allocate them using pbqp.
1253 if (!vregsToAlloc.empty()) {
1255 bool pbqpAllocComplete = false;
1259 while (!pbqpAllocComplete) {
1260 DEBUG(dbgs() << " PBQP Regalloc round " << round << ":\n");
1262 PBQP::Graph problem = constructPBQPProblemOld();
1263 PBQP::Solution solution =
1264 PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(problem);
1266 pbqpAllocComplete = mapPBQPToRegAllocOld(solution);
1271 while (!pbqpAllocComplete) {
1272 DEBUG(dbgs() << " PBQP Regalloc round " << round << ":\n");
1274 std::auto_ptr<PBQPRAProblem> problem =
1275 builder->build(mf, lis, loopInfo, vregsToAlloc);
1276 PBQP::Solution solution =
1277 PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(
1278 problem->getGraph());
1280 pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
1287 // Finalise allocation, allocate empty ranges.
1290 rmf->renderMachineFunction("After PBQP register allocation.", vrm);
1292 vregsToAlloc.clear();
1293 emptyIntervalVRegs.clear();
1296 allowedSets.clear();
1297 problemNodes.clear();
1299 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
1302 std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
1304 rewriter->runOnMachineFunction(*mf, *vrm, lis);
1309 FunctionPass* llvm::createPBQPRegisterAllocator(
1310 std::auto_ptr<PBQPBuilder> builder) {
1311 return new RegAllocPBQP(builder);
1314 FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
1315 if (pbqpCoalescing) {
1316 return createPBQPRegisterAllocator(
1317 std::auto_ptr<PBQPBuilder>(new PBQPBuilderWithCoalescing()));
1319 return createPBQPRegisterAllocator(
1320 std::auto_ptr<PBQPBuilder>(new PBQPBuilder()));