blob: 690732166b28db53762d9a126a51f72f9d507fad [file] [log] [blame]
Evan Chengb1290a62008-10-02 18:29:27 +00001//===------ RegAllocPBQP.cpp ---- PBQP Register Allocator -------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Misha Brukman2a835f92009-01-08 15:50:22 +00009//
Evan Chengb1290a62008-10-02 18:29:27 +000010// 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
Misha Brukman2a835f92009-01-08 15:50:22 +000015// code is inserted and the process repeated.
Evan Chengb1290a62008-10-02 18:29:27 +000016//
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
Misha Brukmance07e992009-01-08 16:40:25 +000019// allocation, see the following papers:
Evan Chengb1290a62008-10-02 18:29:27 +000020//
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.
24//
25// (2) Scholz, B., Eckstein, E. 2002. Register allocation for irregular
26// architectures. In Proceedings of the Joint Conference on Languages,
27// Compilers and Tools for Embedded Systems (LCTES'02), ACM Press, New York,
28// NY, USA, 139-148.
Misha Brukman2a835f92009-01-08 15:50:22 +000029//
Evan Chengb1290a62008-10-02 18:29:27 +000030//===----------------------------------------------------------------------===//
31
Evan Chengb1290a62008-10-02 18:29:27 +000032#define DEBUG_TYPE "regalloc"
33
Lang Hames54cc2ef2010-07-19 15:22:28 +000034#include "RenderMachineFunction.h"
Lang Hames12f35c52010-07-18 00:57:59 +000035#include "Splitter.h"
Evan Chengb1290a62008-10-02 18:29:27 +000036#include "VirtRegMap.h"
Lang Hames87e3bca2009-05-06 02:36:21 +000037#include "VirtRegRewriter.h"
Lang Hamesa937f222009-12-14 06:49:42 +000038#include "llvm/CodeGen/CalcSpillWeights.h"
Evan Chengb1290a62008-10-02 18:29:27 +000039#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Lang Hames27601ef2008-11-16 12:12:54 +000040#include "llvm/CodeGen/LiveStackAnalysis.h"
Lang Hameseb6c8f52010-09-18 09:07:10 +000041#include "llvm/CodeGen/RegAllocPBQP.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000042#include "llvm/CodeGen/MachineFunctionPass.h"
Evan Chengb1290a62008-10-02 18:29:27 +000043#include "llvm/CodeGen/MachineLoopInfo.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000044#include "llvm/CodeGen/MachineRegisterInfo.h"
Lang Hameseb6c8f52010-09-18 09:07:10 +000045#include "llvm/CodeGen/PBQP/HeuristicSolver.h"
46#include "llvm/CodeGen/PBQP/Graph.h"
47#include "llvm/CodeGen/PBQP/Heuristics/Briggs.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000048#include "llvm/CodeGen/RegAllocRegistry.h"
49#include "llvm/CodeGen/RegisterCoalescer.h"
Evan Chengb1290a62008-10-02 18:29:27 +000050#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000051#include "llvm/Support/raw_ostream.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000052#include "llvm/Target/TargetInstrInfo.h"
53#include "llvm/Target/TargetMachine.h"
54#include <limits>
Misha Brukman2a835f92009-01-08 15:50:22 +000055#include <memory>
Evan Chengb1290a62008-10-02 18:29:27 +000056#include <set>
57#include <vector>
Evan Chengb1290a62008-10-02 18:29:27 +000058
Lang Hamesf70e7cc2010-09-23 04:28:54 +000059using namespace llvm;
Lang Hameseb6c8f52010-09-18 09:07:10 +000060
Evan Chengb1290a62008-10-02 18:29:27 +000061static RegisterRegAlloc
Duncan Sands1aecd152010-02-18 14:10:41 +000062registerPBQPRepAlloc("pbqp", "PBQP register allocator",
Lang Hamesf70e7cc2010-09-23 04:28:54 +000063 createDefaultPBQPRegisterAllocator);
Evan Chengb1290a62008-10-02 18:29:27 +000064
Lang Hames8481e3b2009-08-19 01:36:14 +000065static cl::opt<bool>
66pbqpCoalescing("pbqp-coalescing",
Lang Hames030c4bf2010-01-26 04:49:58 +000067 cl::desc("Attempt coalescing during PBQP register allocation."),
68 cl::init(false), cl::Hidden);
Lang Hames8481e3b2009-08-19 01:36:14 +000069
Lang Hames12f35c52010-07-18 00:57:59 +000070static cl::opt<bool>
71pbqpPreSplitting("pbqp-pre-splitting",
Lang Hamesf70e7cc2010-09-23 04:28:54 +000072 cl::desc("Pre-split before PBQP register allocation."),
Lang Hames12f35c52010-07-18 00:57:59 +000073 cl::init(false), cl::Hidden);
74
Lang Hamesf70e7cc2010-09-23 04:28:54 +000075namespace {
76
77///
78/// PBQP based allocators solve the register allocation problem by mapping
79/// register allocation problems to Partitioned Boolean Quadratic
80/// Programming problems.
81class RegAllocPBQP : public MachineFunctionPass {
82public:
83
84 static char ID;
85
86 /// Construct a PBQP register allocator.
87 RegAllocPBQP(std::auto_ptr<PBQPBuilder> b) : MachineFunctionPass(ID), builder(b) {}
88
89 /// Return the pass name.
90 virtual const char* getPassName() const {
91 return "PBQP Register Allocator";
92 }
93
94 /// PBQP analysis usage.
95 virtual void getAnalysisUsage(AnalysisUsage &au) const;
96
97 /// Perform register allocation
98 virtual bool runOnMachineFunction(MachineFunction &MF);
99
100private:
101
102 typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
103 typedef std::vector<const LiveInterval*> Node2LIMap;
104 typedef std::vector<unsigned> AllowedSet;
105 typedef std::vector<AllowedSet> AllowedSetMap;
106 typedef std::pair<unsigned, unsigned> RegPair;
107 typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
108 typedef std::vector<PBQP::Graph::NodeItr> NodeVector;
109 typedef std::set<unsigned> RegSet;
110
111
112 std::auto_ptr<PBQPBuilder> builder;
113
114 MachineFunction *mf;
115 const TargetMachine *tm;
116 const TargetRegisterInfo *tri;
117 const TargetInstrInfo *tii;
118 const MachineLoopInfo *loopInfo;
119 MachineRegisterInfo *mri;
120 RenderMachineFunction *rmf;
121
122 LiveIntervals *lis;
123 LiveStacks *lss;
124 VirtRegMap *vrm;
125
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000126 RegSet vregsToAlloc, emptyIntervalVRegs;
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000127
128 /// \brief Finds the initial set of vreg intervals to allocate.
129 void findVRegIntervalsToAlloc();
130
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000131 /// \brief Adds a stack interval if the given live interval has been
132 /// spilled. Used to support stack slot coloring.
133 void addStackInterval(const LiveInterval *spilled,MachineRegisterInfo* mri);
134
135 /// \brief Given a solved PBQP problem maps this solution back to a register
136 /// assignment.
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000137 bool mapPBQPToRegAlloc(const PBQPRAProblem &problem,
138 const PBQP::Solution &solution);
139
140 /// \brief Postprocessing before final spilling. Sets basic block "live in"
141 /// variables.
142 void finalizeAlloc() const;
143
144};
145
Lang Hameseb6c8f52010-09-18 09:07:10 +0000146char RegAllocPBQP::ID = 0;
Evan Chengb1290a62008-10-02 18:29:27 +0000147
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000148} // End anonymous namespace.
149
Lang Hameseb6c8f52010-09-18 09:07:10 +0000150unsigned PBQPRAProblem::getVRegForNode(PBQP::Graph::ConstNodeItr node) const {
151 Node2VReg::const_iterator vregItr = node2VReg.find(node);
152 assert(vregItr != node2VReg.end() && "No vreg for node.");
153 return vregItr->second;
154}
Evan Chengb1290a62008-10-02 18:29:27 +0000155
Lang Hameseb6c8f52010-09-18 09:07:10 +0000156PBQP::Graph::NodeItr PBQPRAProblem::getNodeForVReg(unsigned vreg) const {
157 VReg2Node::const_iterator nodeItr = vreg2Node.find(vreg);
158 assert(nodeItr != vreg2Node.end() && "No node for vreg.");
159 return nodeItr->second;
160
161}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000162
Lang Hameseb6c8f52010-09-18 09:07:10 +0000163const PBQPRAProblem::AllowedSet&
164 PBQPRAProblem::getAllowedSet(unsigned vreg) const {
165 AllowedSetMap::const_iterator allowedSetItr = allowedSets.find(vreg);
166 assert(allowedSetItr != allowedSets.end() && "No pregs for vreg.");
167 const AllowedSet &allowedSet = allowedSetItr->second;
168 return allowedSet;
169}
Evan Chengb1290a62008-10-02 18:29:27 +0000170
Lang Hameseb6c8f52010-09-18 09:07:10 +0000171unsigned PBQPRAProblem::getPRegForOption(unsigned vreg, unsigned option) const {
172 assert(isPRegOption(vreg, option) && "Not a preg option.");
173
174 const AllowedSet& allowedSet = getAllowedSet(vreg);
175 assert(option <= allowedSet.size() && "Option outside allowed set.");
176 return allowedSet[option - 1];
177}
178
Lang Hamese9c93562010-09-21 13:19:36 +0000179std::auto_ptr<PBQPRAProblem> PBQPBuilder::build(MachineFunction *mf,
180 const LiveIntervals *lis,
181 const MachineLoopInfo *loopInfo,
182 const RegSet &vregs) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000183
184 typedef std::vector<const LiveInterval*> LIVector;
185
186 MachineRegisterInfo *mri = &mf->getRegInfo();
187 const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();
188
189 std::auto_ptr<PBQPRAProblem> p(new PBQPRAProblem());
190 PBQP::Graph &g = p->getGraph();
191 RegSet pregs;
192
193 // Collect the set of preg intervals, record that they're used in the MF.
194 for (LiveIntervals::const_iterator itr = lis->begin(), end = lis->end();
195 itr != end; ++itr) {
196 if (TargetRegisterInfo::isPhysicalRegister(itr->first)) {
197 pregs.insert(itr->first);
198 mri->setPhysRegUsed(itr->first);
Evan Chengb1290a62008-10-02 18:29:27 +0000199 }
Lang Hameseb6c8f52010-09-18 09:07:10 +0000200 }
Evan Chengb1290a62008-10-02 18:29:27 +0000201
Lang Hameseb6c8f52010-09-18 09:07:10 +0000202 BitVector reservedRegs = tri->getReservedRegs(*mf);
Evan Chengb1290a62008-10-02 18:29:27 +0000203
Lang Hameseb6c8f52010-09-18 09:07:10 +0000204 // Iterate over vregs.
205 for (RegSet::const_iterator vregItr = vregs.begin(), vregEnd = vregs.end();
206 vregItr != vregEnd; ++vregItr) {
207 unsigned vreg = *vregItr;
208 const TargetRegisterClass *trc = mri->getRegClass(vreg);
209 const LiveInterval *vregLI = &lis->getInterval(vreg);
Evan Chengb1290a62008-10-02 18:29:27 +0000210
Lang Hameseb6c8f52010-09-18 09:07:10 +0000211 // Compute an initial allowed set for the current vreg.
212 typedef std::vector<unsigned> VRAllowed;
213 VRAllowed vrAllowed;
214 for (TargetRegisterClass::iterator aoItr = trc->allocation_order_begin(*mf),
215 aoEnd = trc->allocation_order_end(*mf);
216 aoItr != aoEnd; ++aoItr) {
217 unsigned preg = *aoItr;
218 if (!reservedRegs.test(preg)) {
219 vrAllowed.push_back(preg);
Lang Hamesd0f6f012010-07-17 06:31:41 +0000220 }
Lang Hameseb6c8f52010-09-18 09:07:10 +0000221 }
Lang Hamesd0f6f012010-07-17 06:31:41 +0000222
Lang Hameseb6c8f52010-09-18 09:07:10 +0000223 // Remove any physical registers which overlap.
224 for (RegSet::const_iterator pregItr = pregs.begin(),
225 pregEnd = pregs.end();
226 pregItr != pregEnd; ++pregItr) {
227 unsigned preg = *pregItr;
228 const LiveInterval *pregLI = &lis->getInterval(preg);
Lang Hames27601ef2008-11-16 12:12:54 +0000229
Lang Hameseb6c8f52010-09-18 09:07:10 +0000230 if (pregLI->empty())
231 continue;
Evan Chengb1290a62008-10-02 18:29:27 +0000232
Lang Hameseb6c8f52010-09-18 09:07:10 +0000233 if (!vregLI->overlaps(*pregLI))
234 continue;
Lang Hames030c4bf2010-01-26 04:49:58 +0000235
Lang Hameseb6c8f52010-09-18 09:07:10 +0000236 // Remove the register from the allowed set.
237 VRAllowed::iterator eraseItr =
238 std::find(vrAllowed.begin(), vrAllowed.end(), preg);
Evan Chengb1290a62008-10-02 18:29:27 +0000239
Lang Hameseb6c8f52010-09-18 09:07:10 +0000240 if (eraseItr != vrAllowed.end()) {
241 vrAllowed.erase(eraseItr);
242 }
Evan Chengb1290a62008-10-02 18:29:27 +0000243
Lang Hameseb6c8f52010-09-18 09:07:10 +0000244 // Also remove any aliases.
245 const unsigned *aliasItr = tri->getAliasSet(preg);
246 if (aliasItr != 0) {
247 for (; *aliasItr != 0; ++aliasItr) {
248 VRAllowed::iterator eraseItr =
249 std::find(vrAllowed.begin(), vrAllowed.end(), *aliasItr);
Evan Chengb1290a62008-10-02 18:29:27 +0000250
Lang Hameseb6c8f52010-09-18 09:07:10 +0000251 if (eraseItr != vrAllowed.end()) {
252 vrAllowed.erase(eraseItr);
253 }
254 }
255 }
256 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000257
Lang Hameseb6c8f52010-09-18 09:07:10 +0000258 // Construct the node.
259 PBQP::Graph::NodeItr node =
260 g.addNode(PBQP::Vector(vrAllowed.size() + 1, 0));
Evan Chengb1290a62008-10-02 18:29:27 +0000261
Lang Hameseb6c8f52010-09-18 09:07:10 +0000262 // Record the mapping and allowed set in the problem.
263 p->recordVReg(vreg, node, vrAllowed.begin(), vrAllowed.end());
Evan Chengb1290a62008-10-02 18:29:27 +0000264
Lang Hameseb6c8f52010-09-18 09:07:10 +0000265 PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
266 vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
Evan Chengb1290a62008-10-02 18:29:27 +0000267
Lang Hameseb6c8f52010-09-18 09:07:10 +0000268 addSpillCosts(g.getNodeCosts(node), spillCost);
269 }
Evan Chengb1290a62008-10-02 18:29:27 +0000270
Lang Hames481630d2010-09-18 09:49:08 +0000271 for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000272 vr1Itr != vrEnd; ++vr1Itr) {
273 unsigned vr1 = *vr1Itr;
274 const LiveInterval &l1 = lis->getInterval(vr1);
275 const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
Evan Chengb1290a62008-10-02 18:29:27 +0000276
Benjamin Kramer9e8d1f92010-09-18 14:41:26 +0000277 for (RegSet::const_iterator vr2Itr = llvm::next(vr1Itr);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000278 vr2Itr != vrEnd; ++vr2Itr) {
279 unsigned vr2 = *vr2Itr;
280 const LiveInterval &l2 = lis->getInterval(vr2);
281 const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
Evan Chengb1290a62008-10-02 18:29:27 +0000282
Lang Hameseb6c8f52010-09-18 09:07:10 +0000283 assert(!l2.empty() && "Empty interval in vreg set?");
284 if (l1.overlaps(l2)) {
285 PBQP::Graph::EdgeItr edge =
286 g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
287 PBQP::Matrix(vr1Allowed.size()+1, vr2Allowed.size()+1, 0));
Lang Hames27601ef2008-11-16 12:12:54 +0000288
Lang Hameseb6c8f52010-09-18 09:07:10 +0000289 addInterferenceCosts(g.getEdgeCosts(edge), vr1Allowed, vr2Allowed, tri);
290 }
291 }
292 }
Evan Chengb1290a62008-10-02 18:29:27 +0000293
Lang Hameseb6c8f52010-09-18 09:07:10 +0000294 return p;
295}
Lang Hames27601ef2008-11-16 12:12:54 +0000296
Lang Hameseb6c8f52010-09-18 09:07:10 +0000297void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
298 PBQP::PBQPNum spillCost) {
299 costVec[0] = spillCost;
300}
Evan Chengb1290a62008-10-02 18:29:27 +0000301
Lang Hamese9c93562010-09-21 13:19:36 +0000302void PBQPBuilder::addInterferenceCosts(
303 PBQP::Matrix &costMat,
304 const PBQPRAProblem::AllowedSet &vr1Allowed,
305 const PBQPRAProblem::AllowedSet &vr2Allowed,
306 const TargetRegisterInfo *tri) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000307 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
308 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
309
310 for (unsigned i = 0; i < vr1Allowed.size(); ++i) {
311 unsigned preg1 = vr1Allowed[i];
312
313 for (unsigned j = 0; j < vr2Allowed.size(); ++j) {
314 unsigned preg2 = vr2Allowed[j];
315
316 if (tri->regsOverlap(preg1, preg2)) {
317 costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
318 }
319 }
320 }
Evan Chengb1290a62008-10-02 18:29:27 +0000321}
322
Lang Hamese9c93562010-09-21 13:19:36 +0000323std::auto_ptr<PBQPRAProblem> PBQPBuilderWithCoalescing::build(
324 MachineFunction *mf,
325 const LiveIntervals *lis,
326 const MachineLoopInfo *loopInfo,
327 const RegSet &vregs) {
328
329 std::auto_ptr<PBQPRAProblem> p = PBQPBuilder::build(mf, lis, loopInfo, vregs);
330 PBQP::Graph &g = p->getGraph();
331
332 const TargetMachine &tm = mf->getTarget();
333 CoalescerPair cp(*tm.getInstrInfo(), *tm.getRegisterInfo());
334
335 // Scan the machine function and add a coalescing cost whenever CoalescerPair
336 // gives the Ok.
337 for (MachineFunction::const_iterator mbbItr = mf->begin(),
338 mbbEnd = mf->end();
339 mbbItr != mbbEnd; ++mbbItr) {
340 const MachineBasicBlock *mbb = &*mbbItr;
341
342 for (MachineBasicBlock::const_iterator miItr = mbb->begin(),
343 miEnd = mbb->end();
344 miItr != miEnd; ++miItr) {
345 const MachineInstr *mi = &*miItr;
346
Lang Hamese9c93562010-09-21 13:19:36 +0000347 if (!cp.setRegisters(mi))
348 continue; // Not coalescable.
349
350 if (cp.getSrcReg() == cp.getDstReg())
351 continue; // Already coalesced.
352
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000353 unsigned dst = cp.getDstReg(),
354 src = cp.getSrcReg();
Lang Hamese9c93562010-09-21 13:19:36 +0000355
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000356 const float copyFactor = 0.5; // Cost of copy relative to load. Current
357 // value plucked randomly out of the air.
358
359 PBQP::PBQPNum cBenefit =
360 copyFactor * LiveIntervals::getSpillWeight(false, true,
361 loopInfo->getLoopDepth(mbb));
Lang Hamese9c93562010-09-21 13:19:36 +0000362
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000363 if (cp.isPhys()) {
364 if (!lis->isAllocatable(dst))
365 continue;
Lang Hamese9c93562010-09-21 13:19:36 +0000366
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000367 const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
368 unsigned pregOpt = 0;
369 while (pregOpt < allowed.size() && allowed[pregOpt] != dst)
370 ++pregOpt;
371 if (pregOpt < allowed.size()) {
372 ++pregOpt; // +1 to account for spill option.
373 PBQP::Graph::NodeItr node = p->getNodeForVReg(src);
374 addPhysRegCoalesce(g.getNodeCosts(node), pregOpt, cBenefit);
Lang Hamese9c93562010-09-21 13:19:36 +0000375 }
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000376 } else {
377 const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
378 const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
379 PBQP::Graph::NodeItr node1 = p->getNodeForVReg(dst);
380 PBQP::Graph::NodeItr node2 = p->getNodeForVReg(src);
381 PBQP::Graph::EdgeItr edge = g.findEdge(node1, node2);
382 if (edge == g.edgesEnd()) {
383 edge = g.addEdge(node1, node2, PBQP::Matrix(allowed1->size() + 1,
384 allowed2->size() + 1,
385 0));
386 } else {
387 if (g.getEdgeNode1(edge) == node2) {
388 std::swap(node1, node2);
389 std::swap(allowed1, allowed2);
390 }
391 }
392
393 addVirtRegCoalesce(g.getEdgeCosts(edge), *allowed1, *allowed2,
394 cBenefit);
Lang Hamese9c93562010-09-21 13:19:36 +0000395 }
396 }
397 }
398
399 return p;
400}
401
Lang Hamese9c93562010-09-21 13:19:36 +0000402void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
403 unsigned pregOption,
404 PBQP::PBQPNum benefit) {
405 costVec[pregOption] += -benefit;
406}
407
408void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
409 PBQP::Matrix &costMat,
410 const PBQPRAProblem::AllowedSet &vr1Allowed,
411 const PBQPRAProblem::AllowedSet &vr2Allowed,
412 PBQP::PBQPNum benefit) {
413
414 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
415 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
416
417 for (unsigned i = 0; i < vr1Allowed.size(); ++i) {
418 unsigned preg1 = vr1Allowed[i];
419 for (unsigned j = 0; j < vr2Allowed.size(); ++j) {
420 unsigned preg2 = vr2Allowed[j];
421
422 if (preg1 == preg2) {
423 costMat[i + 1][j + 1] += -benefit;
424 }
425 }
426 }
427}
Evan Chengb1290a62008-10-02 18:29:27 +0000428
Lang Hameseb6c8f52010-09-18 09:07:10 +0000429
430void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
431 au.addRequired<SlotIndexes>();
432 au.addPreserved<SlotIndexes>();
433 au.addRequired<LiveIntervals>();
434 //au.addRequiredID(SplitCriticalEdgesID);
435 au.addRequired<RegisterCoalescer>();
436 au.addRequired<CalculateSpillWeights>();
437 au.addRequired<LiveStacks>();
438 au.addPreserved<LiveStacks>();
439 au.addRequired<MachineLoopInfo>();
440 au.addPreserved<MachineLoopInfo>();
441 if (pbqpPreSplitting)
442 au.addRequired<LoopSplitter>();
443 au.addRequired<VirtRegMap>();
444 au.addRequired<RenderMachineFunction>();
445 MachineFunctionPass::getAnalysisUsage(au);
446}
447
Lang Hameseb6c8f52010-09-18 09:07:10 +0000448void RegAllocPBQP::findVRegIntervalsToAlloc() {
Lang Hames27601ef2008-11-16 12:12:54 +0000449
450 // Iterate over all live ranges.
451 for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
452 itr != end; ++itr) {
453
454 // Ignore physical ones.
455 if (TargetRegisterInfo::isPhysicalRegister(itr->first))
456 continue;
457
458 LiveInterval *li = itr->second;
459
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
462 // finalizeAlloc.
463 if (!li->empty()) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000464 vregsToAlloc.insert(li->reg);
Lang Hames27601ef2008-11-16 12:12:54 +0000465 }
466 else {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000467 emptyIntervalVRegs.insert(li->reg);
Lang Hames27601ef2008-11-16 12:12:54 +0000468 }
469 }
Evan Chengb1290a62008-10-02 18:29:27 +0000470}
471
Lang Hameseb6c8f52010-09-18 09:07:10 +0000472void RegAllocPBQP::addStackInterval(const LiveInterval *spilled,
Evan Chengc781a242009-05-03 18:32:42 +0000473 MachineRegisterInfo* mri) {
Lang Hames27601ef2008-11-16 12:12:54 +0000474 int stackSlot = vrm->getStackSlot(spilled->reg);
Misha Brukman2a835f92009-01-08 15:50:22 +0000475
476 if (stackSlot == VirtRegMap::NO_STACK_SLOT)
Lang Hames27601ef2008-11-16 12:12:54 +0000477 return;
478
Evan Chengc781a242009-05-03 18:32:42 +0000479 const TargetRegisterClass *RC = mri->getRegClass(spilled->reg);
480 LiveInterval &stackInterval = lss->getOrCreateInterval(stackSlot, RC);
Lang Hames27601ef2008-11-16 12:12:54 +0000481
482 VNInfo *vni;
483 if (stackInterval.getNumValNums() != 0)
484 vni = stackInterval.getValNumInfo(0);
485 else
Lang Hames86511252009-09-04 20:41:11 +0000486 vni = stackInterval.getNextValue(
Lang Hames6e2968c2010-09-25 12:04:16 +0000487 SlotIndex(), 0, lss->getVNInfoAllocator());
Lang Hames27601ef2008-11-16 12:12:54 +0000488
489 LiveInterval &rhsInterval = lis->getInterval(spilled->reg);
490 stackInterval.MergeRangesInAsValue(rhsInterval, vni);
491}
492
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000493bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
494 const PBQP::Solution &solution) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000495 // Set to true if we have any spills
496 bool anotherRoundNeeded = false;
497
498 // Clear the existing allocation.
499 vrm->clearAllVirt();
500
501 const PBQP::Graph &g = problem.getGraph();
502 // Iterate over the nodes mapping the PBQP solution to a register
503 // assignment.
504 for (PBQP::Graph::ConstNodeItr node = g.nodesBegin(),
505 nodeEnd = g.nodesEnd();
506 node != nodeEnd; ++node) {
507 unsigned vreg = problem.getVRegForNode(node);
508 unsigned alloc = solution.getSelection(node);
509
510 if (problem.isPRegOption(vreg, alloc)) {
511 unsigned preg = problem.getPRegForOption(vreg, alloc);
512 DEBUG(dbgs() << "VREG " << vreg << " -> " << tri->getName(preg) << "\n");
513 assert(preg != 0 && "Invalid preg selected.");
514 vrm->assignVirt2Phys(vreg, preg);
515 } else if (problem.isSpillOption(vreg, alloc)) {
516 vregsToAlloc.erase(vreg);
517 const LiveInterval* spillInterval = &lis->getInterval(vreg);
518 double oldWeight = spillInterval->weight;
519 SmallVector<LiveInterval*, 8> spillIs;
520 rmf->rememberUseDefs(spillInterval);
521 std::vector<LiveInterval*> newSpills =
522 lis->addIntervalsForSpills(*spillInterval, spillIs, loopInfo, *vrm);
523 addStackInterval(spillInterval, mri);
524 rmf->rememberSpills(spillInterval, newSpills);
525
526 (void) oldWeight;
527 DEBUG(dbgs() << "VREG " << vreg << " -> SPILLED (Cost: "
528 << oldWeight << ", New vregs: ");
529
530 // Copy any newly inserted live intervals into the list of regs to
531 // allocate.
532 for (std::vector<LiveInterval*>::const_iterator
533 itr = newSpills.begin(), end = newSpills.end();
534 itr != end; ++itr) {
535 assert(!(*itr)->empty() && "Empty spill range.");
536 DEBUG(dbgs() << (*itr)->reg << " ");
537 vregsToAlloc.insert((*itr)->reg);
538 }
539
540 DEBUG(dbgs() << ")\n");
541
542 // We need another round if spill intervals were added.
543 anotherRoundNeeded |= !newSpills.empty();
544 } else {
545 assert(false && "Unknown allocation option.");
546 }
547 }
548
549 return !anotherRoundNeeded;
550}
551
552
553void RegAllocPBQP::finalizeAlloc() const {
Lang Hames27601ef2008-11-16 12:12:54 +0000554 typedef LiveIntervals::iterator LIIterator;
555 typedef LiveInterval::Ranges::const_iterator LRIterator;
556
557 // First allocate registers for the empty intervals.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000558 for (RegSet::const_iterator
559 itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
Lang Hames27601ef2008-11-16 12:12:54 +0000560 itr != end; ++itr) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000561 LiveInterval *li = &lis->getInterval(*itr);
Lang Hames27601ef2008-11-16 12:12:54 +0000562
Evan Cheng90f95f82009-06-14 20:22:55 +0000563 unsigned physReg = vrm->getRegAllocPref(li->reg);
Lang Hames6699fb22009-08-06 23:32:48 +0000564
Lang Hames27601ef2008-11-16 12:12:54 +0000565 if (physReg == 0) {
566 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
Misha Brukman2a835f92009-01-08 15:50:22 +0000567 physReg = *liRC->allocation_order_begin(*mf);
Lang Hames27601ef2008-11-16 12:12:54 +0000568 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000569
570 vrm->assignVirt2Phys(li->reg, physReg);
Lang Hames27601ef2008-11-16 12:12:54 +0000571 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000572
Lang Hames27601ef2008-11-16 12:12:54 +0000573 // Finally iterate over the basic blocks to compute and set the live-in sets.
574 SmallVector<MachineBasicBlock*, 8> liveInMBBs;
575 MachineBasicBlock *entryMBB = &*mf->begin();
576
577 for (LIIterator liItr = lis->begin(), liEnd = lis->end();
578 liItr != liEnd; ++liItr) {
579
580 const LiveInterval *li = liItr->second;
581 unsigned reg = 0;
Misha Brukman2a835f92009-01-08 15:50:22 +0000582
Lang Hames27601ef2008-11-16 12:12:54 +0000583 // Get the physical register for this interval
584 if (TargetRegisterInfo::isPhysicalRegister(li->reg)) {
585 reg = li->reg;
586 }
587 else if (vrm->isAssignedReg(li->reg)) {
588 reg = vrm->getPhys(li->reg);
589 }
590 else {
591 // Ranges which are assigned a stack slot only are ignored.
592 continue;
593 }
594
Lang Hamesb0e519f2009-05-17 23:50:36 +0000595 if (reg == 0) {
Lang Hames6699fb22009-08-06 23:32:48 +0000596 // Filter out zero regs - they're for intervals that were spilled.
Lang Hamesb0e519f2009-05-17 23:50:36 +0000597 continue;
598 }
599
Lang Hames27601ef2008-11-16 12:12:54 +0000600 // Iterate over the ranges of the current interval...
601 for (LRIterator lrItr = li->begin(), lrEnd = li->end();
602 lrItr != lrEnd; ++lrItr) {
Misha Brukman2a835f92009-01-08 15:50:22 +0000603
Lang Hames27601ef2008-11-16 12:12:54 +0000604 // Find the set of basic blocks which this range is live into...
605 if (lis->findLiveInMBBs(lrItr->start, lrItr->end, liveInMBBs)) {
606 // And add the physreg for this interval to their live-in sets.
607 for (unsigned i = 0; i < liveInMBBs.size(); ++i) {
608 if (liveInMBBs[i] != entryMBB) {
609 if (!liveInMBBs[i]->isLiveIn(reg)) {
610 liveInMBBs[i]->addLiveIn(reg);
611 }
612 }
613 }
614 liveInMBBs.clear();
615 }
616 }
617 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000618
Lang Hames27601ef2008-11-16 12:12:54 +0000619}
620
Lang Hameseb6c8f52010-09-18 09:07:10 +0000621bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
Lang Hames27601ef2008-11-16 12:12:54 +0000622
Evan Chengb1290a62008-10-02 18:29:27 +0000623 mf = &MF;
624 tm = &mf->getTarget();
625 tri = tm->getRegisterInfo();
Lang Hames27601ef2008-11-16 12:12:54 +0000626 tii = tm->getInstrInfo();
Lang Hames233a60e2009-11-03 23:52:08 +0000627 mri = &mf->getRegInfo();
Evan Chengb1290a62008-10-02 18:29:27 +0000628
Lang Hames27601ef2008-11-16 12:12:54 +0000629 lis = &getAnalysis<LiveIntervals>();
630 lss = &getAnalysis<LiveStacks>();
Evan Chengb1290a62008-10-02 18:29:27 +0000631 loopInfo = &getAnalysis<MachineLoopInfo>();
Lang Hames33198392010-09-02 08:27:00 +0000632 rmf = &getAnalysis<RenderMachineFunction>();
Evan Chengb1290a62008-10-02 18:29:27 +0000633
Owen Anderson49c8aa02009-03-13 05:55:11 +0000634 vrm = &getAnalysis<VirtRegMap>();
Evan Chengb1290a62008-10-02 18:29:27 +0000635
Lang Hames54cc2ef2010-07-19 15:22:28 +0000636
Lang Hames030c4bf2010-01-26 04:49:58 +0000637 DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getFunction()->getName() << "\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000638
Evan Chengb1290a62008-10-02 18:29:27 +0000639 // Allocator main loop:
Misha Brukman2a835f92009-01-08 15:50:22 +0000640 //
Evan Chengb1290a62008-10-02 18:29:27 +0000641 // * Map current regalloc problem to a PBQP problem
642 // * Solve the PBQP problem
643 // * Map the solution back to a register allocation
644 // * Spill if necessary
Misha Brukman2a835f92009-01-08 15:50:22 +0000645 //
Evan Chengb1290a62008-10-02 18:29:27 +0000646 // This process is continued till no more spills are generated.
647
Lang Hames27601ef2008-11-16 12:12:54 +0000648 // Find the vreg intervals in need of allocation.
649 findVRegIntervalsToAlloc();
Misha Brukman2a835f92009-01-08 15:50:22 +0000650
Lang Hames27601ef2008-11-16 12:12:54 +0000651 // If there are non-empty intervals allocate them using pbqp.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000652 if (!vregsToAlloc.empty()) {
Evan Chengb1290a62008-10-02 18:29:27 +0000653
Lang Hames27601ef2008-11-16 12:12:54 +0000654 bool pbqpAllocComplete = false;
655 unsigned round = 0;
656
Lang Hamesab62b7e2010-10-04 12:13:07 +0000657 while (!pbqpAllocComplete) {
658 DEBUG(dbgs() << " PBQP Regalloc round " << round << ":\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000659
Lang Hamesab62b7e2010-10-04 12:13:07 +0000660 std::auto_ptr<PBQPRAProblem> problem =
661 builder->build(mf, lis, loopInfo, vregsToAlloc);
662 PBQP::Solution solution =
663 PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(
664 problem->getGraph());
Lang Hames233fd9c2009-08-18 23:34:50 +0000665
Lang Hamesab62b7e2010-10-04 12:13:07 +0000666 pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
Lang Hames27601ef2008-11-16 12:12:54 +0000667
Lang Hamesab62b7e2010-10-04 12:13:07 +0000668 ++round;
Lang Hames27601ef2008-11-16 12:12:54 +0000669 }
Evan Chengb1290a62008-10-02 18:29:27 +0000670 }
671
Lang Hames27601ef2008-11-16 12:12:54 +0000672 // Finalise allocation, allocate empty ranges.
673 finalizeAlloc();
Evan Chengb1290a62008-10-02 18:29:27 +0000674
Lang Hamesc4bcc772010-07-20 07:41:44 +0000675 rmf->renderMachineFunction("After PBQP register allocation.", vrm);
676
Lang Hameseb6c8f52010-09-18 09:07:10 +0000677 vregsToAlloc.clear();
678 emptyIntervalVRegs.clear();
Lang Hames27601ef2008-11-16 12:12:54 +0000679
David Greene30931542010-01-05 01:25:43 +0000680 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000681
Lang Hames87e3bca2009-05-06 02:36:21 +0000682 // Run rewriter
683 std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
684
685 rewriter->runOnMachineFunction(*mf, *vrm, lis);
Lang Hames27601ef2008-11-16 12:12:54 +0000686
Misha Brukman2a835f92009-01-08 15:50:22 +0000687 return true;
Evan Chengb1290a62008-10-02 18:29:27 +0000688}
689
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000690FunctionPass* llvm::createPBQPRegisterAllocator(
691 std::auto_ptr<PBQPBuilder> builder) {
692 return new RegAllocPBQP(builder);
Evan Chengb1290a62008-10-02 18:29:27 +0000693}
694
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000695FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
696 if (pbqpCoalescing) {
697 return createPBQPRegisterAllocator(
698 std::auto_ptr<PBQPBuilder>(new PBQPBuilderWithCoalescing()));
699 } // else
700 return createPBQPRegisterAllocator(
701 std::auto_ptr<PBQPBuilder>(new PBQPBuilder()));
Lang Hameseb6c8f52010-09-18 09:07:10 +0000702}
Evan Chengb1290a62008-10-02 18:29:27 +0000703
704#undef DEBUG_TYPE