blob: 471526333f8eb7f67a2ab6eec3cfcf083e10063d [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
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +000034#include "LiveRangeEdit.h"
Lang Hames54cc2ef2010-07-19 15:22:28 +000035#include "RenderMachineFunction.h"
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +000036#include "Spiller.h"
Evan Chengb1290a62008-10-02 18:29:27 +000037#include "VirtRegMap.h"
Rafael Espindolafdf16ca2011-06-26 21:41:06 +000038#include "RegisterCoalescer.h"
Lang Hames9ad7e072011-12-06 01:45:57 +000039#include "llvm/Analysis/AliasAnalysis.h"
Lang Hamesa937f222009-12-14 06:49:42 +000040#include "llvm/CodeGen/CalcSpillWeights.h"
Evan Chengb1290a62008-10-02 18:29:27 +000041#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Lang Hames27601ef2008-11-16 12:12:54 +000042#include "llvm/CodeGen/LiveStackAnalysis.h"
Lang Hameseb6c8f52010-09-18 09:07:10 +000043#include "llvm/CodeGen/RegAllocPBQP.h"
Lang Hames9ad7e072011-12-06 01:45:57 +000044#include "llvm/CodeGen/MachineDominators.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000045#include "llvm/CodeGen/MachineFunctionPass.h"
Evan Chengb1290a62008-10-02 18:29:27 +000046#include "llvm/CodeGen/MachineLoopInfo.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000047#include "llvm/CodeGen/MachineRegisterInfo.h"
Lang Hameseb6c8f52010-09-18 09:07:10 +000048#include "llvm/CodeGen/PBQP/HeuristicSolver.h"
49#include "llvm/CodeGen/PBQP/Graph.h"
50#include "llvm/CodeGen/PBQP/Heuristics/Briggs.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000051#include "llvm/CodeGen/RegAllocRegistry.h"
Evan Chengb1290a62008-10-02 18:29:27 +000052#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000053#include "llvm/Support/raw_ostream.h"
Misha Brukman2a835f92009-01-08 15:50:22 +000054#include "llvm/Target/TargetInstrInfo.h"
55#include "llvm/Target/TargetMachine.h"
56#include <limits>
Misha Brukman2a835f92009-01-08 15:50:22 +000057#include <memory>
Evan Chengb1290a62008-10-02 18:29:27 +000058#include <set>
59#include <vector>
Evan Chengb1290a62008-10-02 18:29:27 +000060
Lang Hamesf70e7cc2010-09-23 04:28:54 +000061using namespace llvm;
Lang Hameseb6c8f52010-09-18 09:07:10 +000062
Evan Chengb1290a62008-10-02 18:29:27 +000063static RegisterRegAlloc
Duncan Sands1aecd152010-02-18 14:10:41 +000064registerPBQPRepAlloc("pbqp", "PBQP register allocator",
Lang Hamesf70e7cc2010-09-23 04:28:54 +000065 createDefaultPBQPRegisterAllocator);
Evan Chengb1290a62008-10-02 18:29:27 +000066
Lang Hames8481e3b2009-08-19 01:36:14 +000067static cl::opt<bool>
68pbqpCoalescing("pbqp-coalescing",
Lang Hames030c4bf2010-01-26 04:49:58 +000069 cl::desc("Attempt coalescing during PBQP register allocation."),
70 cl::init(false), cl::Hidden);
Lang Hames8481e3b2009-08-19 01:36:14 +000071
Lang Hamesf70e7cc2010-09-23 04:28:54 +000072namespace {
73
74///
75/// PBQP based allocators solve the register allocation problem by mapping
76/// register allocation problems to Partitioned Boolean Quadratic
77/// Programming problems.
78class RegAllocPBQP : public MachineFunctionPass {
79public:
80
81 static char ID;
82
83 /// Construct a PBQP register allocator.
Lang Hames8d857662011-06-17 07:09:01 +000084 RegAllocPBQP(std::auto_ptr<PBQPBuilder> b, char *cPassID=0)
85 : MachineFunctionPass(ID), builder(b), customPassID(cPassID) {
Owen Anderson081c34b2010-10-19 17:21:58 +000086 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
87 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +000088 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Owen Anderson081c34b2010-10-19 17:21:58 +000089 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
90 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
91 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
Owen Anderson081c34b2010-10-19 17:21:58 +000092 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
93 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
94 }
Lang Hamesf70e7cc2010-09-23 04:28:54 +000095
96 /// Return the pass name.
97 virtual const char* getPassName() const {
98 return "PBQP Register Allocator";
99 }
100
101 /// PBQP analysis usage.
102 virtual void getAnalysisUsage(AnalysisUsage &au) const;
103
104 /// Perform register allocation
105 virtual bool runOnMachineFunction(MachineFunction &MF);
106
107private:
108
109 typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
110 typedef std::vector<const LiveInterval*> Node2LIMap;
111 typedef std::vector<unsigned> AllowedSet;
112 typedef std::vector<AllowedSet> AllowedSetMap;
113 typedef std::pair<unsigned, unsigned> RegPair;
114 typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
115 typedef std::vector<PBQP::Graph::NodeItr> NodeVector;
116 typedef std::set<unsigned> RegSet;
117
118
119 std::auto_ptr<PBQPBuilder> builder;
120
Lang Hames8d857662011-06-17 07:09:01 +0000121 char *customPassID;
122
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000123 MachineFunction *mf;
124 const TargetMachine *tm;
125 const TargetRegisterInfo *tri;
126 const TargetInstrInfo *tii;
127 const MachineLoopInfo *loopInfo;
128 MachineRegisterInfo *mri;
129 RenderMachineFunction *rmf;
130
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000131 std::auto_ptr<Spiller> spiller;
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000132 LiveIntervals *lis;
133 LiveStacks *lss;
134 VirtRegMap *vrm;
135
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000136 RegSet vregsToAlloc, emptyIntervalVRegs;
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000137
138 /// \brief Finds the initial set of vreg intervals to allocate.
139 void findVRegIntervalsToAlloc();
140
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000141 /// \brief Given a solved PBQP problem maps this solution back to a register
142 /// assignment.
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000143 bool mapPBQPToRegAlloc(const PBQPRAProblem &problem,
144 const PBQP::Solution &solution);
145
146 /// \brief Postprocessing before final spilling. Sets basic block "live in"
147 /// variables.
148 void finalizeAlloc() const;
149
150};
151
Lang Hameseb6c8f52010-09-18 09:07:10 +0000152char RegAllocPBQP::ID = 0;
Evan Chengb1290a62008-10-02 18:29:27 +0000153
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000154} // End anonymous namespace.
155
Lang Hameseb6c8f52010-09-18 09:07:10 +0000156unsigned PBQPRAProblem::getVRegForNode(PBQP::Graph::ConstNodeItr node) const {
157 Node2VReg::const_iterator vregItr = node2VReg.find(node);
158 assert(vregItr != node2VReg.end() && "No vreg for node.");
159 return vregItr->second;
160}
Evan Chengb1290a62008-10-02 18:29:27 +0000161
Lang Hameseb6c8f52010-09-18 09:07:10 +0000162PBQP::Graph::NodeItr PBQPRAProblem::getNodeForVReg(unsigned vreg) const {
163 VReg2Node::const_iterator nodeItr = vreg2Node.find(vreg);
164 assert(nodeItr != vreg2Node.end() && "No node for vreg.");
165 return nodeItr->second;
166
167}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000168
Lang Hameseb6c8f52010-09-18 09:07:10 +0000169const PBQPRAProblem::AllowedSet&
170 PBQPRAProblem::getAllowedSet(unsigned vreg) const {
171 AllowedSetMap::const_iterator allowedSetItr = allowedSets.find(vreg);
172 assert(allowedSetItr != allowedSets.end() && "No pregs for vreg.");
173 const AllowedSet &allowedSet = allowedSetItr->second;
174 return allowedSet;
175}
Evan Chengb1290a62008-10-02 18:29:27 +0000176
Lang Hameseb6c8f52010-09-18 09:07:10 +0000177unsigned PBQPRAProblem::getPRegForOption(unsigned vreg, unsigned option) const {
178 assert(isPRegOption(vreg, option) && "Not a preg option.");
179
180 const AllowedSet& allowedSet = getAllowedSet(vreg);
181 assert(option <= allowedSet.size() && "Option outside allowed set.");
182 return allowedSet[option - 1];
183}
184
Lang Hamese9c93562010-09-21 13:19:36 +0000185std::auto_ptr<PBQPRAProblem> PBQPBuilder::build(MachineFunction *mf,
186 const LiveIntervals *lis,
187 const MachineLoopInfo *loopInfo,
188 const RegSet &vregs) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000189
190 typedef std::vector<const LiveInterval*> LIVector;
191
192 MachineRegisterInfo *mri = &mf->getRegInfo();
193 const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();
194
195 std::auto_ptr<PBQPRAProblem> p(new PBQPRAProblem());
196 PBQP::Graph &g = p->getGraph();
197 RegSet pregs;
198
199 // Collect the set of preg intervals, record that they're used in the MF.
200 for (LiveIntervals::const_iterator itr = lis->begin(), end = lis->end();
201 itr != end; ++itr) {
202 if (TargetRegisterInfo::isPhysicalRegister(itr->first)) {
203 pregs.insert(itr->first);
204 mri->setPhysRegUsed(itr->first);
Evan Chengb1290a62008-10-02 18:29:27 +0000205 }
Lang Hameseb6c8f52010-09-18 09:07:10 +0000206 }
Evan Chengb1290a62008-10-02 18:29:27 +0000207
Lang Hameseb6c8f52010-09-18 09:07:10 +0000208 BitVector reservedRegs = tri->getReservedRegs(*mf);
Evan Chengb1290a62008-10-02 18:29:27 +0000209
Lang Hameseb6c8f52010-09-18 09:07:10 +0000210 // Iterate over vregs.
211 for (RegSet::const_iterator vregItr = vregs.begin(), vregEnd = vregs.end();
212 vregItr != vregEnd; ++vregItr) {
213 unsigned vreg = *vregItr;
214 const TargetRegisterClass *trc = mri->getRegClass(vreg);
215 const LiveInterval *vregLI = &lis->getInterval(vreg);
Evan Chengb1290a62008-10-02 18:29:27 +0000216
Lang Hameseb6c8f52010-09-18 09:07:10 +0000217 // Compute an initial allowed set for the current vreg.
218 typedef std::vector<unsigned> VRAllowed;
219 VRAllowed vrAllowed;
Jakob Stoklund Olesen714c0eb2011-06-16 20:37:45 +0000220 ArrayRef<unsigned> rawOrder = trc->getRawAllocationOrder(*mf);
221 for (unsigned i = 0; i != rawOrder.size(); ++i) {
222 unsigned preg = rawOrder[i];
Lang Hameseb6c8f52010-09-18 09:07:10 +0000223 if (!reservedRegs.test(preg)) {
224 vrAllowed.push_back(preg);
Lang Hamesd0f6f012010-07-17 06:31:41 +0000225 }
Lang Hameseb6c8f52010-09-18 09:07:10 +0000226 }
Lang Hamesd0f6f012010-07-17 06:31:41 +0000227
Lang Hameseb6c8f52010-09-18 09:07:10 +0000228 // Remove any physical registers which overlap.
229 for (RegSet::const_iterator pregItr = pregs.begin(),
230 pregEnd = pregs.end();
231 pregItr != pregEnd; ++pregItr) {
232 unsigned preg = *pregItr;
233 const LiveInterval *pregLI = &lis->getInterval(preg);
Lang Hames27601ef2008-11-16 12:12:54 +0000234
Lang Hames5e77f4b2010-11-12 05:47:21 +0000235 if (pregLI->empty()) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000236 continue;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000237 }
Evan Chengb1290a62008-10-02 18:29:27 +0000238
Lang Hames5e77f4b2010-11-12 05:47:21 +0000239 if (!vregLI->overlaps(*pregLI)) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000240 continue;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000241 }
Lang Hames030c4bf2010-01-26 04:49:58 +0000242
Lang Hameseb6c8f52010-09-18 09:07:10 +0000243 // Remove the register from the allowed set.
244 VRAllowed::iterator eraseItr =
245 std::find(vrAllowed.begin(), vrAllowed.end(), preg);
Evan Chengb1290a62008-10-02 18:29:27 +0000246
Lang Hameseb6c8f52010-09-18 09:07:10 +0000247 if (eraseItr != vrAllowed.end()) {
248 vrAllowed.erase(eraseItr);
249 }
Evan Chengb1290a62008-10-02 18:29:27 +0000250
Lang Hameseb6c8f52010-09-18 09:07:10 +0000251 // Also remove any aliases.
252 const unsigned *aliasItr = tri->getAliasSet(preg);
253 if (aliasItr != 0) {
254 for (; *aliasItr != 0; ++aliasItr) {
255 VRAllowed::iterator eraseItr =
256 std::find(vrAllowed.begin(), vrAllowed.end(), *aliasItr);
Evan Chengb1290a62008-10-02 18:29:27 +0000257
Lang Hameseb6c8f52010-09-18 09:07:10 +0000258 if (eraseItr != vrAllowed.end()) {
259 vrAllowed.erase(eraseItr);
260 }
261 }
262 }
263 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000264
Lang Hameseb6c8f52010-09-18 09:07:10 +0000265 // Construct the node.
266 PBQP::Graph::NodeItr node =
267 g.addNode(PBQP::Vector(vrAllowed.size() + 1, 0));
Evan Chengb1290a62008-10-02 18:29:27 +0000268
Lang Hameseb6c8f52010-09-18 09:07:10 +0000269 // Record the mapping and allowed set in the problem.
270 p->recordVReg(vreg, node, vrAllowed.begin(), vrAllowed.end());
Evan Chengb1290a62008-10-02 18:29:27 +0000271
Lang Hameseb6c8f52010-09-18 09:07:10 +0000272 PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
273 vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
Evan Chengb1290a62008-10-02 18:29:27 +0000274
Lang Hameseb6c8f52010-09-18 09:07:10 +0000275 addSpillCosts(g.getNodeCosts(node), spillCost);
276 }
Evan Chengb1290a62008-10-02 18:29:27 +0000277
Lang Hames481630d2010-09-18 09:49:08 +0000278 for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000279 vr1Itr != vrEnd; ++vr1Itr) {
280 unsigned vr1 = *vr1Itr;
281 const LiveInterval &l1 = lis->getInterval(vr1);
282 const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
Evan Chengb1290a62008-10-02 18:29:27 +0000283
Benjamin Kramer9e8d1f92010-09-18 14:41:26 +0000284 for (RegSet::const_iterator vr2Itr = llvm::next(vr1Itr);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000285 vr2Itr != vrEnd; ++vr2Itr) {
286 unsigned vr2 = *vr2Itr;
287 const LiveInterval &l2 = lis->getInterval(vr2);
288 const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
Evan Chengb1290a62008-10-02 18:29:27 +0000289
Lang Hameseb6c8f52010-09-18 09:07:10 +0000290 assert(!l2.empty() && "Empty interval in vreg set?");
291 if (l1.overlaps(l2)) {
292 PBQP::Graph::EdgeItr edge =
293 g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
294 PBQP::Matrix(vr1Allowed.size()+1, vr2Allowed.size()+1, 0));
Lang Hames27601ef2008-11-16 12:12:54 +0000295
Lang Hameseb6c8f52010-09-18 09:07:10 +0000296 addInterferenceCosts(g.getEdgeCosts(edge), vr1Allowed, vr2Allowed, tri);
297 }
298 }
299 }
Evan Chengb1290a62008-10-02 18:29:27 +0000300
Lang Hameseb6c8f52010-09-18 09:07:10 +0000301 return p;
302}
Lang Hames27601ef2008-11-16 12:12:54 +0000303
Lang Hameseb6c8f52010-09-18 09:07:10 +0000304void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
305 PBQP::PBQPNum spillCost) {
306 costVec[0] = spillCost;
307}
Evan Chengb1290a62008-10-02 18:29:27 +0000308
Lang Hamese9c93562010-09-21 13:19:36 +0000309void PBQPBuilder::addInterferenceCosts(
310 PBQP::Matrix &costMat,
311 const PBQPRAProblem::AllowedSet &vr1Allowed,
312 const PBQPRAProblem::AllowedSet &vr2Allowed,
313 const TargetRegisterInfo *tri) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000314 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
315 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
316
Lang Hames5e77f4b2010-11-12 05:47:21 +0000317 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000318 unsigned preg1 = vr1Allowed[i];
319
Lang Hames5e77f4b2010-11-12 05:47:21 +0000320 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000321 unsigned preg2 = vr2Allowed[j];
322
323 if (tri->regsOverlap(preg1, preg2)) {
324 costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
325 }
326 }
327 }
Evan Chengb1290a62008-10-02 18:29:27 +0000328}
329
Lang Hamese9c93562010-09-21 13:19:36 +0000330std::auto_ptr<PBQPRAProblem> PBQPBuilderWithCoalescing::build(
331 MachineFunction *mf,
332 const LiveIntervals *lis,
333 const MachineLoopInfo *loopInfo,
334 const RegSet &vregs) {
335
336 std::auto_ptr<PBQPRAProblem> p = PBQPBuilder::build(mf, lis, loopInfo, vregs);
337 PBQP::Graph &g = p->getGraph();
338
339 const TargetMachine &tm = mf->getTarget();
340 CoalescerPair cp(*tm.getInstrInfo(), *tm.getRegisterInfo());
341
342 // Scan the machine function and add a coalescing cost whenever CoalescerPair
343 // gives the Ok.
344 for (MachineFunction::const_iterator mbbItr = mf->begin(),
345 mbbEnd = mf->end();
346 mbbItr != mbbEnd; ++mbbItr) {
347 const MachineBasicBlock *mbb = &*mbbItr;
348
349 for (MachineBasicBlock::const_iterator miItr = mbb->begin(),
350 miEnd = mbb->end();
351 miItr != miEnd; ++miItr) {
352 const MachineInstr *mi = &*miItr;
353
Lang Hames5e77f4b2010-11-12 05:47:21 +0000354 if (!cp.setRegisters(mi)) {
Lang Hamese9c93562010-09-21 13:19:36 +0000355 continue; // Not coalescable.
Lang Hames5e77f4b2010-11-12 05:47:21 +0000356 }
Lang Hamese9c93562010-09-21 13:19:36 +0000357
Lang Hames5e77f4b2010-11-12 05:47:21 +0000358 if (cp.getSrcReg() == cp.getDstReg()) {
Lang Hamese9c93562010-09-21 13:19:36 +0000359 continue; // Already coalesced.
Lang Hames5e77f4b2010-11-12 05:47:21 +0000360 }
Lang Hamese9c93562010-09-21 13:19:36 +0000361
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000362 unsigned dst = cp.getDstReg(),
363 src = cp.getSrcReg();
Lang Hamese9c93562010-09-21 13:19:36 +0000364
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000365 const float copyFactor = 0.5; // Cost of copy relative to load. Current
366 // value plucked randomly out of the air.
367
368 PBQP::PBQPNum cBenefit =
369 copyFactor * LiveIntervals::getSpillWeight(false, true,
370 loopInfo->getLoopDepth(mbb));
Lang Hamese9c93562010-09-21 13:19:36 +0000371
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000372 if (cp.isPhys()) {
Lang Hames5e77f4b2010-11-12 05:47:21 +0000373 if (!lis->isAllocatable(dst)) {
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000374 continue;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000375 }
Lang Hamese9c93562010-09-21 13:19:36 +0000376
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000377 const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
378 unsigned pregOpt = 0;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000379 while (pregOpt < allowed.size() && allowed[pregOpt] != dst) {
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000380 ++pregOpt;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000381 }
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000382 if (pregOpt < allowed.size()) {
383 ++pregOpt; // +1 to account for spill option.
384 PBQP::Graph::NodeItr node = p->getNodeForVReg(src);
385 addPhysRegCoalesce(g.getNodeCosts(node), pregOpt, cBenefit);
Lang Hamese9c93562010-09-21 13:19:36 +0000386 }
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000387 } else {
388 const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
389 const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
390 PBQP::Graph::NodeItr node1 = p->getNodeForVReg(dst);
391 PBQP::Graph::NodeItr node2 = p->getNodeForVReg(src);
392 PBQP::Graph::EdgeItr edge = g.findEdge(node1, node2);
393 if (edge == g.edgesEnd()) {
394 edge = g.addEdge(node1, node2, PBQP::Matrix(allowed1->size() + 1,
395 allowed2->size() + 1,
396 0));
397 } else {
398 if (g.getEdgeNode1(edge) == node2) {
399 std::swap(node1, node2);
400 std::swap(allowed1, allowed2);
401 }
402 }
403
404 addVirtRegCoalesce(g.getEdgeCosts(edge), *allowed1, *allowed2,
405 cBenefit);
Lang Hamese9c93562010-09-21 13:19:36 +0000406 }
407 }
408 }
409
410 return p;
411}
412
Lang Hamese9c93562010-09-21 13:19:36 +0000413void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
414 unsigned pregOption,
415 PBQP::PBQPNum benefit) {
416 costVec[pregOption] += -benefit;
417}
418
419void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
420 PBQP::Matrix &costMat,
421 const PBQPRAProblem::AllowedSet &vr1Allowed,
422 const PBQPRAProblem::AllowedSet &vr2Allowed,
423 PBQP::PBQPNum benefit) {
424
425 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
426 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
427
Lang Hames5e77f4b2010-11-12 05:47:21 +0000428 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hamese9c93562010-09-21 13:19:36 +0000429 unsigned preg1 = vr1Allowed[i];
Lang Hames5e77f4b2010-11-12 05:47:21 +0000430 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hamese9c93562010-09-21 13:19:36 +0000431 unsigned preg2 = vr2Allowed[j];
432
433 if (preg1 == preg2) {
434 costMat[i + 1][j + 1] += -benefit;
435 }
436 }
437 }
438}
Evan Chengb1290a62008-10-02 18:29:27 +0000439
Lang Hameseb6c8f52010-09-18 09:07:10 +0000440
441void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
Lang Hames9ad7e072011-12-06 01:45:57 +0000442 au.setPreservesCFG();
443 au.addRequired<AliasAnalysis>();
444 au.addPreserved<AliasAnalysis>();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000445 au.addRequired<SlotIndexes>();
446 au.addPreserved<SlotIndexes>();
447 au.addRequired<LiveIntervals>();
448 //au.addRequiredID(SplitCriticalEdgesID);
Jakob Stoklund Olesen27215672011-08-09 00:29:53 +0000449 au.addRequiredID(RegisterCoalescerPassID);
Lang Hames8d857662011-06-17 07:09:01 +0000450 if (customPassID)
451 au.addRequiredID(*customPassID);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000452 au.addRequired<CalculateSpillWeights>();
453 au.addRequired<LiveStacks>();
454 au.addPreserved<LiveStacks>();
Lang Hames9ad7e072011-12-06 01:45:57 +0000455 au.addRequired<MachineDominatorTree>();
456 au.addPreserved<MachineDominatorTree>();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000457 au.addRequired<MachineLoopInfo>();
458 au.addPreserved<MachineLoopInfo>();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000459 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 Hamesf70e7cc2010-09-23 04:28:54 +0000487bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
488 const PBQP::Solution &solution) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000489 // Set to true if we have any spills
490 bool anotherRoundNeeded = false;
491
492 // Clear the existing allocation.
493 vrm->clearAllVirt();
494
495 const PBQP::Graph &g = problem.getGraph();
496 // Iterate over the nodes mapping the PBQP solution to a register
497 // assignment.
498 for (PBQP::Graph::ConstNodeItr node = g.nodesBegin(),
499 nodeEnd = g.nodesEnd();
500 node != nodeEnd; ++node) {
501 unsigned vreg = problem.getVRegForNode(node);
502 unsigned alloc = solution.getSelection(node);
503
504 if (problem.isPRegOption(vreg, alloc)) {
505 unsigned preg = problem.getPRegForOption(vreg, alloc);
506 DEBUG(dbgs() << "VREG " << vreg << " -> " << tri->getName(preg) << "\n");
507 assert(preg != 0 && "Invalid preg selected.");
508 vrm->assignVirt2Phys(vreg, preg);
509 } else if (problem.isSpillOption(vreg, alloc)) {
510 vregsToAlloc.erase(vreg);
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000511 SmallVector<LiveInterval*, 8> newSpills;
512 LiveRangeEdit LRE(lis->getInterval(vreg), newSpills);
513 spiller->spill(LRE);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000514
Lang Hameseb6c8f52010-09-18 09:07:10 +0000515 DEBUG(dbgs() << "VREG " << vreg << " -> SPILLED (Cost: "
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000516 << LRE.getParent().weight << ", New vregs: ");
Lang Hameseb6c8f52010-09-18 09:07:10 +0000517
518 // Copy any newly inserted live intervals into the list of regs to
519 // allocate.
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000520 for (LiveRangeEdit::iterator itr = LRE.begin(), end = LRE.end();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000521 itr != end; ++itr) {
522 assert(!(*itr)->empty() && "Empty spill range.");
523 DEBUG(dbgs() << (*itr)->reg << " ");
524 vregsToAlloc.insert((*itr)->reg);
525 }
526
527 DEBUG(dbgs() << ")\n");
528
529 // We need another round if spill intervals were added.
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000530 anotherRoundNeeded |= !LRE.empty();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000531 } else {
Craig Topper5e25ee82012-02-05 08:31:47 +0000532 llvm_unreachable("Unknown allocation option.");
Lang Hameseb6c8f52010-09-18 09:07:10 +0000533 }
534 }
535
536 return !anotherRoundNeeded;
537}
538
539
540void RegAllocPBQP::finalizeAlloc() const {
Lang Hames27601ef2008-11-16 12:12:54 +0000541 typedef LiveIntervals::iterator LIIterator;
542 typedef LiveInterval::Ranges::const_iterator LRIterator;
543
544 // First allocate registers for the empty intervals.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000545 for (RegSet::const_iterator
546 itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
Lang Hames27601ef2008-11-16 12:12:54 +0000547 itr != end; ++itr) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000548 LiveInterval *li = &lis->getInterval(*itr);
Lang Hames27601ef2008-11-16 12:12:54 +0000549
Evan Cheng90f95f82009-06-14 20:22:55 +0000550 unsigned physReg = vrm->getRegAllocPref(li->reg);
Lang Hames6699fb22009-08-06 23:32:48 +0000551
Lang Hames27601ef2008-11-16 12:12:54 +0000552 if (physReg == 0) {
553 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
Jakob Stoklund Olesen714c0eb2011-06-16 20:37:45 +0000554 physReg = liRC->getRawAllocationOrder(*mf).front();
Lang Hames27601ef2008-11-16 12:12:54 +0000555 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000556
557 vrm->assignVirt2Phys(li->reg, physReg);
Lang Hames27601ef2008-11-16 12:12:54 +0000558 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000559
Lang Hames27601ef2008-11-16 12:12:54 +0000560 // Finally iterate over the basic blocks to compute and set the live-in sets.
561 SmallVector<MachineBasicBlock*, 8> liveInMBBs;
562 MachineBasicBlock *entryMBB = &*mf->begin();
563
564 for (LIIterator liItr = lis->begin(), liEnd = lis->end();
565 liItr != liEnd; ++liItr) {
566
567 const LiveInterval *li = liItr->second;
568 unsigned reg = 0;
Misha Brukman2a835f92009-01-08 15:50:22 +0000569
Lang Hames27601ef2008-11-16 12:12:54 +0000570 // Get the physical register for this interval
571 if (TargetRegisterInfo::isPhysicalRegister(li->reg)) {
572 reg = li->reg;
Lang Hames5e77f4b2010-11-12 05:47:21 +0000573 } else if (vrm->isAssignedReg(li->reg)) {
Lang Hames27601ef2008-11-16 12:12:54 +0000574 reg = vrm->getPhys(li->reg);
Lang Hames5e77f4b2010-11-12 05:47:21 +0000575 } else {
Lang Hames27601ef2008-11-16 12:12:54 +0000576 // Ranges which are assigned a stack slot only are ignored.
577 continue;
578 }
579
Lang Hamesb0e519f2009-05-17 23:50:36 +0000580 if (reg == 0) {
Lang Hames6699fb22009-08-06 23:32:48 +0000581 // Filter out zero regs - they're for intervals that were spilled.
Lang Hamesb0e519f2009-05-17 23:50:36 +0000582 continue;
583 }
584
Lang Hames27601ef2008-11-16 12:12:54 +0000585 // Iterate over the ranges of the current interval...
586 for (LRIterator lrItr = li->begin(), lrEnd = li->end();
587 lrItr != lrEnd; ++lrItr) {
Misha Brukman2a835f92009-01-08 15:50:22 +0000588
Lang Hames27601ef2008-11-16 12:12:54 +0000589 // Find the set of basic blocks which this range is live into...
590 if (lis->findLiveInMBBs(lrItr->start, lrItr->end, liveInMBBs)) {
591 // And add the physreg for this interval to their live-in sets.
Lang Hames5e77f4b2010-11-12 05:47:21 +0000592 for (unsigned i = 0; i != liveInMBBs.size(); ++i) {
Lang Hames27601ef2008-11-16 12:12:54 +0000593 if (liveInMBBs[i] != entryMBB) {
594 if (!liveInMBBs[i]->isLiveIn(reg)) {
595 liveInMBBs[i]->addLiveIn(reg);
596 }
597 }
598 }
599 liveInMBBs.clear();
600 }
601 }
602 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000603
Lang Hames27601ef2008-11-16 12:12:54 +0000604}
605
Lang Hameseb6c8f52010-09-18 09:07:10 +0000606bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
Lang Hames27601ef2008-11-16 12:12:54 +0000607
Evan Chengb1290a62008-10-02 18:29:27 +0000608 mf = &MF;
609 tm = &mf->getTarget();
610 tri = tm->getRegisterInfo();
Lang Hames27601ef2008-11-16 12:12:54 +0000611 tii = tm->getInstrInfo();
Lang Hames233a60e2009-11-03 23:52:08 +0000612 mri = &mf->getRegInfo();
Evan Chengb1290a62008-10-02 18:29:27 +0000613
Lang Hames27601ef2008-11-16 12:12:54 +0000614 lis = &getAnalysis<LiveIntervals>();
615 lss = &getAnalysis<LiveStacks>();
Evan Chengb1290a62008-10-02 18:29:27 +0000616 loopInfo = &getAnalysis<MachineLoopInfo>();
Lang Hames33198392010-09-02 08:27:00 +0000617 rmf = &getAnalysis<RenderMachineFunction>();
Evan Chengb1290a62008-10-02 18:29:27 +0000618
Owen Anderson49c8aa02009-03-13 05:55:11 +0000619 vrm = &getAnalysis<VirtRegMap>();
Jakob Stoklund Olesencfa81012011-11-12 23:17:52 +0000620 spiller.reset(createInlineSpiller(*this, MF, *vrm));
Evan Chengb1290a62008-10-02 18:29:27 +0000621
Jakob Stoklund Olesend9e5c762012-01-05 00:26:49 +0000622 mri->freezeReservedRegs(MF);
Lang Hames54cc2ef2010-07-19 15:22:28 +0000623
Lang Hames030c4bf2010-01-26 04:49:58 +0000624 DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getFunction()->getName() << "\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000625
Evan Chengb1290a62008-10-02 18:29:27 +0000626 // Allocator main loop:
Misha Brukman2a835f92009-01-08 15:50:22 +0000627 //
Evan Chengb1290a62008-10-02 18:29:27 +0000628 // * Map current regalloc problem to a PBQP problem
629 // * Solve the PBQP problem
630 // * Map the solution back to a register allocation
631 // * Spill if necessary
Misha Brukman2a835f92009-01-08 15:50:22 +0000632 //
Evan Chengb1290a62008-10-02 18:29:27 +0000633 // This process is continued till no more spills are generated.
634
Lang Hames27601ef2008-11-16 12:12:54 +0000635 // Find the vreg intervals in need of allocation.
636 findVRegIntervalsToAlloc();
Misha Brukman2a835f92009-01-08 15:50:22 +0000637
Lang Hames27601ef2008-11-16 12:12:54 +0000638 // If there are non-empty intervals allocate them using pbqp.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000639 if (!vregsToAlloc.empty()) {
Evan Chengb1290a62008-10-02 18:29:27 +0000640
Lang Hames27601ef2008-11-16 12:12:54 +0000641 bool pbqpAllocComplete = false;
642 unsigned round = 0;
643
Lang Hamesab62b7e2010-10-04 12:13:07 +0000644 while (!pbqpAllocComplete) {
645 DEBUG(dbgs() << " PBQP Regalloc round " << round << ":\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000646
Lang Hamesab62b7e2010-10-04 12:13:07 +0000647 std::auto_ptr<PBQPRAProblem> problem =
648 builder->build(mf, lis, loopInfo, vregsToAlloc);
649 PBQP::Solution solution =
650 PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(
651 problem->getGraph());
Lang Hames233fd9c2009-08-18 23:34:50 +0000652
Lang Hamesab62b7e2010-10-04 12:13:07 +0000653 pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
Lang Hames27601ef2008-11-16 12:12:54 +0000654
Lang Hamesab62b7e2010-10-04 12:13:07 +0000655 ++round;
Lang Hames27601ef2008-11-16 12:12:54 +0000656 }
Evan Chengb1290a62008-10-02 18:29:27 +0000657 }
658
Lang Hames27601ef2008-11-16 12:12:54 +0000659 // Finalise allocation, allocate empty ranges.
660 finalizeAlloc();
Evan Chengb1290a62008-10-02 18:29:27 +0000661
Lang Hamesc4bcc772010-07-20 07:41:44 +0000662 rmf->renderMachineFunction("After PBQP register allocation.", vrm);
663
Lang Hameseb6c8f52010-09-18 09:07:10 +0000664 vregsToAlloc.clear();
665 emptyIntervalVRegs.clear();
Lang Hames27601ef2008-11-16 12:12:54 +0000666
David Greene30931542010-01-05 01:25:43 +0000667 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000668
Lang Hames87e3bca2009-05-06 02:36:21 +0000669 // Run rewriter
Jakob Stoklund Olesenc3f27222011-11-13 00:02:24 +0000670 vrm->rewrite(lis->getSlotIndexes());
Lang Hames27601ef2008-11-16 12:12:54 +0000671
Misha Brukman2a835f92009-01-08 15:50:22 +0000672 return true;
Evan Chengb1290a62008-10-02 18:29:27 +0000673}
674
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000675FunctionPass* llvm::createPBQPRegisterAllocator(
Lang Hames8d857662011-06-17 07:09:01 +0000676 std::auto_ptr<PBQPBuilder> builder,
677 char *customPassID) {
678 return new RegAllocPBQP(builder, customPassID);
Evan Chengb1290a62008-10-02 18:29:27 +0000679}
680
Lang Hamesf70e7cc2010-09-23 04:28:54 +0000681FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
682 if (pbqpCoalescing) {
683 return createPBQPRegisterAllocator(
684 std::auto_ptr<PBQPBuilder>(new PBQPBuilderWithCoalescing()));
685 } // else
686 return createPBQPRegisterAllocator(
687 std::auto_ptr<PBQPBuilder>(new PBQPBuilder()));
Lang Hameseb6c8f52010-09-18 09:07:10 +0000688}
Evan Chengb1290a62008-10-02 18:29:27 +0000689
690#undef DEBUG_TYPE