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 "llvm/CodeGen/RegAllocPBQP.h"
35 #include "RegisterCoalescer.h"
37 #include "llvm/ADT/OwningPtr.h"
38 #include "llvm/Analysis/AliasAnalysis.h"
39 #include "llvm/CodeGen/CalcSpillWeights.h"
40 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
41 #include "llvm/CodeGen/LiveRangeEdit.h"
42 #include "llvm/CodeGen/LiveStackAnalysis.h"
43 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
44 #include "llvm/CodeGen/MachineDominators.h"
45 #include "llvm/CodeGen/MachineFunctionPass.h"
46 #include "llvm/CodeGen/MachineLoopInfo.h"
47 #include "llvm/CodeGen/MachineRegisterInfo.h"
48 #include "llvm/CodeGen/PBQP/Graph.h"
49 #include "llvm/CodeGen/PBQP/HeuristicSolver.h"
50 #include "llvm/CodeGen/PBQP/Heuristics/Briggs.h"
51 #include "llvm/CodeGen/RegAllocRegistry.h"
52 #include "llvm/CodeGen/VirtRegMap.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Target/TargetInstrInfo.h"
57 #include "llvm/Target/TargetMachine.h"
66 static RegisterRegAlloc
67 registerPBQPRepAlloc("pbqp", "PBQP register allocator",
68 createDefaultPBQPRegisterAllocator);
71 pbqpCoalescing("pbqp-coalescing",
72 cl::desc("Attempt coalescing during PBQP register allocation."),
73 cl::init(false), cl::Hidden);
77 pbqpDumpGraphs("pbqp-dump-graphs",
78 cl::desc("Dump graphs for each function/round in the compilation unit."),
79 cl::init(false), cl::Hidden);
85 /// PBQP based allocators solve the register allocation problem by mapping
86 /// register allocation problems to Partitioned Boolean Quadratic
87 /// Programming problems.
88 class RegAllocPBQP : public MachineFunctionPass {
93 /// Construct a PBQP register allocator.
94 RegAllocPBQP(OwningPtr<PBQPBuilder> &b, char *cPassID=0)
95 : MachineFunctionPass(ID), builder(b.take()), customPassID(cPassID) {
96 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
97 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
98 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
99 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
102 /// Return the pass name.
103 virtual const char* getPassName() const {
104 return "PBQP Register Allocator";
107 /// PBQP analysis usage.
108 virtual void getAnalysisUsage(AnalysisUsage &au) const;
110 /// Perform register allocation
111 virtual bool runOnMachineFunction(MachineFunction &MF);
115 typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
116 typedef std::vector<const LiveInterval*> Node2LIMap;
117 typedef std::vector<unsigned> AllowedSet;
118 typedef std::vector<AllowedSet> AllowedSetMap;
119 typedef std::pair<unsigned, unsigned> RegPair;
120 typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
121 typedef std::set<unsigned> RegSet;
124 OwningPtr<PBQPBuilder> builder;
129 const TargetMachine *tm;
130 const TargetRegisterInfo *tri;
131 const TargetInstrInfo *tii;
132 MachineRegisterInfo *mri;
133 const MachineBlockFrequencyInfo *mbfi;
135 OwningPtr<Spiller> spiller;
140 RegSet vregsToAlloc, emptyIntervalVRegs;
142 /// \brief Finds the initial set of vreg intervals to allocate.
143 void findVRegIntervalsToAlloc();
145 /// \brief Given a solved PBQP problem maps this solution back to a register
147 bool mapPBQPToRegAlloc(const PBQPRAProblem &problem,
148 const PBQP::Solution &solution);
150 /// \brief Postprocessing before final spilling. Sets basic block "live in"
152 void finalizeAlloc() const;
156 char RegAllocPBQP::ID = 0;
158 } // End anonymous namespace.
160 unsigned PBQPRAProblem::getVRegForNode(PBQP::Graph::NodeId node) const {
161 Node2VReg::const_iterator vregItr = node2VReg.find(node);
162 assert(vregItr != node2VReg.end() && "No vreg for node.");
163 return vregItr->second;
166 PBQP::Graph::NodeId PBQPRAProblem::getNodeForVReg(unsigned vreg) const {
167 VReg2Node::const_iterator nodeItr = vreg2Node.find(vreg);
168 assert(nodeItr != vreg2Node.end() && "No node for vreg.");
169 return nodeItr->second;
173 const PBQPRAProblem::AllowedSet&
174 PBQPRAProblem::getAllowedSet(unsigned vreg) const {
175 AllowedSetMap::const_iterator allowedSetItr = allowedSets.find(vreg);
176 assert(allowedSetItr != allowedSets.end() && "No pregs for vreg.");
177 const AllowedSet &allowedSet = allowedSetItr->second;
181 unsigned PBQPRAProblem::getPRegForOption(unsigned vreg, unsigned option) const {
182 assert(isPRegOption(vreg, option) && "Not a preg option.");
184 const AllowedSet& allowedSet = getAllowedSet(vreg);
185 assert(option <= allowedSet.size() && "Option outside allowed set.");
186 return allowedSet[option - 1];
189 PBQPRAProblem *PBQPBuilder::build(MachineFunction *mf, const LiveIntervals *lis,
190 const MachineBlockFrequencyInfo *mbfi,
191 const RegSet &vregs) {
193 LiveIntervals *LIS = const_cast<LiveIntervals*>(lis);
194 MachineRegisterInfo *mri = &mf->getRegInfo();
195 const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();
197 OwningPtr<PBQPRAProblem> p(new PBQPRAProblem());
198 PBQP::Graph &g = p->getGraph();
201 // Collect the set of preg intervals, record that they're used in the MF.
202 for (unsigned Reg = 1, e = tri->getNumRegs(); Reg != e; ++Reg) {
203 if (mri->def_empty(Reg))
206 mri->setPhysRegUsed(Reg);
209 // Iterate over vregs.
210 for (RegSet::const_iterator vregItr = vregs.begin(), vregEnd = vregs.end();
211 vregItr != vregEnd; ++vregItr) {
212 unsigned vreg = *vregItr;
213 const TargetRegisterClass *trc = mri->getRegClass(vreg);
214 LiveInterval *vregLI = &LIS->getInterval(vreg);
216 // Record any overlaps with regmask operands.
217 BitVector regMaskOverlaps;
218 LIS->checkRegMaskInterference(*vregLI, regMaskOverlaps);
220 // Compute an initial allowed set for the current vreg.
221 typedef std::vector<unsigned> VRAllowed;
223 ArrayRef<uint16_t> rawOrder = trc->getRawAllocationOrder(*mf);
224 for (unsigned i = 0; i != rawOrder.size(); ++i) {
225 unsigned preg = rawOrder[i];
226 if (mri->isReserved(preg))
229 // vregLI crosses a regmask operand that clobbers preg.
230 if (!regMaskOverlaps.empty() && !regMaskOverlaps.test(preg))
233 // vregLI overlaps fixed regunit interference.
234 bool Interference = false;
235 for (MCRegUnitIterator Units(preg, tri); Units.isValid(); ++Units) {
236 if (vregLI->overlaps(LIS->getRegUnit(*Units))) {
244 // preg is usable for this virtual register.
245 vrAllowed.push_back(preg);
248 // Construct the node.
249 PBQP::Graph::NodeId node =
250 g.addNode(PBQP::Vector(vrAllowed.size() + 1, 0));
252 // Record the mapping and allowed set in the problem.
253 p->recordVReg(vreg, node, vrAllowed.begin(), vrAllowed.end());
255 PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
256 vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
258 addSpillCosts(g.getNodeCosts(node), spillCost);
261 for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
262 vr1Itr != vrEnd; ++vr1Itr) {
263 unsigned vr1 = *vr1Itr;
264 const LiveInterval &l1 = lis->getInterval(vr1);
265 const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
267 for (RegSet::const_iterator vr2Itr = llvm::next(vr1Itr);
268 vr2Itr != vrEnd; ++vr2Itr) {
269 unsigned vr2 = *vr2Itr;
270 const LiveInterval &l2 = lis->getInterval(vr2);
271 const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
273 assert(!l2.empty() && "Empty interval in vreg set?");
274 if (l1.overlaps(l2)) {
275 PBQP::Graph::EdgeId edge =
276 g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
277 PBQP::Matrix(vr1Allowed.size()+1, vr2Allowed.size()+1, 0));
279 addInterferenceCosts(g.getEdgeCosts(edge), vr1Allowed, vr2Allowed, tri);
287 void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
288 PBQP::PBQPNum spillCost) {
289 costVec[0] = spillCost;
292 void PBQPBuilder::addInterferenceCosts(
293 PBQP::Matrix &costMat,
294 const PBQPRAProblem::AllowedSet &vr1Allowed,
295 const PBQPRAProblem::AllowedSet &vr2Allowed,
296 const TargetRegisterInfo *tri) {
297 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
298 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
300 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
301 unsigned preg1 = vr1Allowed[i];
303 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
304 unsigned preg2 = vr2Allowed[j];
306 if (tri->regsOverlap(preg1, preg2)) {
307 costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
313 PBQPRAProblem *PBQPBuilderWithCoalescing::build(MachineFunction *mf,
314 const LiveIntervals *lis,
315 const MachineBlockFrequencyInfo *mbfi,
316 const RegSet &vregs) {
318 OwningPtr<PBQPRAProblem> p(PBQPBuilder::build(mf, lis, mbfi, vregs));
319 PBQP::Graph &g = p->getGraph();
321 const TargetMachine &tm = mf->getTarget();
322 CoalescerPair cp(*tm.getRegisterInfo());
324 // Scan the machine function and add a coalescing cost whenever CoalescerPair
326 for (MachineFunction::const_iterator mbbItr = mf->begin(),
328 mbbItr != mbbEnd; ++mbbItr) {
329 const MachineBasicBlock *mbb = &*mbbItr;
331 for (MachineBasicBlock::const_iterator miItr = mbb->begin(),
333 miItr != miEnd; ++miItr) {
334 const MachineInstr *mi = &*miItr;
336 if (!cp.setRegisters(mi)) {
337 continue; // Not coalescable.
340 if (cp.getSrcReg() == cp.getDstReg()) {
341 continue; // Already coalesced.
344 unsigned dst = cp.getDstReg(),
345 src = cp.getSrcReg();
347 const float copyFactor = 0.5; // Cost of copy relative to load. Current
348 // value plucked randomly out of the air.
350 PBQP::PBQPNum cBenefit =
351 copyFactor * LiveIntervals::getSpillWeight(false, true, mbfi, mi);
354 if (!mf->getRegInfo().isAllocatable(dst)) {
358 const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
359 unsigned pregOpt = 0;
360 while (pregOpt < allowed.size() && allowed[pregOpt] != dst) {
363 if (pregOpt < allowed.size()) {
364 ++pregOpt; // +1 to account for spill option.
365 PBQP::Graph::NodeId node = p->getNodeForVReg(src);
366 addPhysRegCoalesce(g.getNodeCosts(node), pregOpt, cBenefit);
369 const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
370 const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
371 PBQP::Graph::NodeId node1 = p->getNodeForVReg(dst);
372 PBQP::Graph::NodeId node2 = p->getNodeForVReg(src);
373 PBQP::Graph::EdgeId edge = g.findEdge(node1, node2);
374 if (edge == g.invalidEdgeId()) {
375 edge = g.addEdge(node1, node2, PBQP::Matrix(allowed1->size() + 1,
376 allowed2->size() + 1,
379 if (g.getEdgeNode1(edge) == node2) {
380 std::swap(node1, node2);
381 std::swap(allowed1, allowed2);
385 addVirtRegCoalesce(g.getEdgeCosts(edge), *allowed1, *allowed2,
394 void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
396 PBQP::PBQPNum benefit) {
397 costVec[pregOption] += -benefit;
400 void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
401 PBQP::Matrix &costMat,
402 const PBQPRAProblem::AllowedSet &vr1Allowed,
403 const PBQPRAProblem::AllowedSet &vr2Allowed,
404 PBQP::PBQPNum benefit) {
406 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
407 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
409 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
410 unsigned preg1 = vr1Allowed[i];
411 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
412 unsigned preg2 = vr2Allowed[j];
414 if (preg1 == preg2) {
415 costMat[i + 1][j + 1] += -benefit;
422 void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
423 au.setPreservesCFG();
424 au.addRequired<AliasAnalysis>();
425 au.addPreserved<AliasAnalysis>();
426 au.addRequired<SlotIndexes>();
427 au.addPreserved<SlotIndexes>();
428 au.addRequired<LiveIntervals>();
429 au.addPreserved<LiveIntervals>();
430 //au.addRequiredID(SplitCriticalEdgesID);
432 au.addRequiredID(*customPassID);
433 au.addRequired<LiveStacks>();
434 au.addPreserved<LiveStacks>();
435 au.addRequired<MachineBlockFrequencyInfo>();
436 au.addPreserved<MachineBlockFrequencyInfo>();
437 au.addRequired<MachineLoopInfo>();
438 au.addPreserved<MachineLoopInfo>();
439 au.addRequired<MachineDominatorTree>();
440 au.addPreserved<MachineDominatorTree>();
441 au.addRequired<VirtRegMap>();
442 au.addPreserved<VirtRegMap>();
443 MachineFunctionPass::getAnalysisUsage(au);
446 void RegAllocPBQP::findVRegIntervalsToAlloc() {
448 // Iterate over all live ranges.
449 for (unsigned i = 0, e = mri->getNumVirtRegs(); i != e; ++i) {
450 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
451 if (mri->reg_nodbg_empty(Reg))
453 LiveInterval *li = &lis->getInterval(Reg);
455 // If this live interval is non-empty we will use pbqp to allocate it.
456 // Empty intervals we allocate in a simple post-processing stage in
459 vregsToAlloc.insert(li->reg);
461 emptyIntervalVRegs.insert(li->reg);
466 bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
467 const PBQP::Solution &solution) {
468 // Set to true if we have any spills
469 bool anotherRoundNeeded = false;
471 // Clear the existing allocation.
474 const PBQP::Graph &g = problem.getGraph();
475 // Iterate over the nodes mapping the PBQP solution to a register
477 for (PBQP::Graph::NodeItr nodeItr = g.nodesBegin(),
478 nodeEnd = g.nodesEnd();
479 nodeItr != nodeEnd; ++nodeItr) {
480 unsigned vreg = problem.getVRegForNode(*nodeItr);
481 unsigned alloc = solution.getSelection(*nodeItr);
483 if (problem.isPRegOption(vreg, alloc)) {
484 unsigned preg = problem.getPRegForOption(vreg, alloc);
485 DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> "
486 << tri->getName(preg) << "\n");
487 assert(preg != 0 && "Invalid preg selected.");
488 vrm->assignVirt2Phys(vreg, preg);
489 } else if (problem.isSpillOption(vreg, alloc)) {
490 vregsToAlloc.erase(vreg);
491 SmallVector<unsigned, 8> newSpills;
492 LiveRangeEdit LRE(&lis->getInterval(vreg), newSpills, *mf, *lis, vrm);
495 DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> SPILLED (Cost: "
496 << LRE.getParent().weight << ", New vregs: ");
498 // Copy any newly inserted live intervals into the list of regs to
500 for (LiveRangeEdit::iterator itr = LRE.begin(), end = LRE.end();
502 LiveInterval &li = lis->getInterval(*itr);
503 assert(!li.empty() && "Empty spill range.");
504 DEBUG(dbgs() << PrintReg(li.reg, tri) << " ");
505 vregsToAlloc.insert(li.reg);
508 DEBUG(dbgs() << ")\n");
510 // We need another round if spill intervals were added.
511 anotherRoundNeeded |= !LRE.empty();
513 llvm_unreachable("Unknown allocation option.");
517 return !anotherRoundNeeded;
521 void RegAllocPBQP::finalizeAlloc() const {
522 // First allocate registers for the empty intervals.
523 for (RegSet::const_iterator
524 itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
526 LiveInterval *li = &lis->getInterval(*itr);
528 unsigned physReg = mri->getSimpleHint(li->reg);
531 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
532 physReg = liRC->getRawAllocationOrder(*mf).front();
535 vrm->assignVirt2Phys(li->reg, physReg);
539 bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
542 tm = &mf->getTarget();
543 tri = tm->getRegisterInfo();
544 tii = tm->getInstrInfo();
545 mri = &mf->getRegInfo();
547 lis = &getAnalysis<LiveIntervals>();
548 lss = &getAnalysis<LiveStacks>();
549 mbfi = &getAnalysis<MachineBlockFrequencyInfo>();
551 calculateSpillWeightsAndHints(*lis, MF, getAnalysis<MachineLoopInfo>(),
554 vrm = &getAnalysis<VirtRegMap>();
555 spiller.reset(createInlineSpiller(*this, MF, *vrm));
557 mri->freezeReservedRegs(MF);
559 DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getName() << "\n");
561 // Allocator main loop:
563 // * Map current regalloc problem to a PBQP problem
564 // * Solve the PBQP problem
565 // * Map the solution back to a register allocation
566 // * Spill if necessary
568 // This process is continued till no more spills are generated.
570 // Find the vreg intervals in need of allocation.
571 findVRegIntervalsToAlloc();
574 const Function* func = mf->getFunction();
576 func->getParent()->getModuleIdentifier() + "." +
577 func->getName().str();
580 // If there are non-empty intervals allocate them using pbqp.
581 if (!vregsToAlloc.empty()) {
583 bool pbqpAllocComplete = false;
586 while (!pbqpAllocComplete) {
587 DEBUG(dbgs() << " PBQP Regalloc round " << round << ":\n");
589 OwningPtr<PBQPRAProblem> problem(
590 builder->build(mf, lis, mbfi, vregsToAlloc));
593 if (pbqpDumpGraphs) {
594 std::ostringstream rs;
596 std::string graphFileName(fqn + "." + rs.str() + ".pbqpgraph");
598 raw_fd_ostream os(graphFileName.c_str(), tmp);
599 DEBUG(dbgs() << "Dumping graph for round " << round << " to \""
600 << graphFileName << "\"\n");
601 problem->getGraph().dump(os);
605 PBQP::Solution solution =
606 PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(
607 problem->getGraph());
609 pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
615 // Finalise allocation, allocate empty ranges.
617 vregsToAlloc.clear();
618 emptyIntervalVRegs.clear();
620 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
625 FunctionPass* llvm::createPBQPRegisterAllocator(
626 OwningPtr<PBQPBuilder> &builder,
627 char *customPassID) {
628 return new RegAllocPBQP(builder, customPassID);
631 FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
632 OwningPtr<PBQPBuilder> Builder;
634 Builder.reset(new PBQPBuilderWithCoalescing());
636 Builder.reset(new PBQPBuilder());
637 return createPBQPRegisterAllocator(Builder);