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 #include "llvm/CodeGen/RegAllocPBQP.h"
33 #include "RegisterCoalescer.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/CodeGen/CalcSpillWeights.h"
37 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
38 #include "llvm/CodeGen/LiveRangeEdit.h"
39 #include "llvm/CodeGen/LiveStackAnalysis.h"
40 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
41 #include "llvm/CodeGen/MachineDominators.h"
42 #include "llvm/CodeGen/MachineFunctionPass.h"
43 #include "llvm/CodeGen/MachineLoopInfo.h"
44 #include "llvm/CodeGen/MachineRegisterInfo.h"
45 #include "llvm/CodeGen/RegAllocRegistry.h"
46 #include "llvm/CodeGen/VirtRegMap.h"
47 #include "llvm/IR/Module.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/FileSystem.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include "llvm/Target/TargetInstrInfo.h"
52 #include "llvm/Target/TargetMachine.h"
53 #include "llvm/Target/TargetSubtargetInfo.h"
62 #define DEBUG_TYPE "regalloc"
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::unique_ptr<PBQPBuilder> b, char *cPassID = nullptr)
93 : MachineFunctionPass(ID), builder(std::move(b)), customPassID(cPassID) {
94 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
95 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
96 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
97 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
100 /// Return the pass name.
101 const char* getPassName() const override {
102 return "PBQP Register Allocator";
105 /// PBQP analysis usage.
106 void getAnalysisUsage(AnalysisUsage &au) const override;
108 /// Perform register allocation
109 bool runOnMachineFunction(MachineFunction &MF) override;
113 typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
114 typedef std::vector<const LiveInterval*> Node2LIMap;
115 typedef std::vector<unsigned> AllowedSet;
116 typedef std::vector<AllowedSet> AllowedSetMap;
117 typedef std::pair<unsigned, unsigned> RegPair;
118 typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
119 typedef std::set<unsigned> RegSet;
121 std::unique_ptr<PBQPBuilder> builder;
126 const TargetMachine *tm;
127 const TargetRegisterInfo *tri;
128 const TargetInstrInfo *tii;
129 MachineRegisterInfo *mri;
130 const MachineBlockFrequencyInfo *mbfi;
132 std::unique_ptr<Spiller> spiller;
137 RegSet vregsToAlloc, emptyIntervalVRegs;
139 /// \brief Finds the initial set of vreg intervals to allocate.
140 void findVRegIntervalsToAlloc();
142 /// \brief Given a solved PBQP problem maps this solution back to a register
144 bool mapPBQPToRegAlloc(const PBQPRAProblem &problem,
145 const PBQP::Solution &solution);
147 /// \brief Postprocessing before final spilling. Sets basic block "live in"
149 void finalizeAlloc() const;
153 char RegAllocPBQP::ID = 0;
155 } // End anonymous namespace.
157 unsigned PBQPRAProblem::getVRegForNode(PBQPRAGraph::NodeId node) const {
158 Node2VReg::const_iterator vregItr = node2VReg.find(node);
159 assert(vregItr != node2VReg.end() && "No vreg for node.");
160 return vregItr->second;
163 PBQPRAGraph::NodeId PBQPRAProblem::getNodeForVReg(unsigned vreg) const {
164 VReg2Node::const_iterator nodeItr = vreg2Node.find(vreg);
165 assert(nodeItr != vreg2Node.end() && "No node for vreg.");
166 return nodeItr->second;
170 const PBQPRAProblem::AllowedSet&
171 PBQPRAProblem::getAllowedSet(unsigned vreg) const {
172 AllowedSetMap::const_iterator allowedSetItr = allowedSets.find(vreg);
173 assert(allowedSetItr != allowedSets.end() && "No pregs for vreg.");
174 const AllowedSet &allowedSet = allowedSetItr->second;
178 unsigned PBQPRAProblem::getPRegForOption(unsigned vreg, unsigned option) const {
179 assert(isPRegOption(vreg, option) && "Not a preg option.");
181 const AllowedSet& allowedSet = getAllowedSet(vreg);
182 assert(option <= allowedSet.size() && "Option outside allowed set.");
183 return allowedSet[option - 1];
186 PBQPRAProblem *PBQPBuilder::build(MachineFunction *mf, const LiveIntervals *lis,
187 const MachineBlockFrequencyInfo *mbfi,
188 const RegSet &vregs) {
190 LiveIntervals *LIS = const_cast<LiveIntervals*>(lis);
191 MachineRegisterInfo *mri = &mf->getRegInfo();
192 const TargetRegisterInfo *tri =
193 mf->getTarget().getSubtargetImpl()->getRegisterInfo();
195 std::unique_ptr<PBQPRAProblem> p(new PBQPRAProblem());
196 PBQPRAGraph &g = p->getGraph();
199 // Collect the set of preg intervals, record that they're used in the MF.
200 for (unsigned Reg = 1, e = tri->getNumRegs(); Reg != e; ++Reg) {
201 if (mri->def_empty(Reg))
204 mri->setPhysRegUsed(Reg);
207 // Iterate over vregs.
208 for (RegSet::const_iterator vregItr = vregs.begin(), vregEnd = vregs.end();
209 vregItr != vregEnd; ++vregItr) {
210 unsigned vreg = *vregItr;
211 const TargetRegisterClass *trc = mri->getRegClass(vreg);
212 LiveInterval *vregLI = &LIS->getInterval(vreg);
214 // Record any overlaps with regmask operands.
215 BitVector regMaskOverlaps;
216 LIS->checkRegMaskInterference(*vregLI, regMaskOverlaps);
218 // Compute an initial allowed set for the current vreg.
219 typedef std::vector<unsigned> VRAllowed;
221 ArrayRef<MCPhysReg> rawOrder = trc->getRawAllocationOrder(*mf);
222 for (unsigned i = 0; i != rawOrder.size(); ++i) {
223 unsigned preg = rawOrder[i];
224 if (mri->isReserved(preg))
227 // vregLI crosses a regmask operand that clobbers preg.
228 if (!regMaskOverlaps.empty() && !regMaskOverlaps.test(preg))
231 // vregLI overlaps fixed regunit interference.
232 bool Interference = false;
233 for (MCRegUnitIterator Units(preg, tri); Units.isValid(); ++Units) {
234 if (vregLI->overlaps(LIS->getRegUnit(*Units))) {
242 // preg is usable for this virtual register.
243 vrAllowed.push_back(preg);
246 PBQP::Vector nodeCosts(vrAllowed.size() + 1, 0);
248 PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
249 vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
251 addSpillCosts(nodeCosts, spillCost);
253 // Construct the node.
254 PBQPRAGraph::NodeId nId = g.addNode(std::move(nodeCosts));
256 // Record the mapping and allowed set in the problem.
257 p->recordVReg(vreg, nId, vrAllowed.begin(), vrAllowed.end());
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 = std::next(vr1Itr); vr2Itr != vrEnd;
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::Matrix edgeCosts(vr1Allowed.size()+1, vr2Allowed.size()+1, 0);
276 addInterferenceCosts(edgeCosts, vr1Allowed, vr2Allowed, tri);
278 g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
279 std::move(edgeCosts));
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 std::unique_ptr<PBQPRAProblem> p(PBQPBuilder::build(mf, lis, mbfi, vregs));
319 PBQPRAGraph &g = p->getGraph();
321 const TargetMachine &tm = mf->getTarget();
322 CoalescerPair cp(*tm.getSubtargetImpl()->getRegisterInfo());
324 // Scan the machine function and add a coalescing cost whenever CoalescerPair
326 for (const auto &mbb : *mf) {
327 for (const auto &mi : mbb) {
328 if (!cp.setRegisters(&mi)) {
329 continue; // Not coalescable.
332 if (cp.getSrcReg() == cp.getDstReg()) {
333 continue; // Already coalesced.
336 unsigned dst = cp.getDstReg(),
337 src = cp.getSrcReg();
339 const float copyFactor = 0.5; // Cost of copy relative to load. Current
340 // value plucked randomly out of the air.
342 PBQP::PBQPNum cBenefit =
343 copyFactor * LiveIntervals::getSpillWeight(false, true, mbfi, &mi);
346 if (!mf->getRegInfo().isAllocatable(dst)) {
350 const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
351 unsigned pregOpt = 0;
352 while (pregOpt < allowed.size() && allowed[pregOpt] != dst) {
355 if (pregOpt < allowed.size()) {
356 ++pregOpt; // +1 to account for spill option.
357 PBQPRAGraph::NodeId node = p->getNodeForVReg(src);
358 llvm::dbgs() << "Reading node costs for node " << node << "\n";
359 llvm::dbgs() << "Source node: " << &g.getNodeCosts(node) << "\n";
360 PBQP::Vector newCosts(g.getNodeCosts(node));
361 addPhysRegCoalesce(newCosts, pregOpt, cBenefit);
362 g.setNodeCosts(node, newCosts);
365 const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
366 const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
367 PBQPRAGraph::NodeId node1 = p->getNodeForVReg(dst);
368 PBQPRAGraph::NodeId node2 = p->getNodeForVReg(src);
369 PBQPRAGraph::EdgeId edge = g.findEdge(node1, node2);
370 if (edge == g.invalidEdgeId()) {
371 PBQP::Matrix costs(allowed1->size() + 1, allowed2->size() + 1, 0);
372 addVirtRegCoalesce(costs, *allowed1, *allowed2, cBenefit);
373 g.addEdge(node1, node2, costs);
375 if (g.getEdgeNode1Id(edge) == node2) {
376 std::swap(node1, node2);
377 std::swap(allowed1, allowed2);
379 PBQP::Matrix costs(g.getEdgeCosts(edge));
380 addVirtRegCoalesce(costs, *allowed1, *allowed2, cBenefit);
381 g.setEdgeCosts(edge, costs);
390 void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
392 PBQP::PBQPNum benefit) {
393 costVec[pregOption] += -benefit;
396 void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
397 PBQP::Matrix &costMat,
398 const PBQPRAProblem::AllowedSet &vr1Allowed,
399 const PBQPRAProblem::AllowedSet &vr2Allowed,
400 PBQP::PBQPNum benefit) {
402 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
403 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
405 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
406 unsigned preg1 = vr1Allowed[i];
407 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
408 unsigned preg2 = vr2Allowed[j];
410 if (preg1 == preg2) {
411 costMat[i + 1][j + 1] += -benefit;
418 void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
419 au.setPreservesCFG();
420 au.addRequired<AliasAnalysis>();
421 au.addPreserved<AliasAnalysis>();
422 au.addRequired<SlotIndexes>();
423 au.addPreserved<SlotIndexes>();
424 au.addRequired<LiveIntervals>();
425 au.addPreserved<LiveIntervals>();
426 //au.addRequiredID(SplitCriticalEdgesID);
428 au.addRequiredID(*customPassID);
429 au.addRequired<LiveStacks>();
430 au.addPreserved<LiveStacks>();
431 au.addRequired<MachineBlockFrequencyInfo>();
432 au.addPreserved<MachineBlockFrequencyInfo>();
433 au.addRequired<MachineLoopInfo>();
434 au.addPreserved<MachineLoopInfo>();
435 au.addRequired<MachineDominatorTree>();
436 au.addPreserved<MachineDominatorTree>();
437 au.addRequired<VirtRegMap>();
438 au.addPreserved<VirtRegMap>();
439 MachineFunctionPass::getAnalysisUsage(au);
442 void RegAllocPBQP::findVRegIntervalsToAlloc() {
444 // Iterate over all live ranges.
445 for (unsigned i = 0, e = mri->getNumVirtRegs(); i != e; ++i) {
446 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
447 if (mri->reg_nodbg_empty(Reg))
449 LiveInterval *li = &lis->getInterval(Reg);
451 // If this live interval is non-empty we will use pbqp to allocate it.
452 // Empty intervals we allocate in a simple post-processing stage in
455 vregsToAlloc.insert(li->reg);
457 emptyIntervalVRegs.insert(li->reg);
462 bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
463 const PBQP::Solution &solution) {
464 // Set to true if we have any spills
465 bool anotherRoundNeeded = false;
467 // Clear the existing allocation.
470 const PBQPRAGraph &g = problem.getGraph();
471 // Iterate over the nodes mapping the PBQP solution to a register
473 for (auto NId : g.nodeIds()) {
474 unsigned vreg = problem.getVRegForNode(NId);
475 unsigned alloc = solution.getSelection(NId);
477 if (problem.isPRegOption(vreg, alloc)) {
478 unsigned preg = problem.getPRegForOption(vreg, alloc);
479 DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> "
480 << tri->getName(preg) << "\n");
481 assert(preg != 0 && "Invalid preg selected.");
482 vrm->assignVirt2Phys(vreg, preg);
483 } else if (problem.isSpillOption(vreg, alloc)) {
484 vregsToAlloc.erase(vreg);
485 SmallVector<unsigned, 8> newSpills;
486 LiveRangeEdit LRE(&lis->getInterval(vreg), newSpills, *mf, *lis, vrm);
489 DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> SPILLED (Cost: "
490 << LRE.getParent().weight << ", New vregs: ");
492 // Copy any newly inserted live intervals into the list of regs to
494 for (LiveRangeEdit::iterator itr = LRE.begin(), end = LRE.end();
496 LiveInterval &li = lis->getInterval(*itr);
497 assert(!li.empty() && "Empty spill range.");
498 DEBUG(dbgs() << PrintReg(li.reg, tri) << " ");
499 vregsToAlloc.insert(li.reg);
502 DEBUG(dbgs() << ")\n");
504 // We need another round if spill intervals were added.
505 anotherRoundNeeded |= !LRE.empty();
507 llvm_unreachable("Unknown allocation option.");
511 return !anotherRoundNeeded;
515 void RegAllocPBQP::finalizeAlloc() const {
516 // First allocate registers for the empty intervals.
517 for (RegSet::const_iterator
518 itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
520 LiveInterval *li = &lis->getInterval(*itr);
522 unsigned physReg = mri->getSimpleHint(li->reg);
525 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
526 physReg = liRC->getRawAllocationOrder(*mf).front();
529 vrm->assignVirt2Phys(li->reg, physReg);
533 bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
536 tm = &mf->getTarget();
537 tri = tm->getSubtargetImpl()->getRegisterInfo();
538 tii = tm->getSubtargetImpl()->getInstrInfo();
539 mri = &mf->getRegInfo();
541 lis = &getAnalysis<LiveIntervals>();
542 lss = &getAnalysis<LiveStacks>();
543 mbfi = &getAnalysis<MachineBlockFrequencyInfo>();
545 calculateSpillWeightsAndHints(*lis, MF, getAnalysis<MachineLoopInfo>(),
548 vrm = &getAnalysis<VirtRegMap>();
549 spiller.reset(createInlineSpiller(*this, MF, *vrm));
551 mri->freezeReservedRegs(MF);
553 DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getName() << "\n");
555 // Allocator main loop:
557 // * Map current regalloc problem to a PBQP problem
558 // * Solve the PBQP problem
559 // * Map the solution back to a register allocation
560 // * Spill if necessary
562 // This process is continued till no more spills are generated.
564 // Find the vreg intervals in need of allocation.
565 findVRegIntervalsToAlloc();
568 const Function* func = mf->getFunction();
570 func->getParent()->getModuleIdentifier() + "." +
571 func->getName().str();
574 // If there are non-empty intervals allocate them using pbqp.
575 if (!vregsToAlloc.empty()) {
577 bool pbqpAllocComplete = false;
580 while (!pbqpAllocComplete) {
581 DEBUG(dbgs() << " PBQP Regalloc round " << round << ":\n");
583 std::unique_ptr<PBQPRAProblem> problem(
584 builder->build(mf, lis, mbfi, vregsToAlloc));
587 if (pbqpDumpGraphs) {
588 std::ostringstream rs;
590 std::string graphFileName(fqn + "." + rs.str() + ".pbqpgraph");
592 raw_fd_ostream os(graphFileName.c_str(), tmp, sys::fs::F_Text);
593 DEBUG(dbgs() << "Dumping graph for round " << round << " to \""
594 << graphFileName << "\"\n");
595 problem->getGraph().dump(os);
599 PBQP::Solution solution =
600 PBQP::RegAlloc::solve(problem->getGraph());
602 pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
608 // Finalise allocation, allocate empty ranges.
610 vregsToAlloc.clear();
611 emptyIntervalVRegs.clear();
613 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
619 llvm::createPBQPRegisterAllocator(std::unique_ptr<PBQPBuilder> builder,
620 char *customPassID) {
621 return new RegAllocPBQP(std::move(builder), customPassID);
624 FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
625 std::unique_ptr<PBQPBuilder> Builder;
627 Builder = llvm::make_unique<PBQPBuilderWithCoalescing>();
629 Builder = llvm::make_unique<PBQPBuilder>();
630 return createPBQPRegisterAllocator(std::move(Builder));