blob: 605507f014d6d75e39162f05d9443592bcb009a6 [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.
Owen Anderson081c34b2010-10-19 17:21:58 +000087 RegAllocPBQP(std::auto_ptr<PBQPBuilder> b)
88 : MachineFunctionPass(ID), builder(b) {
89 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
90 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
91 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
92 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
93 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
94 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
95 initializeLoopSplitterPass(*PassRegistry::getPassRegistry());
96 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
97 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
98 }
Lang Hamesf70e7cc2010-09-23 04:28:54 +000099
100 /// Return the pass name.
101 virtual const char* getPassName() const {
102 return "PBQP Register Allocator";
103 }
104
105 /// PBQP analysis usage.
106 virtual void getAnalysisUsage(AnalysisUsage &au) const;
107
108 /// Perform register allocation
109 virtual bool runOnMachineFunction(MachineFunction &MF);
110
111private:
112
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::vector<PBQP::Graph::NodeItr> NodeVector;
120 typedef std::set<unsigned> RegSet;
121
122
123 std::auto_ptr<PBQPBuilder> builder;
124
125 MachineFunction *mf;
126 const TargetMachine *tm;
127 const TargetRegisterInfo *tri;
128 const TargetInstrInfo *tii;
129 const MachineLoopInfo *loopInfo;
130 MachineRegisterInfo *mri;
131 RenderMachineFunction *rmf;
132
133 LiveIntervals *lis;
134 LiveStacks *lss;
135 VirtRegMap *vrm;
136
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000137 RegSet vregsToAlloc, emptyIntervalVRegs;
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000138
139 /// \brief Finds the initial set of vreg intervals to allocate.
140 void findVRegIntervalsToAlloc();
141
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000142 /// \brief Adds a stack interval if the given live interval has been
143 /// spilled. Used to support stack slot coloring.
144 void addStackInterval(const LiveInterval *spilled,MachineRegisterInfo* mri);
145
146 /// \brief Given a solved PBQP problem maps this solution back to a register
147 /// assignment.
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000148 bool mapPBQPToRegAlloc(const PBQPRAProblem &problem,
149 const PBQP::Solution &solution);
150
151 /// \brief Postprocessing before final spilling. Sets basic block "live in"
152 /// variables.
153 void finalizeAlloc() const;
154
155};
156
Lang Hameseb6c8f52010-09-18 09:07:10 +0000157char RegAllocPBQP::ID = 0;
Evan Chengb1290a62008-10-02 18:29:27 +0000158
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000159} // End anonymous namespace.
160
Lang Hameseb6c8f52010-09-18 09:07:10 +0000161unsigned 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;
165}
Evan Chengb1290a62008-10-02 18:29:27 +0000166
Lang Hameseb6c8f52010-09-18 09:07:10 +0000167PBQP::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;
171
172}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000173
Lang Hameseb6c8f52010-09-18 09:07:10 +0000174const 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;
179 return allowedSet;
180}
Evan Chengb1290a62008-10-02 18:29:27 +0000181
Lang Hameseb6c8f52010-09-18 09:07:10 +0000182unsigned PBQPRAProblem::getPRegForOption(unsigned vreg, unsigned option) const {
183 assert(isPRegOption(vreg, option) && "Not a preg option.");
184
185 const AllowedSet& allowedSet = getAllowedSet(vreg);
186 assert(option <= allowedSet.size() && "Option outside allowed set.");
187 return allowedSet[option - 1];
188}
189
Lang Hamese9c93562010-09-21 13:19:36 +0000190std::auto_ptr<PBQPRAProblem> PBQPBuilder::build(MachineFunction *mf,
191 const LiveIntervals *lis,
192 const MachineLoopInfo *loopInfo,
193 const RegSet &vregs) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000194
195 typedef std::vector<const LiveInterval*> LIVector;
196
197 MachineRegisterInfo *mri = &mf->getRegInfo();
198 const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();
199
200 std::auto_ptr<PBQPRAProblem> p(new PBQPRAProblem());
201 PBQP::Graph &g = p->getGraph();
202 RegSet pregs;
203
204 // Collect the set of preg intervals, record that they're used in the MF.
205 for (LiveIntervals::const_iterator itr = lis->begin(), end = lis->end();
206 itr != end; ++itr) {
207 if (TargetRegisterInfo::isPhysicalRegister(itr->first)) {
208 pregs.insert(itr->first);
209 mri->setPhysRegUsed(itr->first);
Evan Chengb1290a62008-10-02 18:29:27 +0000210 }
Lang Hameseb6c8f52010-09-18 09:07:10 +0000211 }
Evan Chengb1290a62008-10-02 18:29:27 +0000212
Lang Hameseb6c8f52010-09-18 09:07:10 +0000213 BitVector reservedRegs = tri->getReservedRegs(*mf);
Evan Chengb1290a62008-10-02 18:29:27 +0000214
Lang Hameseb6c8f52010-09-18 09:07:10 +0000215 // Iterate over vregs.
216 for (RegSet::const_iterator vregItr = vregs.begin(), vregEnd = vregs.end();
217 vregItr != vregEnd; ++vregItr) {
218 unsigned vreg = *vregItr;
219 const TargetRegisterClass *trc = mri->getRegClass(vreg);
220 const LiveInterval *vregLI = &lis->getInterval(vreg);
Evan Chengb1290a62008-10-02 18:29:27 +0000221
Lang Hameseb6c8f52010-09-18 09:07:10 +0000222 // Compute an initial allowed set for the current vreg.
223 typedef std::vector<unsigned> VRAllowed;
224 VRAllowed vrAllowed;
Jakob Stoklund Olesen714c0eb2011-06-16 20:37:45 +0000225 ArrayRef<unsigned> rawOrder = trc->getRawAllocationOrder(*mf);
226 for (unsigned i = 0; i != rawOrder.size(); ++i) {
227 unsigned preg = rawOrder[i];
Lang Hameseb6c8f52010-09-18 09:07:10 +0000228 if (!reservedRegs.test(preg)) {
229 vrAllowed.push_back(preg);
Lang Hamesd0f6f012010-07-17 06:31:41 +0000230 }
Lang Hameseb6c8f52010-09-18 09:07:10 +0000231 }
Lang Hamesd0f6f012010-07-17 06:31:41 +0000232
Lang Hameseb6c8f52010-09-18 09:07:10 +0000233 // Remove any physical registers which overlap.
234 for (RegSet::const_iterator pregItr = pregs.begin(),
235 pregEnd = pregs.end();
236 pregItr != pregEnd; ++pregItr) {
237 unsigned preg = *pregItr;
238 const LiveInterval *pregLI = &lis->getInterval(preg);
Lang Hames27601ef2008-11-16 12:12:54 +0000239
Lang Hames5e77f4b2010-11-12 05:47:21 +0000240 if (pregLI->empty()) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000241 continue;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000242 }
Evan Chengb1290a62008-10-02 18:29:27 +0000243
Lang Hames5e77f4b2010-11-12 05:47:21 +0000244 if (!vregLI->overlaps(*pregLI)) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000245 continue;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000246 }
Lang Hames030c4bf2010-01-26 04:49:58 +0000247
Lang Hameseb6c8f52010-09-18 09:07:10 +0000248 // Remove the register from the allowed set.
249 VRAllowed::iterator eraseItr =
250 std::find(vrAllowed.begin(), vrAllowed.end(), preg);
Evan Chengb1290a62008-10-02 18:29:27 +0000251
Lang Hameseb6c8f52010-09-18 09:07:10 +0000252 if (eraseItr != vrAllowed.end()) {
253 vrAllowed.erase(eraseItr);
254 }
Evan Chengb1290a62008-10-02 18:29:27 +0000255
Lang Hameseb6c8f52010-09-18 09:07:10 +0000256 // Also remove any aliases.
257 const unsigned *aliasItr = tri->getAliasSet(preg);
258 if (aliasItr != 0) {
259 for (; *aliasItr != 0; ++aliasItr) {
260 VRAllowed::iterator eraseItr =
261 std::find(vrAllowed.begin(), vrAllowed.end(), *aliasItr);
Evan Chengb1290a62008-10-02 18:29:27 +0000262
Lang Hameseb6c8f52010-09-18 09:07:10 +0000263 if (eraseItr != vrAllowed.end()) {
264 vrAllowed.erase(eraseItr);
265 }
266 }
267 }
268 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000269
Lang Hameseb6c8f52010-09-18 09:07:10 +0000270 // Construct the node.
271 PBQP::Graph::NodeItr node =
272 g.addNode(PBQP::Vector(vrAllowed.size() + 1, 0));
Evan Chengb1290a62008-10-02 18:29:27 +0000273
Lang Hameseb6c8f52010-09-18 09:07:10 +0000274 // Record the mapping and allowed set in the problem.
275 p->recordVReg(vreg, node, vrAllowed.begin(), vrAllowed.end());
Evan Chengb1290a62008-10-02 18:29:27 +0000276
Lang Hameseb6c8f52010-09-18 09:07:10 +0000277 PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
278 vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
Evan Chengb1290a62008-10-02 18:29:27 +0000279
Lang Hameseb6c8f52010-09-18 09:07:10 +0000280 addSpillCosts(g.getNodeCosts(node), spillCost);
281 }
Evan Chengb1290a62008-10-02 18:29:27 +0000282
Lang Hames481630d2010-09-18 09:49:08 +0000283 for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000284 vr1Itr != vrEnd; ++vr1Itr) {
285 unsigned vr1 = *vr1Itr;
286 const LiveInterval &l1 = lis->getInterval(vr1);
287 const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
Evan Chengb1290a62008-10-02 18:29:27 +0000288
Benjamin Kramer9e8d1f92010-09-18 14:41:26 +0000289 for (RegSet::const_iterator vr2Itr = llvm::next(vr1Itr);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000290 vr2Itr != vrEnd; ++vr2Itr) {
291 unsigned vr2 = *vr2Itr;
292 const LiveInterval &l2 = lis->getInterval(vr2);
293 const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
Evan Chengb1290a62008-10-02 18:29:27 +0000294
Lang Hameseb6c8f52010-09-18 09:07:10 +0000295 assert(!l2.empty() && "Empty interval in vreg set?");
296 if (l1.overlaps(l2)) {
297 PBQP::Graph::EdgeItr edge =
298 g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
299 PBQP::Matrix(vr1Allowed.size()+1, vr2Allowed.size()+1, 0));
Lang Hames27601ef2008-11-16 12:12:54 +0000300
Lang Hameseb6c8f52010-09-18 09:07:10 +0000301 addInterferenceCosts(g.getEdgeCosts(edge), vr1Allowed, vr2Allowed, tri);
302 }
303 }
304 }
Evan Chengb1290a62008-10-02 18:29:27 +0000305
Lang Hameseb6c8f52010-09-18 09:07:10 +0000306 return p;
307}
Lang Hames27601ef2008-11-16 12:12:54 +0000308
Lang Hameseb6c8f52010-09-18 09:07:10 +0000309void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
310 PBQP::PBQPNum spillCost) {
311 costVec[0] = spillCost;
312}
Evan Chengb1290a62008-10-02 18:29:27 +0000313
Lang Hamese9c93562010-09-21 13:19:36 +0000314void PBQPBuilder::addInterferenceCosts(
315 PBQP::Matrix &costMat,
316 const PBQPRAProblem::AllowedSet &vr1Allowed,
317 const PBQPRAProblem::AllowedSet &vr2Allowed,
318 const TargetRegisterInfo *tri) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000319 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
320 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
321
Lang Hames5e77f4b2010-11-12 05:47:21 +0000322 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000323 unsigned preg1 = vr1Allowed[i];
324
Lang Hames5e77f4b2010-11-12 05:47:21 +0000325 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000326 unsigned preg2 = vr2Allowed[j];
327
328 if (tri->regsOverlap(preg1, preg2)) {
329 costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
330 }
331 }
332 }
Evan Chengb1290a62008-10-02 18:29:27 +0000333}
334
Lang Hamese9c93562010-09-21 13:19:36 +0000335std::auto_ptr<PBQPRAProblem> PBQPBuilderWithCoalescing::build(
336 MachineFunction *mf,
337 const LiveIntervals *lis,
338 const MachineLoopInfo *loopInfo,
339 const RegSet &vregs) {
340
341 std::auto_ptr<PBQPRAProblem> p = PBQPBuilder::build(mf, lis, loopInfo, vregs);
342 PBQP::Graph &g = p->getGraph();
343
344 const TargetMachine &tm = mf->getTarget();
345 CoalescerPair cp(*tm.getInstrInfo(), *tm.getRegisterInfo());
346
347 // Scan the machine function and add a coalescing cost whenever CoalescerPair
348 // gives the Ok.
349 for (MachineFunction::const_iterator mbbItr = mf->begin(),
350 mbbEnd = mf->end();
351 mbbItr != mbbEnd; ++mbbItr) {
352 const MachineBasicBlock *mbb = &*mbbItr;
353
354 for (MachineBasicBlock::const_iterator miItr = mbb->begin(),
355 miEnd = mbb->end();
356 miItr != miEnd; ++miItr) {
357 const MachineInstr *mi = &*miItr;
358
Lang Hames5e77f4b2010-11-12 05:47:21 +0000359 if (!cp.setRegisters(mi)) {
Lang Hamese9c93562010-09-21 13:19:36 +0000360 continue; // Not coalescable.
Lang Hames5e77f4b2010-11-12 05:47:21 +0000361 }
Lang Hamese9c93562010-09-21 13:19:36 +0000362
Lang Hames5e77f4b2010-11-12 05:47:21 +0000363 if (cp.getSrcReg() == cp.getDstReg()) {
Lang Hamese9c93562010-09-21 13:19:36 +0000364 continue; // Already coalesced.
Lang Hames5e77f4b2010-11-12 05:47:21 +0000365 }
Lang Hamese9c93562010-09-21 13:19:36 +0000366
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000367 unsigned dst = cp.getDstReg(),
368 src = cp.getSrcReg();
Lang Hamese9c93562010-09-21 13:19:36 +0000369
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000370 const float copyFactor = 0.5; // Cost of copy relative to load. Current
371 // value plucked randomly out of the air.
372
373 PBQP::PBQPNum cBenefit =
374 copyFactor * LiveIntervals::getSpillWeight(false, true,
375 loopInfo->getLoopDepth(mbb));
Lang Hamese9c93562010-09-21 13:19:36 +0000376
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000377 if (cp.isPhys()) {
Lang Hames5e77f4b2010-11-12 05:47:21 +0000378 if (!lis->isAllocatable(dst)) {
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000379 continue;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000380 }
Lang Hamese9c93562010-09-21 13:19:36 +0000381
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000382 const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
383 unsigned pregOpt = 0;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000384 while (pregOpt < allowed.size() && allowed[pregOpt] != dst) {
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000385 ++pregOpt;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000386 }
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000387 if (pregOpt < allowed.size()) {
388 ++pregOpt; // +1 to account for spill option.
389 PBQP::Graph::NodeItr node = p->getNodeForVReg(src);
390 addPhysRegCoalesce(g.getNodeCosts(node), pregOpt, cBenefit);
Lang Hamese9c93562010-09-21 13:19:36 +0000391 }
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000392 } else {
393 const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
394 const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
395 PBQP::Graph::NodeItr node1 = p->getNodeForVReg(dst);
396 PBQP::Graph::NodeItr node2 = p->getNodeForVReg(src);
397 PBQP::Graph::EdgeItr edge = g.findEdge(node1, node2);
398 if (edge == g.edgesEnd()) {
399 edge = g.addEdge(node1, node2, PBQP::Matrix(allowed1->size() + 1,
400 allowed2->size() + 1,
401 0));
402 } else {
403 if (g.getEdgeNode1(edge) == node2) {
404 std::swap(node1, node2);
405 std::swap(allowed1, allowed2);
406 }
407 }
408
409 addVirtRegCoalesce(g.getEdgeCosts(edge), *allowed1, *allowed2,
410 cBenefit);
Lang Hamese9c93562010-09-21 13:19:36 +0000411 }
412 }
413 }
414
415 return p;
416}
417
Lang Hamese9c93562010-09-21 13:19:36 +0000418void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
419 unsigned pregOption,
420 PBQP::PBQPNum benefit) {
421 costVec[pregOption] += -benefit;
422}
423
424void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
425 PBQP::Matrix &costMat,
426 const PBQPRAProblem::AllowedSet &vr1Allowed,
427 const PBQPRAProblem::AllowedSet &vr2Allowed,
428 PBQP::PBQPNum benefit) {
429
430 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
431 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
432
Lang Hames5e77f4b2010-11-12 05:47:21 +0000433 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hamese9c93562010-09-21 13:19:36 +0000434 unsigned preg1 = vr1Allowed[i];
Lang Hames5e77f4b2010-11-12 05:47:21 +0000435 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hamese9c93562010-09-21 13:19:36 +0000436 unsigned preg2 = vr2Allowed[j];
437
438 if (preg1 == preg2) {
439 costMat[i + 1][j + 1] += -benefit;
440 }
441 }
442 }
443}
Evan Chengb1290a62008-10-02 18:29:27 +0000444
Lang Hameseb6c8f52010-09-18 09:07:10 +0000445
446void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
447 au.addRequired<SlotIndexes>();
448 au.addPreserved<SlotIndexes>();
449 au.addRequired<LiveIntervals>();
450 //au.addRequiredID(SplitCriticalEdgesID);
451 au.addRequired<RegisterCoalescer>();
452 au.addRequired<CalculateSpillWeights>();
453 au.addRequired<LiveStacks>();
454 au.addPreserved<LiveStacks>();
455 au.addRequired<MachineLoopInfo>();
456 au.addPreserved<MachineLoopInfo>();
457 if (pbqpPreSplitting)
458 au.addRequired<LoopSplitter>();
459 au.addRequired<VirtRegMap>();
460 au.addRequired<RenderMachineFunction>();
461 MachineFunctionPass::getAnalysisUsage(au);
462}
463
Lang Hameseb6c8f52010-09-18 09:07:10 +0000464void RegAllocPBQP::findVRegIntervalsToAlloc() {
Lang Hames27601ef2008-11-16 12:12:54 +0000465
466 // Iterate over all live ranges.
467 for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
468 itr != end; ++itr) {
469
470 // Ignore physical ones.
471 if (TargetRegisterInfo::isPhysicalRegister(itr->first))
472 continue;
473
474 LiveInterval *li = itr->second;
475
476 // If this live interval is non-empty we will use pbqp to allocate it.
477 // Empty intervals we allocate in a simple post-processing stage in
478 // finalizeAlloc.
479 if (!li->empty()) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000480 vregsToAlloc.insert(li->reg);
Lang Hames5e77f4b2010-11-12 05:47:21 +0000481 } else {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000482 emptyIntervalVRegs.insert(li->reg);
Lang Hames27601ef2008-11-16 12:12:54 +0000483 }
484 }
Evan Chengb1290a62008-10-02 18:29:27 +0000485}
486
Lang Hameseb6c8f52010-09-18 09:07:10 +0000487void RegAllocPBQP::addStackInterval(const LiveInterval *spilled,
Evan Chengc781a242009-05-03 18:32:42 +0000488 MachineRegisterInfo* mri) {
Lang Hames27601ef2008-11-16 12:12:54 +0000489 int stackSlot = vrm->getStackSlot(spilled->reg);
Misha Brukman2a835f92009-01-08 15:50:22 +0000490
Lang Hames5e77f4b2010-11-12 05:47:21 +0000491 if (stackSlot == VirtRegMap::NO_STACK_SLOT) {
Lang Hames27601ef2008-11-16 12:12:54 +0000492 return;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000493 }
Lang Hames27601ef2008-11-16 12:12:54 +0000494
Evan Chengc781a242009-05-03 18:32:42 +0000495 const TargetRegisterClass *RC = mri->getRegClass(spilled->reg);
496 LiveInterval &stackInterval = lss->getOrCreateInterval(stackSlot, RC);
Lang Hames27601ef2008-11-16 12:12:54 +0000497
498 VNInfo *vni;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000499 if (stackInterval.getNumValNums() != 0) {
Lang Hames27601ef2008-11-16 12:12:54 +0000500 vni = stackInterval.getValNumInfo(0);
Lang Hames5e77f4b2010-11-12 05:47:21 +0000501 } else {
Lang Hames86511252009-09-04 20:41:11 +0000502 vni = stackInterval.getNextValue(
Lang Hames6e2968c2010-09-25 12:04:16 +0000503 SlotIndex(), 0, lss->getVNInfoAllocator());
Lang Hames5e77f4b2010-11-12 05:47:21 +0000504 }
Lang Hames27601ef2008-11-16 12:12:54 +0000505
506 LiveInterval &rhsInterval = lis->getInterval(spilled->reg);
507 stackInterval.MergeRangesInAsValue(rhsInterval, vni);
508}
509
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000510bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
511 const PBQP::Solution &solution) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000512 // Set to true if we have any spills
513 bool anotherRoundNeeded = false;
514
515 // Clear the existing allocation.
516 vrm->clearAllVirt();
517
518 const PBQP::Graph &g = problem.getGraph();
519 // Iterate over the nodes mapping the PBQP solution to a register
520 // assignment.
521 for (PBQP::Graph::ConstNodeItr node = g.nodesBegin(),
522 nodeEnd = g.nodesEnd();
523 node != nodeEnd; ++node) {
524 unsigned vreg = problem.getVRegForNode(node);
525 unsigned alloc = solution.getSelection(node);
526
527 if (problem.isPRegOption(vreg, alloc)) {
528 unsigned preg = problem.getPRegForOption(vreg, alloc);
529 DEBUG(dbgs() << "VREG " << vreg << " -> " << tri->getName(preg) << "\n");
530 assert(preg != 0 && "Invalid preg selected.");
531 vrm->assignVirt2Phys(vreg, preg);
532 } else if (problem.isSpillOption(vreg, alloc)) {
533 vregsToAlloc.erase(vreg);
534 const LiveInterval* spillInterval = &lis->getInterval(vreg);
535 double oldWeight = spillInterval->weight;
Lang Hameseb6c8f52010-09-18 09:07:10 +0000536 rmf->rememberUseDefs(spillInterval);
537 std::vector<LiveInterval*> newSpills =
Jakob Stoklund Olesen38f6bd02011-03-10 01:21:58 +0000538 lis->addIntervalsForSpills(*spillInterval, 0, loopInfo, *vrm);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000539 addStackInterval(spillInterval, mri);
540 rmf->rememberSpills(spillInterval, newSpills);
541
542 (void) oldWeight;
543 DEBUG(dbgs() << "VREG " << vreg << " -> SPILLED (Cost: "
544 << oldWeight << ", New vregs: ");
545
546 // Copy any newly inserted live intervals into the list of regs to
547 // allocate.
548 for (std::vector<LiveInterval*>::const_iterator
549 itr = newSpills.begin(), end = newSpills.end();
550 itr != end; ++itr) {
551 assert(!(*itr)->empty() && "Empty spill range.");
552 DEBUG(dbgs() << (*itr)->reg << " ");
553 vregsToAlloc.insert((*itr)->reg);
554 }
555
556 DEBUG(dbgs() << ")\n");
557
558 // We need another round if spill intervals were added.
559 anotherRoundNeeded |= !newSpills.empty();
560 } else {
561 assert(false && "Unknown allocation option.");
562 }
563 }
564
565 return !anotherRoundNeeded;
566}
567
568
569void RegAllocPBQP::finalizeAlloc() const {
Lang Hames27601ef2008-11-16 12:12:54 +0000570 typedef LiveIntervals::iterator LIIterator;
571 typedef LiveInterval::Ranges::const_iterator LRIterator;
572
573 // First allocate registers for the empty intervals.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000574 for (RegSet::const_iterator
575 itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
Lang Hames27601ef2008-11-16 12:12:54 +0000576 itr != end; ++itr) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000577 LiveInterval *li = &lis->getInterval(*itr);
Lang Hames27601ef2008-11-16 12:12:54 +0000578
Evan Cheng90f95f82009-06-14 20:22:55 +0000579 unsigned physReg = vrm->getRegAllocPref(li->reg);
Lang Hames6699fb22009-08-06 23:32:48 +0000580
Lang Hames27601ef2008-11-16 12:12:54 +0000581 if (physReg == 0) {
582 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
Jakob Stoklund Olesen714c0eb2011-06-16 20:37:45 +0000583 physReg = liRC->getRawAllocationOrder(*mf).front();
Lang Hames27601ef2008-11-16 12:12:54 +0000584 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000585
586 vrm->assignVirt2Phys(li->reg, physReg);
Lang Hames27601ef2008-11-16 12:12:54 +0000587 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000588
Lang Hames27601ef2008-11-16 12:12:54 +0000589 // Finally iterate over the basic blocks to compute and set the live-in sets.
590 SmallVector<MachineBasicBlock*, 8> liveInMBBs;
591 MachineBasicBlock *entryMBB = &*mf->begin();
592
593 for (LIIterator liItr = lis->begin(), liEnd = lis->end();
594 liItr != liEnd; ++liItr) {
595
596 const LiveInterval *li = liItr->second;
597 unsigned reg = 0;
Misha Brukman2a835f92009-01-08 15:50:22 +0000598
Lang Hames27601ef2008-11-16 12:12:54 +0000599 // Get the physical register for this interval
600 if (TargetRegisterInfo::isPhysicalRegister(li->reg)) {
601 reg = li->reg;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000602 } else if (vrm->isAssignedReg(li->reg)) {
Lang Hames27601ef2008-11-16 12:12:54 +0000603 reg = vrm->getPhys(li->reg);
Lang Hames5e77f4b2010-11-12 05:47:21 +0000604 } else {
Lang Hames27601ef2008-11-16 12:12:54 +0000605 // Ranges which are assigned a stack slot only are ignored.
606 continue;
607 }
608
Lang Hamesb0e519f2009-05-17 23:50:36 +0000609 if (reg == 0) {
Lang Hames6699fb22009-08-06 23:32:48 +0000610 // Filter out zero regs - they're for intervals that were spilled.
Lang Hamesb0e519f2009-05-17 23:50:36 +0000611 continue;
612 }
613
Lang Hames27601ef2008-11-16 12:12:54 +0000614 // Iterate over the ranges of the current interval...
615 for (LRIterator lrItr = li->begin(), lrEnd = li->end();
616 lrItr != lrEnd; ++lrItr) {
Misha Brukman2a835f92009-01-08 15:50:22 +0000617
Lang Hames27601ef2008-11-16 12:12:54 +0000618 // Find the set of basic blocks which this range is live into...
619 if (lis->findLiveInMBBs(lrItr->start, lrItr->end, liveInMBBs)) {
620 // And add the physreg for this interval to their live-in sets.
Lang Hames5e77f4b2010-11-12 05:47:21 +0000621 for (unsigned i = 0; i != liveInMBBs.size(); ++i) {
Lang Hames27601ef2008-11-16 12:12:54 +0000622 if (liveInMBBs[i] != entryMBB) {
623 if (!liveInMBBs[i]->isLiveIn(reg)) {
624 liveInMBBs[i]->addLiveIn(reg);
625 }
626 }
627 }
628 liveInMBBs.clear();
629 }
630 }
631 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000632
Lang Hames27601ef2008-11-16 12:12:54 +0000633}
634
Lang Hameseb6c8f52010-09-18 09:07:10 +0000635bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
Lang Hames27601ef2008-11-16 12:12:54 +0000636
Evan Chengb1290a62008-10-02 18:29:27 +0000637 mf = &MF;
638 tm = &mf->getTarget();
639 tri = tm->getRegisterInfo();
Lang Hames27601ef2008-11-16 12:12:54 +0000640 tii = tm->getInstrInfo();
Lang Hames233a60e2009-11-03 23:52:08 +0000641 mri = &mf->getRegInfo();
Evan Chengb1290a62008-10-02 18:29:27 +0000642
Lang Hames27601ef2008-11-16 12:12:54 +0000643 lis = &getAnalysis<LiveIntervals>();
644 lss = &getAnalysis<LiveStacks>();
Evan Chengb1290a62008-10-02 18:29:27 +0000645 loopInfo = &getAnalysis<MachineLoopInfo>();
Lang Hames33198392010-09-02 08:27:00 +0000646 rmf = &getAnalysis<RenderMachineFunction>();
Evan Chengb1290a62008-10-02 18:29:27 +0000647
Owen Anderson49c8aa02009-03-13 05:55:11 +0000648 vrm = &getAnalysis<VirtRegMap>();
Evan Chengb1290a62008-10-02 18:29:27 +0000649
Lang Hames54cc2ef2010-07-19 15:22:28 +0000650
Lang Hames030c4bf2010-01-26 04:49:58 +0000651 DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getFunction()->getName() << "\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000652
Evan Chengb1290a62008-10-02 18:29:27 +0000653 // Allocator main loop:
Misha Brukman2a835f92009-01-08 15:50:22 +0000654 //
Evan Chengb1290a62008-10-02 18:29:27 +0000655 // * Map current regalloc problem to a PBQP problem
656 // * Solve the PBQP problem
657 // * Map the solution back to a register allocation
658 // * Spill if necessary
Misha Brukman2a835f92009-01-08 15:50:22 +0000659 //
Evan Chengb1290a62008-10-02 18:29:27 +0000660 // This process is continued till no more spills are generated.
661
Lang Hames27601ef2008-11-16 12:12:54 +0000662 // Find the vreg intervals in need of allocation.
663 findVRegIntervalsToAlloc();
Misha Brukman2a835f92009-01-08 15:50:22 +0000664
Lang Hames27601ef2008-11-16 12:12:54 +0000665 // If there are non-empty intervals allocate them using pbqp.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000666 if (!vregsToAlloc.empty()) {
Evan Chengb1290a62008-10-02 18:29:27 +0000667
Lang Hames27601ef2008-11-16 12:12:54 +0000668 bool pbqpAllocComplete = false;
669 unsigned round = 0;
670
Lang Hamesab62b7e2010-10-04 12:13:07 +0000671 while (!pbqpAllocComplete) {
672 DEBUG(dbgs() << " PBQP Regalloc round " << round << ":\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000673
Lang Hamesab62b7e2010-10-04 12:13:07 +0000674 std::auto_ptr<PBQPRAProblem> problem =
675 builder->build(mf, lis, loopInfo, vregsToAlloc);
676 PBQP::Solution solution =
677 PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(
678 problem->getGraph());
Lang Hames233fd9c2009-08-18 23:34:50 +0000679
Lang Hamesab62b7e2010-10-04 12:13:07 +0000680 pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
Lang Hames27601ef2008-11-16 12:12:54 +0000681
Lang Hamesab62b7e2010-10-04 12:13:07 +0000682 ++round;
Lang Hames27601ef2008-11-16 12:12:54 +0000683 }
Evan Chengb1290a62008-10-02 18:29:27 +0000684 }
685
Lang Hames27601ef2008-11-16 12:12:54 +0000686 // Finalise allocation, allocate empty ranges.
687 finalizeAlloc();
Evan Chengb1290a62008-10-02 18:29:27 +0000688
Lang Hamesc4bcc772010-07-20 07:41:44 +0000689 rmf->renderMachineFunction("After PBQP register allocation.", vrm);
690
Lang Hameseb6c8f52010-09-18 09:07:10 +0000691 vregsToAlloc.clear();
692 emptyIntervalVRegs.clear();
Lang Hames27601ef2008-11-16 12:12:54 +0000693
David Greene30931542010-01-05 01:25:43 +0000694 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000695
Lang Hames87e3bca2009-05-06 02:36:21 +0000696 // Run rewriter
697 std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
698
699 rewriter->runOnMachineFunction(*mf, *vrm, lis);
Lang Hames27601ef2008-11-16 12:12:54 +0000700
Misha Brukman2a835f92009-01-08 15:50:22 +0000701 return true;
Evan Chengb1290a62008-10-02 18:29:27 +0000702}
703
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000704FunctionPass* llvm::createPBQPRegisterAllocator(
705 std::auto_ptr<PBQPBuilder> builder) {
706 return new RegAllocPBQP(builder);
Evan Chengb1290a62008-10-02 18:29:27 +0000707}
708
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000709FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
710 if (pbqpCoalescing) {
711 return createPBQPRegisterAllocator(
712 std::auto_ptr<PBQPBuilder>(new PBQPBuilderWithCoalescing()));
713 } // else
714 return createPBQPRegisterAllocator(
715 std::auto_ptr<PBQPBuilder>(new PBQPBuilder()));
Lang Hameseb6c8f52010-09-18 09:07:10 +0000716}
Evan Chengb1290a62008-10-02 18:29:27 +0000717
718#undef DEBUG_TYPE