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"
35 #include "VirtRegMap.h"
36 #include "RegisterCoalescer.h"
37 #include "llvm/Module.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/RegAllocPBQP.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/HeuristicSolver.h"
49 #include "llvm/CodeGen/PBQP/Graph.h"
50 #include "llvm/CodeGen/PBQP/Heuristics/Briggs.h"
51 #include "llvm/CodeGen/RegAllocRegistry.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetInstrInfo.h"
55 #include "llvm/Target/TargetMachine.h"
64 static RegisterRegAlloc
65 registerPBQPRepAlloc("pbqp", "PBQP register allocator",
66 createDefaultPBQPRegisterAllocator);
69 pbqpCoalescing("pbqp-coalescing",
70 cl::desc("Attempt coalescing during PBQP register allocation."),
71 cl::init(false), cl::Hidden);
75 pbqpDumpGraphs("pbqp-dump-graphs",
76 cl::desc("Dump graphs for each function/round in the compilation unit."),
77 cl::init(false), cl::Hidden);
83 /// PBQP based allocators solve the register allocation problem by mapping
84 /// register allocation problems to Partitioned Boolean Quadratic
85 /// Programming problems.
86 class RegAllocPBQP : public MachineFunctionPass {
91 /// Construct a PBQP register allocator.
92 RegAllocPBQP(std::auto_ptr<PBQPBuilder> b, char *cPassID=0)
93 : MachineFunctionPass(ID), builder(b), customPassID(cPassID) {
94 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
95 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
96 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
97 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
98 initializeMachineLoopInfoPass(*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::vector<PBQP::Graph::NodeItr> NodeVector;
122 typedef std::set<unsigned> RegSet;
125 std::auto_ptr<PBQPBuilder> builder;
130 const TargetMachine *tm;
131 const TargetRegisterInfo *tri;
132 const TargetInstrInfo *tii;
133 const MachineLoopInfo *loopInfo;
134 MachineRegisterInfo *mri;
136 std::auto_ptr<Spiller> spiller;
141 RegSet vregsToAlloc, emptyIntervalVRegs;
143 /// \brief Finds the initial set of vreg intervals to allocate.
144 void findVRegIntervalsToAlloc();
146 /// \brief Given a solved PBQP problem maps this solution back to a register
148 bool mapPBQPToRegAlloc(const PBQPRAProblem &problem,
149 const PBQP::Solution &solution);
151 /// \brief Postprocessing before final spilling. Sets basic block "live in"
153 void finalizeAlloc() const;
157 char RegAllocPBQP::ID = 0;
159 } // End anonymous namespace.
161 unsigned PBQPRAProblem::getVRegForNode(PBQP::Graph::ConstNodeItr node) const {
162 Node2VReg::const_iterator vregItr = node2VReg.find(node);
163 assert(vregItr != node2VReg.end() && "No vreg for node.");
164 return vregItr->second;
167 PBQP::Graph::NodeItr PBQPRAProblem::getNodeForVReg(unsigned vreg) const {
168 VReg2Node::const_iterator nodeItr = vreg2Node.find(vreg);
169 assert(nodeItr != vreg2Node.end() && "No node for vreg.");
170 return nodeItr->second;
174 const PBQPRAProblem::AllowedSet&
175 PBQPRAProblem::getAllowedSet(unsigned vreg) const {
176 AllowedSetMap::const_iterator allowedSetItr = allowedSets.find(vreg);
177 assert(allowedSetItr != allowedSets.end() && "No pregs for vreg.");
178 const AllowedSet &allowedSet = allowedSetItr->second;
182 unsigned PBQPRAProblem::getPRegForOption(unsigned vreg, unsigned option) const {
183 assert(isPRegOption(vreg, option) && "Not a preg option.");
185 const AllowedSet& allowedSet = getAllowedSet(vreg);
186 assert(option <= allowedSet.size() && "Option outside allowed set.");
187 return allowedSet[option - 1];
190 std::auto_ptr<PBQPRAProblem> PBQPBuilder::build(MachineFunction *mf,
191 const LiveIntervals *lis,
192 const MachineLoopInfo *loopInfo,
193 const RegSet &vregs) {
195 LiveIntervals *LIS = const_cast<LiveIntervals*>(lis);
196 MachineRegisterInfo *mri = &mf->getRegInfo();
197 const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();
199 std::auto_ptr<PBQPRAProblem> p(new PBQPRAProblem());
200 PBQP::Graph &g = p->getGraph();
203 // Collect the set of preg intervals, record that they're used in the MF.
204 for (unsigned Reg = 1, e = tri->getNumRegs(); Reg != e; ++Reg) {
205 if (mri->def_empty(Reg))
208 mri->setPhysRegUsed(Reg);
211 BitVector reservedRegs = tri->getReservedRegs(*mf);
213 // Iterate over vregs.
214 for (RegSet::const_iterator vregItr = vregs.begin(), vregEnd = vregs.end();
215 vregItr != vregEnd; ++vregItr) {
216 unsigned vreg = *vregItr;
217 const TargetRegisterClass *trc = mri->getRegClass(vreg);
218 LiveInterval *vregLI = &LIS->getInterval(vreg);
220 // Record any overlaps with regmask operands.
221 BitVector regMaskOverlaps;
222 LIS->checkRegMaskInterference(*vregLI, regMaskOverlaps);
224 // Compute an initial allowed set for the current vreg.
225 typedef std::vector<unsigned> 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))
233 // vregLI crosses a regmask operand that clobbers preg.
234 if (!regMaskOverlaps.empty() && !regMaskOverlaps.test(preg))
237 // vregLI overlaps fixed regunit interference.
238 bool Interference = false;
239 for (MCRegUnitIterator Units(preg, tri); Units.isValid(); ++Units) {
240 if (vregLI->overlaps(LIS->getRegUnit(*Units))) {
248 // preg is usable for this virtual register.
249 vrAllowed.push_back(preg);
252 // Construct the node.
253 PBQP::Graph::NodeItr node =
254 g.addNode(PBQP::Vector(vrAllowed.size() + 1, 0));
256 // Record the mapping and allowed set in the problem.
257 p->recordVReg(vreg, node, vrAllowed.begin(), vrAllowed.end());
259 PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
260 vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
262 addSpillCosts(g.getNodeCosts(node), spillCost);
265 for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
266 vr1Itr != vrEnd; ++vr1Itr) {
267 unsigned vr1 = *vr1Itr;
268 const LiveInterval &l1 = lis->getInterval(vr1);
269 const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
271 for (RegSet::const_iterator vr2Itr = llvm::next(vr1Itr);
272 vr2Itr != vrEnd; ++vr2Itr) {
273 unsigned vr2 = *vr2Itr;
274 const LiveInterval &l2 = lis->getInterval(vr2);
275 const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
277 assert(!l2.empty() && "Empty interval in vreg set?");
278 if (l1.overlaps(l2)) {
279 PBQP::Graph::EdgeItr edge =
280 g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
281 PBQP::Matrix(vr1Allowed.size()+1, vr2Allowed.size()+1, 0));
283 addInterferenceCosts(g.getEdgeCosts(edge), vr1Allowed, vr2Allowed, tri);
291 void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
292 PBQP::PBQPNum spillCost) {
293 costVec[0] = spillCost;
296 void PBQPBuilder::addInterferenceCosts(
297 PBQP::Matrix &costMat,
298 const PBQPRAProblem::AllowedSet &vr1Allowed,
299 const PBQPRAProblem::AllowedSet &vr2Allowed,
300 const TargetRegisterInfo *tri) {
301 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
302 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
304 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
305 unsigned preg1 = vr1Allowed[i];
307 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
308 unsigned preg2 = vr2Allowed[j];
310 if (tri->regsOverlap(preg1, preg2)) {
311 costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
317 std::auto_ptr<PBQPRAProblem> PBQPBuilderWithCoalescing::build(
319 const LiveIntervals *lis,
320 const MachineLoopInfo *loopInfo,
321 const RegSet &vregs) {
323 std::auto_ptr<PBQPRAProblem> p = PBQPBuilder::build(mf, lis, loopInfo, vregs);
324 PBQP::Graph &g = p->getGraph();
326 const TargetMachine &tm = mf->getTarget();
327 CoalescerPair cp(*tm.getRegisterInfo());
329 // Scan the machine function and add a coalescing cost whenever CoalescerPair
331 for (MachineFunction::const_iterator mbbItr = mf->begin(),
333 mbbItr != mbbEnd; ++mbbItr) {
334 const MachineBasicBlock *mbb = &*mbbItr;
336 for (MachineBasicBlock::const_iterator miItr = mbb->begin(),
338 miItr != miEnd; ++miItr) {
339 const MachineInstr *mi = &*miItr;
341 if (!cp.setRegisters(mi)) {
342 continue; // Not coalescable.
345 if (cp.getSrcReg() == cp.getDstReg()) {
346 continue; // Already coalesced.
349 unsigned dst = cp.getDstReg(),
350 src = cp.getSrcReg();
352 const float copyFactor = 0.5; // Cost of copy relative to load. Current
353 // value plucked randomly out of the air.
355 PBQP::PBQPNum cBenefit =
356 copyFactor * LiveIntervals::getSpillWeight(false, true,
357 loopInfo->getLoopDepth(mbb));
360 if (!lis->isAllocatable(dst)) {
364 const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
365 unsigned pregOpt = 0;
366 while (pregOpt < allowed.size() && allowed[pregOpt] != dst) {
369 if (pregOpt < allowed.size()) {
370 ++pregOpt; // +1 to account for spill option.
371 PBQP::Graph::NodeItr node = p->getNodeForVReg(src);
372 addPhysRegCoalesce(g.getNodeCosts(node), pregOpt, cBenefit);
375 const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
376 const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
377 PBQP::Graph::NodeItr node1 = p->getNodeForVReg(dst);
378 PBQP::Graph::NodeItr node2 = p->getNodeForVReg(src);
379 PBQP::Graph::EdgeItr edge = g.findEdge(node1, node2);
380 if (edge == g.edgesEnd()) {
381 edge = g.addEdge(node1, node2, PBQP::Matrix(allowed1->size() + 1,
382 allowed2->size() + 1,
385 if (g.getEdgeNode1(edge) == node2) {
386 std::swap(node1, node2);
387 std::swap(allowed1, allowed2);
391 addVirtRegCoalesce(g.getEdgeCosts(edge), *allowed1, *allowed2,
400 void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
402 PBQP::PBQPNum benefit) {
403 costVec[pregOption] += -benefit;
406 void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
407 PBQP::Matrix &costMat,
408 const PBQPRAProblem::AllowedSet &vr1Allowed,
409 const PBQPRAProblem::AllowedSet &vr2Allowed,
410 PBQP::PBQPNum benefit) {
412 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
413 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
415 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
416 unsigned preg1 = vr1Allowed[i];
417 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
418 unsigned preg2 = vr2Allowed[j];
420 if (preg1 == preg2) {
421 costMat[i + 1][j + 1] += -benefit;
428 void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
429 au.setPreservesCFG();
430 au.addRequired<AliasAnalysis>();
431 au.addPreserved<AliasAnalysis>();
432 au.addRequired<SlotIndexes>();
433 au.addPreserved<SlotIndexes>();
434 au.addRequired<LiveIntervals>();
435 au.addPreserved<LiveIntervals>();
436 //au.addRequiredID(SplitCriticalEdgesID);
438 au.addRequiredID(*customPassID);
439 au.addRequired<CalculateSpillWeights>();
440 au.addRequired<LiveStacks>();
441 au.addPreserved<LiveStacks>();
442 au.addRequired<MachineDominatorTree>();
443 au.addPreserved<MachineDominatorTree>();
444 au.addRequired<MachineLoopInfo>();
445 au.addPreserved<MachineLoopInfo>();
446 au.addRequired<VirtRegMap>();
447 au.addPreserved<VirtRegMap>();
448 MachineFunctionPass::getAnalysisUsage(au);
451 void RegAllocPBQP::findVRegIntervalsToAlloc() {
453 // Iterate over all live ranges.
454 for (unsigned i = 0, e = mri->getNumVirtRegs(); i != e; ++i) {
455 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
456 if (mri->reg_nodbg_empty(Reg))
458 LiveInterval *li = &lis->getInterval(Reg);
460 // If this live interval is non-empty we will use pbqp to allocate it.
461 // Empty intervals we allocate in a simple post-processing stage in
464 vregsToAlloc.insert(li->reg);
466 emptyIntervalVRegs.insert(li->reg);
471 bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
472 const PBQP::Solution &solution) {
473 // Set to true if we have any spills
474 bool anotherRoundNeeded = false;
476 // Clear the existing allocation.
479 const PBQP::Graph &g = problem.getGraph();
480 // Iterate over the nodes mapping the PBQP solution to a register
482 for (PBQP::Graph::ConstNodeItr node = g.nodesBegin(),
483 nodeEnd = g.nodesEnd();
484 node != nodeEnd; ++node) {
485 unsigned vreg = problem.getVRegForNode(node);
486 unsigned alloc = solution.getSelection(node);
488 if (problem.isPRegOption(vreg, alloc)) {
489 unsigned preg = problem.getPRegForOption(vreg, alloc);
490 DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> "
491 << tri->getName(preg) << "\n");
492 assert(preg != 0 && "Invalid preg selected.");
493 vrm->assignVirt2Phys(vreg, preg);
494 } else if (problem.isSpillOption(vreg, alloc)) {
495 vregsToAlloc.erase(vreg);
496 SmallVector<LiveInterval*, 8> newSpills;
497 LiveRangeEdit LRE(&lis->getInterval(vreg), newSpills, *mf, *lis, vrm);
500 DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> SPILLED (Cost: "
501 << LRE.getParent().weight << ", New vregs: ");
503 // Copy any newly inserted live intervals into the list of regs to
505 for (LiveRangeEdit::iterator itr = LRE.begin(), end = LRE.end();
507 assert(!(*itr)->empty() && "Empty spill range.");
508 DEBUG(dbgs() << PrintReg((*itr)->reg, tri) << " ");
509 vregsToAlloc.insert((*itr)->reg);
512 DEBUG(dbgs() << ")\n");
514 // We need another round if spill intervals were added.
515 anotherRoundNeeded |= !LRE.empty();
517 llvm_unreachable("Unknown allocation option.");
521 return !anotherRoundNeeded;
525 void RegAllocPBQP::finalizeAlloc() const {
526 // First allocate registers for the empty intervals.
527 for (RegSet::const_iterator
528 itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
530 LiveInterval *li = &lis->getInterval(*itr);
532 unsigned physReg = vrm->getRegAllocPref(li->reg);
535 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
536 physReg = liRC->getRawAllocationOrder(*mf).front();
539 vrm->assignVirt2Phys(li->reg, physReg);
543 bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
546 tm = &mf->getTarget();
547 tri = tm->getRegisterInfo();
548 tii = tm->getInstrInfo();
549 mri = &mf->getRegInfo();
551 lis = &getAnalysis<LiveIntervals>();
552 lss = &getAnalysis<LiveStacks>();
553 loopInfo = &getAnalysis<MachineLoopInfo>();
555 vrm = &getAnalysis<VirtRegMap>();
556 spiller.reset(createInlineSpiller(*this, MF, *vrm));
558 mri->freezeReservedRegs(MF);
560 DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getName() << "\n");
562 // Allocator main loop:
564 // * Map current regalloc problem to a PBQP problem
565 // * Solve the PBQP problem
566 // * Map the solution back to a register allocation
567 // * Spill if necessary
569 // This process is continued till no more spills are generated.
571 // Find the vreg intervals in need of allocation.
572 findVRegIntervalsToAlloc();
575 const Function* func = mf->getFunction();
577 func->getParent()->getModuleIdentifier() + "." +
578 func->getName().str();
581 // If there are non-empty intervals allocate them using pbqp.
582 if (!vregsToAlloc.empty()) {
584 bool pbqpAllocComplete = false;
587 while (!pbqpAllocComplete) {
588 DEBUG(dbgs() << " PBQP Regalloc round " << round << ":\n");
590 std::auto_ptr<PBQPRAProblem> problem =
591 builder->build(mf, lis, loopInfo, vregsToAlloc);
594 if (pbqpDumpGraphs) {
595 std::ostringstream rs;
597 std::string graphFileName(fqn + "." + rs.str() + ".pbqpgraph");
599 raw_fd_ostream os(graphFileName.c_str(), tmp);
600 DEBUG(dbgs() << "Dumping graph for round " << round << " to \""
601 << graphFileName << "\"\n");
602 problem->getGraph().dump(os);
606 PBQP::Solution solution =
607 PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(
608 problem->getGraph());
610 pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
616 // Finalise allocation, allocate empty ranges.
618 vregsToAlloc.clear();
619 emptyIntervalVRegs.clear();
621 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
626 FunctionPass* llvm::createPBQPRegisterAllocator(
627 std::auto_ptr<PBQPBuilder> builder,
628 char *customPassID) {
629 return new RegAllocPBQP(builder, customPassID);
632 FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
633 if (pbqpCoalescing) {
634 return createPBQPRegisterAllocator(
635 std::auto_ptr<PBQPBuilder>(new PBQPBuilderWithCoalescing()));
637 return createPBQPRegisterAllocator(
638 std::auto_ptr<PBQPBuilder>(new PBQPBuilder()));