blob: 63538353a8c377a695639e6c48818a968c806ff9 [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 Hameseb6c8f52010-09-18 09:07:10 +000059namespace llvm {
60
Evan Chengb1290a62008-10-02 18:29:27 +000061static RegisterRegAlloc
Duncan Sands1aecd152010-02-18 14:10:41 +000062registerPBQPRepAlloc("pbqp", "PBQP register allocator",
Lang Hames030c4bf2010-01-26 04:49:58 +000063 llvm::createPBQPRegisterAllocator);
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>
Lang Hameseb6c8f52010-09-18 09:07:10 +000071pbqpBuilder("pbqp-builder",
72 cl::desc("Use new builder system."),
73 cl::init(false), cl::Hidden);
74
75
76static cl::opt<bool>
Lang Hames12f35c52010-07-18 00:57:59 +000077pbqpPreSplitting("pbqp-pre-splitting",
78 cl::desc("Pre-splite before PBQP register allocation."),
79 cl::init(false), cl::Hidden);
80
Lang Hameseb6c8f52010-09-18 09:07:10 +000081char RegAllocPBQP::ID = 0;
Evan Chengb1290a62008-10-02 18:29:27 +000082
Lang Hameseb6c8f52010-09-18 09:07:10 +000083unsigned PBQPRAProblem::getVRegForNode(PBQP::Graph::ConstNodeItr node) const {
84 Node2VReg::const_iterator vregItr = node2VReg.find(node);
85 assert(vregItr != node2VReg.end() && "No vreg for node.");
86 return vregItr->second;
87}
Evan Chengb1290a62008-10-02 18:29:27 +000088
Lang Hameseb6c8f52010-09-18 09:07:10 +000089PBQP::Graph::NodeItr PBQPRAProblem::getNodeForVReg(unsigned vreg) const {
90 VReg2Node::const_iterator nodeItr = vreg2Node.find(vreg);
91 assert(nodeItr != vreg2Node.end() && "No node for vreg.");
92 return nodeItr->second;
93
94}
Daniel Dunbara279bc32009-09-20 02:20:51 +000095
Lang Hameseb6c8f52010-09-18 09:07:10 +000096const PBQPRAProblem::AllowedSet&
97 PBQPRAProblem::getAllowedSet(unsigned vreg) const {
98 AllowedSetMap::const_iterator allowedSetItr = allowedSets.find(vreg);
99 assert(allowedSetItr != allowedSets.end() && "No pregs for vreg.");
100 const AllowedSet &allowedSet = allowedSetItr->second;
101 return allowedSet;
102}
Evan Chengb1290a62008-10-02 18:29:27 +0000103
Lang Hameseb6c8f52010-09-18 09:07:10 +0000104unsigned PBQPRAProblem::getPRegForOption(unsigned vreg, unsigned option) const {
105 assert(isPRegOption(vreg, option) && "Not a preg option.");
106
107 const AllowedSet& allowedSet = getAllowedSet(vreg);
108 assert(option <= allowedSet.size() && "Option outside allowed set.");
109 return allowedSet[option - 1];
110}
111
Lang Hamese9c93562010-09-21 13:19:36 +0000112std::auto_ptr<PBQPRAProblem> PBQPBuilder::build(MachineFunction *mf,
113 const LiveIntervals *lis,
114 const MachineLoopInfo *loopInfo,
115 const RegSet &vregs) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000116
117 typedef std::vector<const LiveInterval*> LIVector;
118
119 MachineRegisterInfo *mri = &mf->getRegInfo();
120 const TargetRegisterInfo *tri = mf->getTarget().getRegisterInfo();
121
122 std::auto_ptr<PBQPRAProblem> p(new PBQPRAProblem());
123 PBQP::Graph &g = p->getGraph();
124 RegSet pregs;
125
126 // Collect the set of preg intervals, record that they're used in the MF.
127 for (LiveIntervals::const_iterator itr = lis->begin(), end = lis->end();
128 itr != end; ++itr) {
129 if (TargetRegisterInfo::isPhysicalRegister(itr->first)) {
130 pregs.insert(itr->first);
131 mri->setPhysRegUsed(itr->first);
Evan Chengb1290a62008-10-02 18:29:27 +0000132 }
Lang Hameseb6c8f52010-09-18 09:07:10 +0000133 }
Evan Chengb1290a62008-10-02 18:29:27 +0000134
Lang Hameseb6c8f52010-09-18 09:07:10 +0000135 BitVector reservedRegs = tri->getReservedRegs(*mf);
Evan Chengb1290a62008-10-02 18:29:27 +0000136
Lang Hameseb6c8f52010-09-18 09:07:10 +0000137 // Iterate over vregs.
138 for (RegSet::const_iterator vregItr = vregs.begin(), vregEnd = vregs.end();
139 vregItr != vregEnd; ++vregItr) {
140 unsigned vreg = *vregItr;
141 const TargetRegisterClass *trc = mri->getRegClass(vreg);
142 const LiveInterval *vregLI = &lis->getInterval(vreg);
Evan Chengb1290a62008-10-02 18:29:27 +0000143
Lang Hameseb6c8f52010-09-18 09:07:10 +0000144 // Compute an initial allowed set for the current vreg.
145 typedef std::vector<unsigned> VRAllowed;
146 VRAllowed vrAllowed;
147 for (TargetRegisterClass::iterator aoItr = trc->allocation_order_begin(*mf),
148 aoEnd = trc->allocation_order_end(*mf);
149 aoItr != aoEnd; ++aoItr) {
150 unsigned preg = *aoItr;
151 if (!reservedRegs.test(preg)) {
152 vrAllowed.push_back(preg);
Lang Hamesd0f6f012010-07-17 06:31:41 +0000153 }
Lang Hameseb6c8f52010-09-18 09:07:10 +0000154 }
Lang Hamesd0f6f012010-07-17 06:31:41 +0000155
Lang Hameseb6c8f52010-09-18 09:07:10 +0000156 // Remove any physical registers which overlap.
157 for (RegSet::const_iterator pregItr = pregs.begin(),
158 pregEnd = pregs.end();
159 pregItr != pregEnd; ++pregItr) {
160 unsigned preg = *pregItr;
161 const LiveInterval *pregLI = &lis->getInterval(preg);
Lang Hames27601ef2008-11-16 12:12:54 +0000162
Lang Hameseb6c8f52010-09-18 09:07:10 +0000163 if (pregLI->empty())
164 continue;
Evan Chengb1290a62008-10-02 18:29:27 +0000165
Lang Hameseb6c8f52010-09-18 09:07:10 +0000166 if (!vregLI->overlaps(*pregLI))
167 continue;
Lang Hames030c4bf2010-01-26 04:49:58 +0000168
Lang Hameseb6c8f52010-09-18 09:07:10 +0000169 // Remove the register from the allowed set.
170 VRAllowed::iterator eraseItr =
171 std::find(vrAllowed.begin(), vrAllowed.end(), preg);
Evan Chengb1290a62008-10-02 18:29:27 +0000172
Lang Hameseb6c8f52010-09-18 09:07:10 +0000173 if (eraseItr != vrAllowed.end()) {
174 vrAllowed.erase(eraseItr);
175 }
Evan Chengb1290a62008-10-02 18:29:27 +0000176
Lang Hameseb6c8f52010-09-18 09:07:10 +0000177 // Also remove any aliases.
178 const unsigned *aliasItr = tri->getAliasSet(preg);
179 if (aliasItr != 0) {
180 for (; *aliasItr != 0; ++aliasItr) {
181 VRAllowed::iterator eraseItr =
182 std::find(vrAllowed.begin(), vrAllowed.end(), *aliasItr);
Evan Chengb1290a62008-10-02 18:29:27 +0000183
Lang Hameseb6c8f52010-09-18 09:07:10 +0000184 if (eraseItr != vrAllowed.end()) {
185 vrAllowed.erase(eraseItr);
186 }
187 }
188 }
189 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000190
Lang Hameseb6c8f52010-09-18 09:07:10 +0000191 // Construct the node.
192 PBQP::Graph::NodeItr node =
193 g.addNode(PBQP::Vector(vrAllowed.size() + 1, 0));
Evan Chengb1290a62008-10-02 18:29:27 +0000194
Lang Hameseb6c8f52010-09-18 09:07:10 +0000195 // Record the mapping and allowed set in the problem.
196 p->recordVReg(vreg, node, vrAllowed.begin(), vrAllowed.end());
Evan Chengb1290a62008-10-02 18:29:27 +0000197
Lang Hameseb6c8f52010-09-18 09:07:10 +0000198 PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
199 vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
Evan Chengb1290a62008-10-02 18:29:27 +0000200
Lang Hameseb6c8f52010-09-18 09:07:10 +0000201 addSpillCosts(g.getNodeCosts(node), spillCost);
202 }
Evan Chengb1290a62008-10-02 18:29:27 +0000203
Lang Hames481630d2010-09-18 09:49:08 +0000204 for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
Lang Hameseb6c8f52010-09-18 09:07:10 +0000205 vr1Itr != vrEnd; ++vr1Itr) {
206 unsigned vr1 = *vr1Itr;
207 const LiveInterval &l1 = lis->getInterval(vr1);
208 const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
Evan Chengb1290a62008-10-02 18:29:27 +0000209
Benjamin Kramer9e8d1f92010-09-18 14:41:26 +0000210 for (RegSet::const_iterator vr2Itr = llvm::next(vr1Itr);
Lang Hameseb6c8f52010-09-18 09:07:10 +0000211 vr2Itr != vrEnd; ++vr2Itr) {
212 unsigned vr2 = *vr2Itr;
213 const LiveInterval &l2 = lis->getInterval(vr2);
214 const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
Evan Chengb1290a62008-10-02 18:29:27 +0000215
Lang Hameseb6c8f52010-09-18 09:07:10 +0000216 assert(!l2.empty() && "Empty interval in vreg set?");
217 if (l1.overlaps(l2)) {
218 PBQP::Graph::EdgeItr edge =
219 g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
220 PBQP::Matrix(vr1Allowed.size()+1, vr2Allowed.size()+1, 0));
Lang Hames27601ef2008-11-16 12:12:54 +0000221
Lang Hameseb6c8f52010-09-18 09:07:10 +0000222 addInterferenceCosts(g.getEdgeCosts(edge), vr1Allowed, vr2Allowed, tri);
223 }
224 }
225 }
Evan Chengb1290a62008-10-02 18:29:27 +0000226
Lang Hameseb6c8f52010-09-18 09:07:10 +0000227 return p;
228}
Lang Hames27601ef2008-11-16 12:12:54 +0000229
Lang Hameseb6c8f52010-09-18 09:07:10 +0000230void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
231 PBQP::PBQPNum spillCost) {
232 costVec[0] = spillCost;
233}
Evan Chengb1290a62008-10-02 18:29:27 +0000234
Lang Hamese9c93562010-09-21 13:19:36 +0000235void PBQPBuilder::addInterferenceCosts(
236 PBQP::Matrix &costMat,
237 const PBQPRAProblem::AllowedSet &vr1Allowed,
238 const PBQPRAProblem::AllowedSet &vr2Allowed,
239 const TargetRegisterInfo *tri) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000240 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
241 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
242
243 for (unsigned i = 0; i < vr1Allowed.size(); ++i) {
244 unsigned preg1 = vr1Allowed[i];
245
246 for (unsigned j = 0; j < vr2Allowed.size(); ++j) {
247 unsigned preg2 = vr2Allowed[j];
248
249 if (tri->regsOverlap(preg1, preg2)) {
250 costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
251 }
252 }
253 }
Evan Chengb1290a62008-10-02 18:29:27 +0000254}
255
Lang Hamese9c93562010-09-21 13:19:36 +0000256std::auto_ptr<PBQPRAProblem> PBQPBuilderWithCoalescing::build(
257 MachineFunction *mf,
258 const LiveIntervals *lis,
259 const MachineLoopInfo *loopInfo,
260 const RegSet &vregs) {
261
262 std::auto_ptr<PBQPRAProblem> p = PBQPBuilder::build(mf, lis, loopInfo, vregs);
263 PBQP::Graph &g = p->getGraph();
264
265 const TargetMachine &tm = mf->getTarget();
266 CoalescerPair cp(*tm.getInstrInfo(), *tm.getRegisterInfo());
267
268 // Scan the machine function and add a coalescing cost whenever CoalescerPair
269 // gives the Ok.
270 for (MachineFunction::const_iterator mbbItr = mf->begin(),
271 mbbEnd = mf->end();
272 mbbItr != mbbEnd; ++mbbItr) {
273 const MachineBasicBlock *mbb = &*mbbItr;
274
275 for (MachineBasicBlock::const_iterator miItr = mbb->begin(),
276 miEnd = mbb->end();
277 miItr != miEnd; ++miItr) {
278 const MachineInstr *mi = &*miItr;
279
280 if (!mi->isCopy() && !mi->isSubregToReg())
281 continue; // Not coalescable.
282
283 if (!cp.setRegisters(mi))
284 continue; // Not coalescable.
285
286 if (cp.getSrcReg() == cp.getDstReg())
287 continue; // Already coalesced.
288
289 if (cp.isCoalescable(mi)) {
290
291 unsigned dst = cp.getDstReg(),
292 src = cp.getSrcReg();
293
294
295
Lang Hames08982912010-09-21 13:47:10 +0000296 PBQP::PBQPNum cBenefit =
297 std::pow(10.0f, (float)loopInfo->getLoopDepth(mbb));
Lang Hamese9c93562010-09-21 13:19:36 +0000298
299 if (cp.isPhys()) {
300 if (!lis->isAllocatable(dst))
301 continue;
302
303 const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
304 unsigned pregOpt = 0;
305 while (pregOpt < allowed.size() && allowed[pregOpt] != dst)
306 ++pregOpt;
307 if (pregOpt < allowed.size()) {
308 ++pregOpt; // +1 to account for spill option.
309 PBQP::Graph::NodeItr node = p->getNodeForVReg(src);
310 addPhysRegCoalesce(g.getNodeCosts(node), pregOpt, cBenefit);
311 }
312 } else {
313 const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
314 const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
315 PBQP::Graph::NodeItr node1 = p->getNodeForVReg(dst);
316 PBQP::Graph::NodeItr node2 = p->getNodeForVReg(src);
317 PBQP::Graph::EdgeItr edge = g.findEdge(node1, node2);
318 if (edge == g.edgesEnd()) {
319 edge = g.addEdge(node1, node2, PBQP::Matrix(allowed1->size() + 1,
320 allowed2->size() + 1,
321 0));
322 } else {
323 if (g.getEdgeNode1(edge) == node2) {
324 std::swap(node1, node2);
325 std::swap(allowed1, allowed2);
326 }
327 }
328
329 addVirtRegCoalesce(g.getEdgeCosts(edge), *allowed1, *allowed2,
330 cBenefit);
331 }
332 }
333 }
334 }
335
336 return p;
337}
338
339
340void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
341 unsigned pregOption,
342 PBQP::PBQPNum benefit) {
343 costVec[pregOption] += -benefit;
344}
345
346void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
347 PBQP::Matrix &costMat,
348 const PBQPRAProblem::AllowedSet &vr1Allowed,
349 const PBQPRAProblem::AllowedSet &vr2Allowed,
350 PBQP::PBQPNum benefit) {
351
352 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
353 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
354
355 for (unsigned i = 0; i < vr1Allowed.size(); ++i) {
356 unsigned preg1 = vr1Allowed[i];
357 for (unsigned j = 0; j < vr2Allowed.size(); ++j) {
358 unsigned preg2 = vr2Allowed[j];
359
360 if (preg1 == preg2) {
361 costMat[i + 1][j + 1] += -benefit;
362 }
363 }
364 }
365}
Evan Chengb1290a62008-10-02 18:29:27 +0000366
Lang Hameseb6c8f52010-09-18 09:07:10 +0000367
368void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
369 au.addRequired<SlotIndexes>();
370 au.addPreserved<SlotIndexes>();
371 au.addRequired<LiveIntervals>();
372 //au.addRequiredID(SplitCriticalEdgesID);
373 au.addRequired<RegisterCoalescer>();
374 au.addRequired<CalculateSpillWeights>();
375 au.addRequired<LiveStacks>();
376 au.addPreserved<LiveStacks>();
377 au.addRequired<MachineLoopInfo>();
378 au.addPreserved<MachineLoopInfo>();
379 if (pbqpPreSplitting)
380 au.addRequired<LoopSplitter>();
381 au.addRequired<VirtRegMap>();
382 au.addRequired<RenderMachineFunction>();
383 MachineFunctionPass::getAnalysisUsage(au);
384}
385
Lang Hames27601ef2008-11-16 12:12:54 +0000386template <typename RegContainer>
Lang Hameseb6c8f52010-09-18 09:07:10 +0000387PBQP::Vector RegAllocPBQP::buildCostVector(unsigned vReg,
Lang Hames6699fb22009-08-06 23:32:48 +0000388 const RegContainer &allowed,
389 const CoalesceMap &coalesces,
390 PBQP::PBQPNum spillCost) const {
Evan Chengb1290a62008-10-02 18:29:27 +0000391
Lang Hames27601ef2008-11-16 12:12:54 +0000392 typedef typename RegContainer::const_iterator AllowedItr;
393
Evan Chengb1290a62008-10-02 18:29:27 +0000394 // Allocate vector. Additional element (0th) used for spill option
Lang Hames6699fb22009-08-06 23:32:48 +0000395 PBQP::Vector v(allowed.size() + 1, 0);
Evan Chengb1290a62008-10-02 18:29:27 +0000396
Lang Hames6699fb22009-08-06 23:32:48 +0000397 v[0] = spillCost;
Evan Chengb1290a62008-10-02 18:29:27 +0000398
Lang Hames27601ef2008-11-16 12:12:54 +0000399 // Iterate over the allowed registers inserting coalesce benefits if there
400 // are any.
401 unsigned ai = 0;
402 for (AllowedItr itr = allowed.begin(), end = allowed.end();
403 itr != end; ++itr, ++ai) {
404
405 unsigned pReg = *itr;
406
407 CoalesceMap::const_iterator cmItr =
408 coalesces.find(RegPair(vReg, pReg));
409
410 // No coalesce - on to the next preg.
411 if (cmItr == coalesces.end())
412 continue;
Misha Brukman2a835f92009-01-08 15:50:22 +0000413
414 // We have a coalesce - insert the benefit.
Lang Hames6699fb22009-08-06 23:32:48 +0000415 v[ai + 1] = -cmItr->second;
Lang Hames27601ef2008-11-16 12:12:54 +0000416 }
417
Evan Chengb1290a62008-10-02 18:29:27 +0000418 return v;
419}
420
Lang Hames27601ef2008-11-16 12:12:54 +0000421template <typename RegContainer>
Lang Hameseb6c8f52010-09-18 09:07:10 +0000422PBQP::Matrix* RegAllocPBQP::buildInterferenceMatrix(
Lang Hames27601ef2008-11-16 12:12:54 +0000423 const RegContainer &allowed1, const RegContainer &allowed2) const {
Evan Chengb1290a62008-10-02 18:29:27 +0000424
Lang Hames27601ef2008-11-16 12:12:54 +0000425 typedef typename RegContainer::const_iterator RegContainerIterator;
Evan Chengb1290a62008-10-02 18:29:27 +0000426
427 // Construct a PBQP matrix representing the cost of allocation options. The
428 // rows and columns correspond to the allocation options for the two live
429 // intervals. Elements will be infinite where corresponding registers alias,
430 // since we cannot allocate aliasing registers to interfering live intervals.
431 // All other elements (non-aliasing combinations) will have zero cost. Note
432 // that the spill option (element 0,0) has zero cost, since we can allocate
433 // both intervals to memory safely (the cost for each individual allocation
434 // to memory is accounted for by the cost vectors for each live interval).
Lang Hames6699fb22009-08-06 23:32:48 +0000435 PBQP::Matrix *m =
436 new PBQP::Matrix(allowed1.size() + 1, allowed2.size() + 1, 0);
Misha Brukman2a835f92009-01-08 15:50:22 +0000437
Evan Chengb1290a62008-10-02 18:29:27 +0000438 // Assume this is a zero matrix until proven otherwise. Zero matrices occur
439 // between interfering live ranges with non-overlapping register sets (e.g.
440 // non-overlapping reg classes, or disjoint sets of allowed regs within the
441 // same class). The term "overlapping" is used advisedly: sets which do not
442 // intersect, but contain registers which alias, will have non-zero matrices.
443 // We optimize zero matrices away to improve solver speed.
444 bool isZeroMatrix = true;
445
446
447 // Row index. Starts at 1, since the 0th row is for the spill option, which
448 // is always zero.
Misha Brukman2a835f92009-01-08 15:50:22 +0000449 unsigned ri = 1;
Evan Chengb1290a62008-10-02 18:29:27 +0000450
Misha Brukman2a835f92009-01-08 15:50:22 +0000451 // Iterate over allowed sets, insert infinities where required.
Lang Hames27601ef2008-11-16 12:12:54 +0000452 for (RegContainerIterator a1Itr = allowed1.begin(), a1End = allowed1.end();
Evan Chengb1290a62008-10-02 18:29:27 +0000453 a1Itr != a1End; ++a1Itr) {
454
455 // Column index, starts at 1 as for row index.
456 unsigned ci = 1;
457 unsigned reg1 = *a1Itr;
458
Lang Hames27601ef2008-11-16 12:12:54 +0000459 for (RegContainerIterator a2Itr = allowed2.begin(), a2End = allowed2.end();
Evan Chengb1290a62008-10-02 18:29:27 +0000460 a2Itr != a2End; ++a2Itr) {
461
462 unsigned reg2 = *a2Itr;
463
464 // If the row/column regs are identical or alias insert an infinity.
Lang Hames3f2f3f52009-09-03 02:52:02 +0000465 if (tri->regsOverlap(reg1, reg2)) {
Lang Hames6699fb22009-08-06 23:32:48 +0000466 (*m)[ri][ci] = std::numeric_limits<PBQP::PBQPNum>::infinity();
Evan Chengb1290a62008-10-02 18:29:27 +0000467 isZeroMatrix = false;
468 }
469
470 ++ci;
471 }
472
473 ++ri;
474 }
475
476 // If this turns out to be a zero matrix...
477 if (isZeroMatrix) {
478 // free it and return null.
479 delete m;
480 return 0;
481 }
482
483 // ...otherwise return the cost matrix.
484 return m;
485}
486
Lang Hames27601ef2008-11-16 12:12:54 +0000487template <typename RegContainer>
Lang Hameseb6c8f52010-09-18 09:07:10 +0000488PBQP::Matrix* RegAllocPBQP::buildCoalescingMatrix(
Lang Hames27601ef2008-11-16 12:12:54 +0000489 const RegContainer &allowed1, const RegContainer &allowed2,
Lang Hames6699fb22009-08-06 23:32:48 +0000490 PBQP::PBQPNum cBenefit) const {
Evan Chengb1290a62008-10-02 18:29:27 +0000491
Lang Hames27601ef2008-11-16 12:12:54 +0000492 typedef typename RegContainer::const_iterator RegContainerIterator;
493
494 // Construct a PBQP Matrix representing the benefits of coalescing. As with
495 // interference matrices the rows and columns represent allowed registers
496 // for the LiveIntervals which are (potentially) to be coalesced. The amount
497 // -cBenefit will be placed in any element representing the same register
498 // for both intervals.
Lang Hames6699fb22009-08-06 23:32:48 +0000499 PBQP::Matrix *m =
500 new PBQP::Matrix(allowed1.size() + 1, allowed2.size() + 1, 0);
Lang Hames27601ef2008-11-16 12:12:54 +0000501
502 // Reset costs to zero.
503 m->reset(0);
504
505 // Assume the matrix is zero till proven otherwise. Zero matrices will be
506 // optimized away as in the interference case.
507 bool isZeroMatrix = true;
508
509 // Row index. Starts at 1, since the 0th row is for the spill option, which
510 // is always zero.
511 unsigned ri = 1;
512
513 // Iterate over the allowed sets, insert coalescing benefits where
514 // appropriate.
515 for (RegContainerIterator a1Itr = allowed1.begin(), a1End = allowed1.end();
516 a1Itr != a1End; ++a1Itr) {
517
518 // Column index, starts at 1 as for row index.
519 unsigned ci = 1;
520 unsigned reg1 = *a1Itr;
521
522 for (RegContainerIterator a2Itr = allowed2.begin(), a2End = allowed2.end();
523 a2Itr != a2End; ++a2Itr) {
524
525 // If the row and column represent the same register insert a beneficial
526 // cost to preference this allocation - it would allow us to eliminate a
Misha Brukman2a835f92009-01-08 15:50:22 +0000527 // move instruction.
Lang Hames27601ef2008-11-16 12:12:54 +0000528 if (reg1 == *a2Itr) {
529 (*m)[ri][ci] = -cBenefit;
530 isZeroMatrix = false;
531 }
532
533 ++ci;
534 }
535
536 ++ri;
537 }
538
539 // If this turns out to be a zero matrix...
540 if (isZeroMatrix) {
541 // ...free it and return null.
542 delete m;
543 return 0;
544 }
545
546 return m;
547}
548
Lang Hameseb6c8f52010-09-18 09:07:10 +0000549RegAllocPBQP::CoalesceMap RegAllocPBQP::findCoalesces() {
Lang Hames27601ef2008-11-16 12:12:54 +0000550
551 typedef MachineFunction::const_iterator MFIterator;
552 typedef MachineBasicBlock::const_iterator MBBIterator;
553 typedef LiveInterval::const_vni_iterator VNIIterator;
Misha Brukman2a835f92009-01-08 15:50:22 +0000554
Lang Hames27601ef2008-11-16 12:12:54 +0000555 CoalesceMap coalescesFound;
556
557 // To find coalesces we need to iterate over the function looking for
558 // copy instructions.
559 for (MFIterator bbItr = mf->begin(), bbEnd = mf->end();
Evan Chengb1290a62008-10-02 18:29:27 +0000560 bbItr != bbEnd; ++bbItr) {
561
562 const MachineBasicBlock *mbb = &*bbItr;
Evan Chengb1290a62008-10-02 18:29:27 +0000563
Lang Hames27601ef2008-11-16 12:12:54 +0000564 for (MBBIterator iItr = mbb->begin(), iEnd = mbb->end();
565 iItr != iEnd; ++iItr) {
Evan Chengb1290a62008-10-02 18:29:27 +0000566
567 const MachineInstr *instr = &*iItr;
568
Lang Hames27601ef2008-11-16 12:12:54 +0000569 // If this isn't a copy then continue to the next instruction.
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000570 if (!instr->isCopy())
Lang Hames27601ef2008-11-16 12:12:54 +0000571 continue;
Evan Chengb1290a62008-10-02 18:29:27 +0000572
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000573 unsigned srcReg = instr->getOperand(1).getReg();
574 unsigned dstReg = instr->getOperand(0).getReg();
575
Lang Hames27601ef2008-11-16 12:12:54 +0000576 // If the registers are already the same our job is nice and easy.
577 if (dstReg == srcReg)
578 continue;
Evan Chengb1290a62008-10-02 18:29:27 +0000579
Lang Hames27601ef2008-11-16 12:12:54 +0000580 bool srcRegIsPhysical = TargetRegisterInfo::isPhysicalRegister(srcReg),
581 dstRegIsPhysical = TargetRegisterInfo::isPhysicalRegister(dstReg);
582
583 // If both registers are physical then we can't coalesce.
584 if (srcRegIsPhysical && dstRegIsPhysical)
585 continue;
Misha Brukman2a835f92009-01-08 15:50:22 +0000586
Rafael Espindolacbeb3db2010-07-12 01:45:38 +0000587 // If it's a copy that includes two virtual register but the source and
588 // destination classes differ then we can't coalesce.
589 if (!srcRegIsPhysical && !dstRegIsPhysical &&
590 mri->getRegClass(srcReg) != mri->getRegClass(dstReg))
Lang Hames27601ef2008-11-16 12:12:54 +0000591 continue;
592
Rafael Espindolacbeb3db2010-07-12 01:45:38 +0000593 // If one is physical and one is virtual, check that the physical is
594 // allocatable in the class of the virtual.
595 if (srcRegIsPhysical && !dstRegIsPhysical) {
596 const TargetRegisterClass *dstRegClass = mri->getRegClass(dstReg);
Lang Hames0b23dc02010-02-09 00:50:27 +0000597 if (std::find(dstRegClass->allocation_order_begin(*mf),
598 dstRegClass->allocation_order_end(*mf), srcReg) ==
599 dstRegClass->allocation_order_end(*mf))
Evan Chengb1290a62008-10-02 18:29:27 +0000600 continue;
Evan Chengb1290a62008-10-02 18:29:27 +0000601 }
Rafael Espindolacbeb3db2010-07-12 01:45:38 +0000602 if (!srcRegIsPhysical && dstRegIsPhysical) {
603 const TargetRegisterClass *srcRegClass = mri->getRegClass(srcReg);
Lang Hames0b23dc02010-02-09 00:50:27 +0000604 if (std::find(srcRegClass->allocation_order_begin(*mf),
605 srcRegClass->allocation_order_end(*mf), dstReg) ==
606 srcRegClass->allocation_order_end(*mf))
Lang Hames27601ef2008-11-16 12:12:54 +0000607 continue;
608 }
609
610 // If we've made it here we have a copy with compatible register classes.
Misha Brukman2a835f92009-01-08 15:50:22 +0000611 // We can probably coalesce, but we need to consider overlap.
Lang Hames27601ef2008-11-16 12:12:54 +0000612 const LiveInterval *srcLI = &lis->getInterval(srcReg),
613 *dstLI = &lis->getInterval(dstReg);
614
615 if (srcLI->overlaps(*dstLI)) {
616 // Even in the case of an overlap we might still be able to coalesce,
617 // but we need to make sure that no definition of either range occurs
618 // while the other range is live.
619
620 // Otherwise start by assuming we're ok.
621 bool badDef = false;
622
623 // Test all defs of the source range.
Misha Brukman2a835f92009-01-08 15:50:22 +0000624 for (VNIIterator
Lang Hames27601ef2008-11-16 12:12:54 +0000625 vniItr = srcLI->vni_begin(), vniEnd = srcLI->vni_end();
626 vniItr != vniEnd; ++vniItr) {
627
Lang Hames0b23dc02010-02-09 00:50:27 +0000628 // If we find a poorly defined def we err on the side of caution.
629 if (!(*vniItr)->def.isValid()) {
630 badDef = true;
631 break;
632 }
633
Lang Hames27601ef2008-11-16 12:12:54 +0000634 // If we find a def that kills the coalescing opportunity then
635 // record it and break from the loop.
636 if (dstLI->liveAt((*vniItr)->def)) {
637 badDef = true;
638 break;
639 }
640 }
641
642 // If we have a bad def give up, continue to the next instruction.
643 if (badDef)
644 continue;
Misha Brukman2a835f92009-01-08 15:50:22 +0000645
Lang Hames27601ef2008-11-16 12:12:54 +0000646 // Otherwise test definitions of the destination range.
647 for (VNIIterator
648 vniItr = dstLI->vni_begin(), vniEnd = dstLI->vni_end();
649 vniItr != vniEnd; ++vniItr) {
Misha Brukman2a835f92009-01-08 15:50:22 +0000650
Lang Hames27601ef2008-11-16 12:12:54 +0000651 // We want to make sure we skip the copy instruction itself.
Lang Hames52c1afc2009-08-10 23:43:28 +0000652 if ((*vniItr)->getCopy() == instr)
Lang Hames27601ef2008-11-16 12:12:54 +0000653 continue;
654
Lang Hames0b23dc02010-02-09 00:50:27 +0000655 if (!(*vniItr)->def.isValid()) {
656 badDef = true;
657 break;
658 }
659
Lang Hames27601ef2008-11-16 12:12:54 +0000660 if (srcLI->liveAt((*vniItr)->def)) {
661 badDef = true;
662 break;
663 }
664 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000665
Lang Hames27601ef2008-11-16 12:12:54 +0000666 // As before a bad def we give up and continue to the next instr.
667 if (badDef)
668 continue;
669 }
670
671 // If we make it to here then either the ranges didn't overlap, or they
672 // did, but none of their definitions would prevent us from coalescing.
673 // We're good to go with the coalesce.
674
Chris Lattner87565c12010-05-15 17:10:24 +0000675 float cBenefit = std::pow(10.0f, (float)loopInfo->getLoopDepth(mbb)) / 5.0;
Misha Brukman2a835f92009-01-08 15:50:22 +0000676
Lang Hames27601ef2008-11-16 12:12:54 +0000677 coalescesFound[RegPair(srcReg, dstReg)] = cBenefit;
678 coalescesFound[RegPair(dstReg, srcReg)] = cBenefit;
Evan Chengb1290a62008-10-02 18:29:27 +0000679 }
680
681 }
682
Lang Hames27601ef2008-11-16 12:12:54 +0000683 return coalescesFound;
684}
685
Lang Hameseb6c8f52010-09-18 09:07:10 +0000686void RegAllocPBQP::findVRegIntervalsToAlloc() {
Lang Hames27601ef2008-11-16 12:12:54 +0000687
688 // Iterate over all live ranges.
689 for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
690 itr != end; ++itr) {
691
692 // Ignore physical ones.
693 if (TargetRegisterInfo::isPhysicalRegister(itr->first))
694 continue;
695
696 LiveInterval *li = itr->second;
697
698 // If this live interval is non-empty we will use pbqp to allocate it.
699 // Empty intervals we allocate in a simple post-processing stage in
700 // finalizeAlloc.
701 if (!li->empty()) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000702 vregsToAlloc.insert(li->reg);
Lang Hames27601ef2008-11-16 12:12:54 +0000703 }
704 else {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000705 emptyIntervalVRegs.insert(li->reg);
Lang Hames27601ef2008-11-16 12:12:54 +0000706 }
707 }
Evan Chengb1290a62008-10-02 18:29:27 +0000708}
709
Lang Hameseb6c8f52010-09-18 09:07:10 +0000710PBQP::Graph RegAllocPBQP::constructPBQPProblem() {
Evan Chengb1290a62008-10-02 18:29:27 +0000711
712 typedef std::vector<const LiveInterval*> LIVector;
Lang Hames27601ef2008-11-16 12:12:54 +0000713 typedef std::vector<unsigned> RegVector;
Evan Chengb1290a62008-10-02 18:29:27 +0000714
Lang Hames27601ef2008-11-16 12:12:54 +0000715 // This will store the physical intervals for easy reference.
716 LIVector physIntervals;
Evan Chengb1290a62008-10-02 18:29:27 +0000717
718 // Start by clearing the old node <-> live interval mappings & allowed sets
719 li2Node.clear();
720 node2LI.clear();
721 allowedSets.clear();
722
Lang Hames27601ef2008-11-16 12:12:54 +0000723 // Populate physIntervals, update preg use:
724 for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
Evan Chengb1290a62008-10-02 18:29:27 +0000725 itr != end; ++itr) {
726
Evan Chengb1290a62008-10-02 18:29:27 +0000727 if (TargetRegisterInfo::isPhysicalRegister(itr->first)) {
728 physIntervals.push_back(itr->second);
729 mri->setPhysRegUsed(itr->second->reg);
730 }
Evan Chengb1290a62008-10-02 18:29:27 +0000731 }
732
Lang Hames27601ef2008-11-16 12:12:54 +0000733 // Iterate over vreg intervals, construct live interval <-> node number
734 // mappings.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000735 for (RegSet::const_iterator itr = vregsToAlloc.begin(),
736 end = vregsToAlloc.end();
Lang Hames27601ef2008-11-16 12:12:54 +0000737 itr != end; ++itr) {
Lang Hameseb6c8f52010-09-18 09:07:10 +0000738 const LiveInterval *li = &lis->getInterval(*itr);
Lang Hames27601ef2008-11-16 12:12:54 +0000739
740 li2Node[li] = node2LI.size();
741 node2LI.push_back(li);
742 }
743
744 // Get the set of potential coalesces.
Lang Hames8481e3b2009-08-19 01:36:14 +0000745 CoalesceMap coalesces;
746
747 if (pbqpCoalescing) {
748 coalesces = findCoalesces();
749 }
Evan Chengb1290a62008-10-02 18:29:27 +0000750
751 // Construct a PBQP solver for this problem
Lang Hames030c4bf2010-01-26 04:49:58 +0000752 PBQP::Graph problem;
Lang Hameseb6c8f52010-09-18 09:07:10 +0000753 problemNodes.resize(vregsToAlloc.size());
Evan Chengb1290a62008-10-02 18:29:27 +0000754
755 // Resize allowedSets container appropriately.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000756 allowedSets.resize(vregsToAlloc.size());
Evan Chengb1290a62008-10-02 18:29:27 +0000757
Jim Grosbach269354e2010-09-01 21:23:03 +0000758 BitVector ReservedRegs = tri->getReservedRegs(*mf);
759
Evan Chengb1290a62008-10-02 18:29:27 +0000760 // Iterate over virtual register intervals to compute allowed sets...
761 for (unsigned node = 0; node < node2LI.size(); ++node) {
762
763 // Grab pointers to the interval and its register class.
764 const LiveInterval *li = node2LI[node];
765 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
Misha Brukman2a835f92009-01-08 15:50:22 +0000766
Evan Chengb1290a62008-10-02 18:29:27 +0000767 // Start by assuming all allocable registers in the class are allowed...
Jim Grosbach269354e2010-09-01 21:23:03 +0000768 RegVector liAllowed;
769 TargetRegisterClass::iterator aob = liRC->allocation_order_begin(*mf);
770 TargetRegisterClass::iterator aoe = liRC->allocation_order_end(*mf);
771 for (TargetRegisterClass::iterator it = aob; it != aoe; ++it)
772 if (!ReservedRegs.test(*it))
773 liAllowed.push_back(*it);
Evan Chengb1290a62008-10-02 18:29:27 +0000774
Lang Hames27601ef2008-11-16 12:12:54 +0000775 // Eliminate the physical registers which overlap with this range, along
776 // with all their aliases.
777 for (LIVector::iterator pItr = physIntervals.begin(),
778 pEnd = physIntervals.end(); pItr != pEnd; ++pItr) {
Evan Chengb1290a62008-10-02 18:29:27 +0000779
Lang Hames27601ef2008-11-16 12:12:54 +0000780 if (!li->overlaps(**pItr))
781 continue;
Evan Chengb1290a62008-10-02 18:29:27 +0000782
Lang Hames27601ef2008-11-16 12:12:54 +0000783 unsigned pReg = (*pItr)->reg;
Evan Chengb1290a62008-10-02 18:29:27 +0000784
Lang Hames27601ef2008-11-16 12:12:54 +0000785 // If we get here then the live intervals overlap, but we're still ok
786 // if they're coalescable.
Lang Hameseb6c8f52010-09-18 09:07:10 +0000787 if (coalesces.find(RegPair(li->reg, pReg)) != coalesces.end()) {
788 DEBUG(dbgs() << "CoalescingOverride: (" << li->reg << ", " << pReg << ")\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000789 continue;
Lang Hameseb6c8f52010-09-18 09:07:10 +0000790 }
Evan Chengb1290a62008-10-02 18:29:27 +0000791
Lang Hames27601ef2008-11-16 12:12:54 +0000792 // If we get here then we have a genuine exclusion.
Evan Chengb1290a62008-10-02 18:29:27 +0000793
Lang Hames27601ef2008-11-16 12:12:54 +0000794 // Remove the overlapping reg...
795 RegVector::iterator eraseItr =
796 std::find(liAllowed.begin(), liAllowed.end(), pReg);
Misha Brukman2a835f92009-01-08 15:50:22 +0000797
Lang Hames27601ef2008-11-16 12:12:54 +0000798 if (eraseItr != liAllowed.end())
799 liAllowed.erase(eraseItr);
Evan Chengb1290a62008-10-02 18:29:27 +0000800
Lang Hames27601ef2008-11-16 12:12:54 +0000801 const unsigned *aliasItr = tri->getAliasSet(pReg);
802
803 if (aliasItr != 0) {
804 // ...and its aliases.
805 for (; *aliasItr != 0; ++aliasItr) {
806 RegVector::iterator eraseItr =
807 std::find(liAllowed.begin(), liAllowed.end(), *aliasItr);
Misha Brukman2a835f92009-01-08 15:50:22 +0000808
Lang Hames27601ef2008-11-16 12:12:54 +0000809 if (eraseItr != liAllowed.end()) {
810 liAllowed.erase(eraseItr);
Evan Chengb1290a62008-10-02 18:29:27 +0000811 }
Evan Chengb1290a62008-10-02 18:29:27 +0000812 }
Evan Chengb1290a62008-10-02 18:29:27 +0000813 }
Evan Chengb1290a62008-10-02 18:29:27 +0000814 }
815
816 // Copy the allowed set into a member vector for use when constructing cost
817 // vectors & matrices, and mapping PBQP solutions back to assignments.
818 allowedSets[node] = AllowedSet(liAllowed.begin(), liAllowed.end());
819
820 // Set the spill cost to the interval weight, or epsilon if the
821 // interval weight is zero
Lang Hames6699fb22009-08-06 23:32:48 +0000822 PBQP::PBQPNum spillCost = (li->weight != 0.0) ?
823 li->weight : std::numeric_limits<PBQP::PBQPNum>::min();
Evan Chengb1290a62008-10-02 18:29:27 +0000824
825 // Build a cost vector for this interval.
Lang Hames6699fb22009-08-06 23:32:48 +0000826 problemNodes[node] =
827 problem.addNode(
828 buildCostVector(li->reg, allowedSets[node], coalesces, spillCost));
Evan Chengb1290a62008-10-02 18:29:27 +0000829
830 }
831
Lang Hames27601ef2008-11-16 12:12:54 +0000832
Evan Chengb1290a62008-10-02 18:29:27 +0000833 // Now add the cost matrices...
834 for (unsigned node1 = 0; node1 < node2LI.size(); ++node1) {
Evan Chengb1290a62008-10-02 18:29:27 +0000835 const LiveInterval *li = node2LI[node1];
836
Evan Chengb1290a62008-10-02 18:29:27 +0000837 // Test for live range overlaps and insert interference matrices.
838 for (unsigned node2 = node1 + 1; node2 < node2LI.size(); ++node2) {
839 const LiveInterval *li2 = node2LI[node2];
840
Lang Hames27601ef2008-11-16 12:12:54 +0000841 CoalesceMap::const_iterator cmItr =
842 coalesces.find(RegPair(li->reg, li2->reg));
Evan Chengb1290a62008-10-02 18:29:27 +0000843
Lang Hames6699fb22009-08-06 23:32:48 +0000844 PBQP::Matrix *m = 0;
Evan Chengb1290a62008-10-02 18:29:27 +0000845
Lang Hames27601ef2008-11-16 12:12:54 +0000846 if (cmItr != coalesces.end()) {
847 m = buildCoalescingMatrix(allowedSets[node1], allowedSets[node2],
848 cmItr->second);
849 }
850 else if (li->overlaps(*li2)) {
851 m = buildInterferenceMatrix(allowedSets[node1], allowedSets[node2]);
852 }
Misha Brukman2a835f92009-01-08 15:50:22 +0000853
Lang Hames27601ef2008-11-16 12:12:54 +0000854 if (m != 0) {
Lang Hames6699fb22009-08-06 23:32:48 +0000855 problem.addEdge(problemNodes[node1],
856 problemNodes[node2],
857 *m);
858
Lang Hames27601ef2008-11-16 12:12:54 +0000859 delete m;
Evan Chengb1290a62008-10-02 18:29:27 +0000860 }
861 }
862 }
863
Lang Hames6699fb22009-08-06 23:32:48 +0000864 assert(problem.getNumNodes() == allowedSets.size());
Lang Hames6699fb22009-08-06 23:32:48 +0000865/*
866 std::cerr << "Allocating for " << problem.getNumNodes() << " nodes, "
867 << problem.getNumEdges() << " edges.\n";
868
869 problem.printDot(std::cerr);
870*/
Evan Chengb1290a62008-10-02 18:29:27 +0000871 // We're done, PBQP problem constructed - return it.
Lang Hames6699fb22009-08-06 23:32:48 +0000872 return problem;
Evan Chengb1290a62008-10-02 18:29:27 +0000873}
874
Lang Hameseb6c8f52010-09-18 09:07:10 +0000875void RegAllocPBQP::addStackInterval(const LiveInterval *spilled,
Evan Chengc781a242009-05-03 18:32:42 +0000876 MachineRegisterInfo* mri) {
Lang Hames27601ef2008-11-16 12:12:54 +0000877 int stackSlot = vrm->getStackSlot(spilled->reg);
Misha Brukman2a835f92009-01-08 15:50:22 +0000878
879 if (stackSlot == VirtRegMap::NO_STACK_SLOT)
Lang Hames27601ef2008-11-16 12:12:54 +0000880 return;
881
Evan Chengc781a242009-05-03 18:32:42 +0000882 const TargetRegisterClass *RC = mri->getRegClass(spilled->reg);
883 LiveInterval &stackInterval = lss->getOrCreateInterval(stackSlot, RC);
Lang Hames27601ef2008-11-16 12:12:54 +0000884
885 VNInfo *vni;
886 if (stackInterval.getNumValNums() != 0)
887 vni = stackInterval.getValNumInfo(0);
888 else
Lang Hames86511252009-09-04 20:41:11 +0000889 vni = stackInterval.getNextValue(
Lang Hames233a60e2009-11-03 23:52:08 +0000890 SlotIndex(), 0, false, lss->getVNInfoAllocator());
Lang Hames27601ef2008-11-16 12:12:54 +0000891
892 LiveInterval &rhsInterval = lis->getInterval(spilled->reg);
893 stackInterval.MergeRangesInAsValue(rhsInterval, vni);
894}
895
Lang Hameseb6c8f52010-09-18 09:07:10 +0000896bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQP::Solution &solution) {
Lang Hamese98b4b02009-11-15 04:39:51 +0000897
Evan Chengb1290a62008-10-02 18:29:27 +0000898 // Set to true if we have any spills
899 bool anotherRoundNeeded = false;
900
901 // Clear the existing allocation.
902 vrm->clearAllVirt();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000903
Evan Chengb1290a62008-10-02 18:29:27 +0000904 // Iterate over the nodes mapping the PBQP solution to a register assignment.
905 for (unsigned node = 0; node < node2LI.size(); ++node) {
Lang Hames27601ef2008-11-16 12:12:54 +0000906 unsigned virtReg = node2LI[node]->reg,
Lang Hames030c4bf2010-01-26 04:49:58 +0000907 allocSelection = solution.getSelection(problemNodes[node]);
Lang Hames6699fb22009-08-06 23:32:48 +0000908
Evan Chengb1290a62008-10-02 18:29:27 +0000909
910 // If the PBQP solution is non-zero it's a physical register...
911 if (allocSelection != 0) {
912 // Get the physical reg, subtracting 1 to account for the spill option.
913 unsigned physReg = allowedSets[node][allocSelection - 1];
914
David Greene30931542010-01-05 01:25:43 +0000915 DEBUG(dbgs() << "VREG " << virtReg << " -> "
Lang Hameseb6c8f52010-09-18 09:07:10 +0000916 << tri->getName(physReg) << " (Option: " << allocSelection << ")\n");
Lang Hames27601ef2008-11-16 12:12:54 +0000917
918 assert(physReg != 0);
919
Evan Chengb1290a62008-10-02 18:29:27 +0000920 // Add to the virt reg map and update the used phys regs.
Lang Hames27601ef2008-11-16 12:12:54 +0000921 vrm->assignVirt2Phys(virtReg, physReg);
Evan Chengb1290a62008-10-02 18:29:27 +0000922 }
923 // ...Otherwise it's a spill.
924 else {
925
926 // Make sure we ignore this virtual reg on the next round
927 // of allocation
Lang Hameseb6c8f52010-09-18 09:07:10 +0000928 vregsToAlloc.erase(virtReg);
Evan Chengb1290a62008-10-02 18:29:27 +0000929
Evan Chengb1290a62008-10-02 18:29:27 +0000930 // Insert spill ranges for this live range
Lang Hames27601ef2008-11-16 12:12:54 +0000931 const LiveInterval *spillInterval = node2LI[node];
932 double oldSpillWeight = spillInterval->weight;
Evan Chengb1290a62008-10-02 18:29:27 +0000933 SmallVector<LiveInterval*, 8> spillIs;
Lang Hames33198392010-09-02 08:27:00 +0000934 rmf->rememberUseDefs(spillInterval);
Evan Chengb1290a62008-10-02 18:29:27 +0000935 std::vector<LiveInterval*> newSpills =
Evan Chengc781a242009-05-03 18:32:42 +0000936 lis->addIntervalsForSpills(*spillInterval, spillIs, loopInfo, *vrm);
937 addStackInterval(spillInterval, mri);
Lang Hames33198392010-09-02 08:27:00 +0000938 rmf->rememberSpills(spillInterval, newSpills);
Lang Hames27601ef2008-11-16 12:12:54 +0000939
Daniel Dunbarbc84ad92009-08-20 20:01:34 +0000940 (void) oldSpillWeight;
Lang Hameseb6c8f52010-09-18 09:07:10 +0000941 DEBUG(dbgs() << "VREG " << virtReg << " -> SPILLED (Option: 0, Cost: "
Lang Hames233fd9c2009-08-18 23:34:50 +0000942 << oldSpillWeight << ", New vregs: ");
Lang Hames27601ef2008-11-16 12:12:54 +0000943
944 // Copy any newly inserted live intervals into the list of regs to
945 // allocate.
946 for (std::vector<LiveInterval*>::const_iterator
947 itr = newSpills.begin(), end = newSpills.end();
948 itr != end; ++itr) {
949
950 assert(!(*itr)->empty() && "Empty spill range.");
951
David Greene30931542010-01-05 01:25:43 +0000952 DEBUG(dbgs() << (*itr)->reg << " ");
Lang Hames27601ef2008-11-16 12:12:54 +0000953
Lang Hameseb6c8f52010-09-18 09:07:10 +0000954 vregsToAlloc.insert((*itr)->reg);
Lang Hames27601ef2008-11-16 12:12:54 +0000955 }
956
David Greene30931542010-01-05 01:25:43 +0000957 DEBUG(dbgs() << ")\n");
Evan Chengb1290a62008-10-02 18:29:27 +0000958
959 // We need another round if spill intervals were added.
960 anotherRoundNeeded |= !newSpills.empty();
961 }
962 }
963
964 return !anotherRoundNeeded;
965}
966
Lang Hameseb6c8f52010-09-18 09:07:10 +0000967bool RegAllocPBQP::mapPBQPToRegAlloc2(const PBQPRAProblem &problem,
968 const PBQP::Solution &solution) {
969 // Set to true if we have any spills
970 bool anotherRoundNeeded = false;
971
972 // Clear the existing allocation.
973 vrm->clearAllVirt();
974
975 const PBQP::Graph &g = problem.getGraph();
976 // Iterate over the nodes mapping the PBQP solution to a register
977 // assignment.
978 for (PBQP::Graph::ConstNodeItr node = g.nodesBegin(),
979 nodeEnd = g.nodesEnd();
980 node != nodeEnd; ++node) {
981 unsigned vreg = problem.getVRegForNode(node);
982 unsigned alloc = solution.getSelection(node);
983
984 if (problem.isPRegOption(vreg, alloc)) {
985 unsigned preg = problem.getPRegForOption(vreg, alloc);
986 DEBUG(dbgs() << "VREG " << vreg << " -> " << tri->getName(preg) << "\n");
987 assert(preg != 0 && "Invalid preg selected.");
988 vrm->assignVirt2Phys(vreg, preg);
989 } else if (problem.isSpillOption(vreg, alloc)) {
990 vregsToAlloc.erase(vreg);
991 const LiveInterval* spillInterval = &lis->getInterval(vreg);
992 double oldWeight = spillInterval->weight;
993 SmallVector<LiveInterval*, 8> spillIs;
994 rmf->rememberUseDefs(spillInterval);
995 std::vector<LiveInterval*> newSpills =
996 lis->addIntervalsForSpills(*spillInterval, spillIs, loopInfo, *vrm);
997 addStackInterval(spillInterval, mri);
998 rmf->rememberSpills(spillInterval, newSpills);
999
1000 (void) oldWeight;
1001 DEBUG(dbgs() << "VREG " << vreg << " -> SPILLED (Cost: "
1002 << oldWeight << ", New vregs: ");
1003
1004 // Copy any newly inserted live intervals into the list of regs to
1005 // allocate.
1006 for (std::vector<LiveInterval*>::const_iterator
1007 itr = newSpills.begin(), end = newSpills.end();
1008 itr != end; ++itr) {
1009 assert(!(*itr)->empty() && "Empty spill range.");
1010 DEBUG(dbgs() << (*itr)->reg << " ");
1011 vregsToAlloc.insert((*itr)->reg);
1012 }
1013
1014 DEBUG(dbgs() << ")\n");
1015
1016 // We need another round if spill intervals were added.
1017 anotherRoundNeeded |= !newSpills.empty();
1018 } else {
1019 assert(false && "Unknown allocation option.");
1020 }
1021 }
1022
1023 return !anotherRoundNeeded;
1024}
1025
1026
1027void RegAllocPBQP::finalizeAlloc() const {
Lang Hames27601ef2008-11-16 12:12:54 +00001028 typedef LiveIntervals::iterator LIIterator;
1029 typedef LiveInterval::Ranges::const_iterator LRIterator;
1030
1031 // First allocate registers for the empty intervals.
Lang Hameseb6c8f52010-09-18 09:07:10 +00001032 for (RegSet::const_iterator
1033 itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
Lang Hames27601ef2008-11-16 12:12:54 +00001034 itr != end; ++itr) {
Lang Hameseb6c8f52010-09-18 09:07:10 +00001035 LiveInterval *li = &lis->getInterval(*itr);
Lang Hames27601ef2008-11-16 12:12:54 +00001036
Evan Cheng90f95f82009-06-14 20:22:55 +00001037 unsigned physReg = vrm->getRegAllocPref(li->reg);
Lang Hames6699fb22009-08-06 23:32:48 +00001038
Lang Hames27601ef2008-11-16 12:12:54 +00001039 if (physReg == 0) {
1040 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
Misha Brukman2a835f92009-01-08 15:50:22 +00001041 physReg = *liRC->allocation_order_begin(*mf);
Lang Hames27601ef2008-11-16 12:12:54 +00001042 }
Misha Brukman2a835f92009-01-08 15:50:22 +00001043
1044 vrm->assignVirt2Phys(li->reg, physReg);
Lang Hames27601ef2008-11-16 12:12:54 +00001045 }
Misha Brukman2a835f92009-01-08 15:50:22 +00001046
Lang Hames27601ef2008-11-16 12:12:54 +00001047 // Finally iterate over the basic blocks to compute and set the live-in sets.
1048 SmallVector<MachineBasicBlock*, 8> liveInMBBs;
1049 MachineBasicBlock *entryMBB = &*mf->begin();
1050
1051 for (LIIterator liItr = lis->begin(), liEnd = lis->end();
1052 liItr != liEnd; ++liItr) {
1053
1054 const LiveInterval *li = liItr->second;
1055 unsigned reg = 0;
Misha Brukman2a835f92009-01-08 15:50:22 +00001056
Lang Hames27601ef2008-11-16 12:12:54 +00001057 // Get the physical register for this interval
1058 if (TargetRegisterInfo::isPhysicalRegister(li->reg)) {
1059 reg = li->reg;
1060 }
1061 else if (vrm->isAssignedReg(li->reg)) {
1062 reg = vrm->getPhys(li->reg);
1063 }
1064 else {
1065 // Ranges which are assigned a stack slot only are ignored.
1066 continue;
1067 }
1068
Lang Hamesb0e519f2009-05-17 23:50:36 +00001069 if (reg == 0) {
Lang Hames6699fb22009-08-06 23:32:48 +00001070 // Filter out zero regs - they're for intervals that were spilled.
Lang Hamesb0e519f2009-05-17 23:50:36 +00001071 continue;
1072 }
1073
Lang Hames27601ef2008-11-16 12:12:54 +00001074 // Iterate over the ranges of the current interval...
1075 for (LRIterator lrItr = li->begin(), lrEnd = li->end();
1076 lrItr != lrEnd; ++lrItr) {
Misha Brukman2a835f92009-01-08 15:50:22 +00001077
Lang Hames27601ef2008-11-16 12:12:54 +00001078 // Find the set of basic blocks which this range is live into...
1079 if (lis->findLiveInMBBs(lrItr->start, lrItr->end, liveInMBBs)) {
1080 // And add the physreg for this interval to their live-in sets.
1081 for (unsigned i = 0; i < liveInMBBs.size(); ++i) {
1082 if (liveInMBBs[i] != entryMBB) {
1083 if (!liveInMBBs[i]->isLiveIn(reg)) {
1084 liveInMBBs[i]->addLiveIn(reg);
1085 }
1086 }
1087 }
1088 liveInMBBs.clear();
1089 }
1090 }
1091 }
Misha Brukman2a835f92009-01-08 15:50:22 +00001092
Lang Hames27601ef2008-11-16 12:12:54 +00001093}
1094
Lang Hameseb6c8f52010-09-18 09:07:10 +00001095bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
Lang Hames27601ef2008-11-16 12:12:54 +00001096
Evan Chengb1290a62008-10-02 18:29:27 +00001097 mf = &MF;
1098 tm = &mf->getTarget();
1099 tri = tm->getRegisterInfo();
Lang Hames27601ef2008-11-16 12:12:54 +00001100 tii = tm->getInstrInfo();
Lang Hames233a60e2009-11-03 23:52:08 +00001101 mri = &mf->getRegInfo();
Evan Chengb1290a62008-10-02 18:29:27 +00001102
Lang Hames27601ef2008-11-16 12:12:54 +00001103 lis = &getAnalysis<LiveIntervals>();
1104 lss = &getAnalysis<LiveStacks>();
Evan Chengb1290a62008-10-02 18:29:27 +00001105 loopInfo = &getAnalysis<MachineLoopInfo>();
Lang Hames33198392010-09-02 08:27:00 +00001106 rmf = &getAnalysis<RenderMachineFunction>();
Evan Chengb1290a62008-10-02 18:29:27 +00001107
Owen Anderson49c8aa02009-03-13 05:55:11 +00001108 vrm = &getAnalysis<VirtRegMap>();
Evan Chengb1290a62008-10-02 18:29:27 +00001109
Lang Hames54cc2ef2010-07-19 15:22:28 +00001110
Lang Hames030c4bf2010-01-26 04:49:58 +00001111 DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getFunction()->getName() << "\n");
Lang Hames27601ef2008-11-16 12:12:54 +00001112
Evan Chengb1290a62008-10-02 18:29:27 +00001113 // Allocator main loop:
Misha Brukman2a835f92009-01-08 15:50:22 +00001114 //
Evan Chengb1290a62008-10-02 18:29:27 +00001115 // * Map current regalloc problem to a PBQP problem
1116 // * Solve the PBQP problem
1117 // * Map the solution back to a register allocation
1118 // * Spill if necessary
Misha Brukman2a835f92009-01-08 15:50:22 +00001119 //
Evan Chengb1290a62008-10-02 18:29:27 +00001120 // This process is continued till no more spills are generated.
1121
Lang Hames27601ef2008-11-16 12:12:54 +00001122 // Find the vreg intervals in need of allocation.
1123 findVRegIntervalsToAlloc();
Misha Brukman2a835f92009-01-08 15:50:22 +00001124
Lang Hames27601ef2008-11-16 12:12:54 +00001125 // If there are non-empty intervals allocate them using pbqp.
Lang Hameseb6c8f52010-09-18 09:07:10 +00001126 if (!vregsToAlloc.empty()) {
Evan Chengb1290a62008-10-02 18:29:27 +00001127
Lang Hames27601ef2008-11-16 12:12:54 +00001128 bool pbqpAllocComplete = false;
1129 unsigned round = 0;
1130
Lang Hameseb6c8f52010-09-18 09:07:10 +00001131 if (!pbqpBuilder) {
1132 while (!pbqpAllocComplete) {
1133 DEBUG(dbgs() << " PBQP Regalloc round " << round << ":\n");
Lang Hames27601ef2008-11-16 12:12:54 +00001134
Lang Hameseb6c8f52010-09-18 09:07:10 +00001135 PBQP::Graph problem = constructPBQPProblem();
1136 PBQP::Solution solution =
1137 PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(problem);
Lang Hames233fd9c2009-08-18 23:34:50 +00001138
Lang Hameseb6c8f52010-09-18 09:07:10 +00001139 pbqpAllocComplete = mapPBQPToRegAlloc(solution);
Lang Hames27601ef2008-11-16 12:12:54 +00001140
Lang Hameseb6c8f52010-09-18 09:07:10 +00001141 ++round;
1142 }
1143 } else {
1144 while (!pbqpAllocComplete) {
1145 DEBUG(dbgs() << " PBQP Regalloc round " << round << ":\n");
1146
1147 std::auto_ptr<PBQPRAProblem> problem =
Lang Hamese9c93562010-09-21 13:19:36 +00001148 builder->build(mf, lis, loopInfo, vregsToAlloc);
Lang Hameseb6c8f52010-09-18 09:07:10 +00001149 PBQP::Solution solution =
Lang Hamese9c93562010-09-21 13:19:36 +00001150 PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(
1151 problem->getGraph());
Lang Hameseb6c8f52010-09-18 09:07:10 +00001152
1153 pbqpAllocComplete = mapPBQPToRegAlloc2(*problem, solution);
1154
1155 ++round;
1156 }
Lang Hames27601ef2008-11-16 12:12:54 +00001157 }
Evan Chengb1290a62008-10-02 18:29:27 +00001158 }
1159
Lang Hames27601ef2008-11-16 12:12:54 +00001160 // Finalise allocation, allocate empty ranges.
1161 finalizeAlloc();
Evan Chengb1290a62008-10-02 18:29:27 +00001162
Lang Hamesc4bcc772010-07-20 07:41:44 +00001163 rmf->renderMachineFunction("After PBQP register allocation.", vrm);
1164
Lang Hameseb6c8f52010-09-18 09:07:10 +00001165 vregsToAlloc.clear();
1166 emptyIntervalVRegs.clear();
Lang Hames27601ef2008-11-16 12:12:54 +00001167 li2Node.clear();
1168 node2LI.clear();
1169 allowedSets.clear();
Lang Hames030c4bf2010-01-26 04:49:58 +00001170 problemNodes.clear();
Lang Hames27601ef2008-11-16 12:12:54 +00001171
David Greene30931542010-01-05 01:25:43 +00001172 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
Lang Hames27601ef2008-11-16 12:12:54 +00001173
Lang Hames87e3bca2009-05-06 02:36:21 +00001174 // Run rewriter
1175 std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
1176
1177 rewriter->runOnMachineFunction(*mf, *vrm, lis);
Lang Hames27601ef2008-11-16 12:12:54 +00001178
Misha Brukman2a835f92009-01-08 15:50:22 +00001179 return true;
Evan Chengb1290a62008-10-02 18:29:27 +00001180}
1181
Lang Hameseb6c8f52010-09-18 09:07:10 +00001182FunctionPass* createPBQPRegisterAllocator() {
Lang Hamese9c93562010-09-21 13:19:36 +00001183 if (pbqpCoalescing) {
1184 return new RegAllocPBQP(
1185 std::auto_ptr<PBQPBuilder>(new PBQPBuilderWithCoalescing()));
1186 } // else
1187 return new RegAllocPBQP(
1188 std::auto_ptr<PBQPBuilder>(new PBQPBuilder()));
Evan Chengb1290a62008-10-02 18:29:27 +00001189}
1190
Lang Hameseb6c8f52010-09-18 09:07:10 +00001191}
Evan Chengb1290a62008-10-02 18:29:27 +00001192
1193#undef DEBUG_TYPE