blob: 23043a222e22f684c74b5390628062353fe00221 [file] [log] [blame]
Evan Chengb25f4632008-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 Brukmanda467482009-01-08 15:50:22 +00009//
Evan Chengb25f4632008-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 Brukmanda467482009-01-08 15:50:22 +000015// code is inserted and the process repeated.
Evan Chengb25f4632008-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 Brukman572f2642009-01-08 16:40:25 +000019// allocation, see the following papers:
Evan Chengb25f4632008-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 Brukmanda467482009-01-08 15:50:22 +000029//
Evan Chengb25f4632008-10-02 18:29:27 +000030//===----------------------------------------------------------------------===//
31
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/CodeGen/RegAllocPBQP.h"
Rafael Espindolafef3c642011-06-26 21:41:06 +000033#include "RegisterCoalescer.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "Spiller.h"
Lang Hamesb13b6a02011-12-06 01:45:57 +000035#include "llvm/Analysis/AliasAnalysis.h"
Lang Hamesd17e2962009-12-14 06:49:42 +000036#include "llvm/CodeGen/CalcSpillWeights.h"
Evan Chengb25f4632008-10-02 18:29:27 +000037#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper3ca96f92012-04-02 22:44:18 +000038#include "llvm/CodeGen/LiveRangeEdit.h"
Lang Hames49ab8bc2008-11-16 12:12:54 +000039#include "llvm/CodeGen/LiveStackAnalysis.h"
Benjamin Kramere2a1d892013-06-17 19:00:36 +000040#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Lang Hamesb13b6a02011-12-06 01:45:57 +000041#include "llvm/CodeGen/MachineDominators.h"
Misha Brukmanda467482009-01-08 15:50:22 +000042#include "llvm/CodeGen/MachineFunctionPass.h"
Lang Hames7d99d792013-07-01 20:47:47 +000043#include "llvm/CodeGen/MachineLoopInfo.h"
Misha Brukmanda467482009-01-08 15:50:22 +000044#include "llvm/CodeGen/MachineRegisterInfo.h"
45#include "llvm/CodeGen/RegAllocRegistry.h"
Jakob Stoklund Olesen26c9d702012-11-28 19:13:06 +000046#include "llvm/CodeGen/VirtRegMap.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/Module.h"
Evan Chengb25f4632008-10-02 18:29:27 +000048#include "llvm/Support/Debug.h"
Benjamin Kramerd59664f2014-04-29 23:26:49 +000049#include "llvm/Support/FileSystem.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000050#include "llvm/Support/raw_ostream.h"
Misha Brukmanda467482009-01-08 15:50:22 +000051#include "llvm/Target/TargetInstrInfo.h"
52#include "llvm/Target/TargetMachine.h"
Eric Christopherd9134482014-08-04 21:25:23 +000053#include "llvm/Target/TargetSubtargetInfo.h"
Misha Brukmanda467482009-01-08 15:50:22 +000054#include <limits>
Misha Brukmanda467482009-01-08 15:50:22 +000055#include <memory>
Evan Chengb25f4632008-10-02 18:29:27 +000056#include <set>
Lang Hames95e021f2012-03-26 23:07:23 +000057#include <sstream>
Evan Chengb25f4632008-10-02 18:29:27 +000058#include <vector>
Evan Chengb25f4632008-10-02 18:29:27 +000059
Lang Hamesfd1bc422010-09-23 04:28:54 +000060using namespace llvm;
Lang Hamescb1e1012010-09-18 09:07:10 +000061
Chandler Carruth1b9dde02014-04-22 02:02:50 +000062#define DEBUG_TYPE "regalloc"
63
Evan Chengb25f4632008-10-02 18:29:27 +000064static RegisterRegAlloc
Duncan Sands1804b4f2010-02-18 14:10:41 +000065registerPBQPRepAlloc("pbqp", "PBQP register allocator",
Lang Hamesfd1bc422010-09-23 04:28:54 +000066 createDefaultPBQPRegisterAllocator);
Evan Chengb25f4632008-10-02 18:29:27 +000067
Lang Hames11732ad2009-08-19 01:36:14 +000068static cl::opt<bool>
69pbqpCoalescing("pbqp-coalescing",
Lang Hames090c7e82010-01-26 04:49:58 +000070 cl::desc("Attempt coalescing during PBQP register allocation."),
71 cl::init(false), cl::Hidden);
Lang Hames11732ad2009-08-19 01:36:14 +000072
Lang Hames95e021f2012-03-26 23:07:23 +000073#ifndef NDEBUG
74static cl::opt<bool>
75pbqpDumpGraphs("pbqp-dump-graphs",
76 cl::desc("Dump graphs for each function/round in the compilation unit."),
77 cl::init(false), cl::Hidden);
78#endif
79
Lang Hamesfd1bc422010-09-23 04:28:54 +000080namespace {
81
82///
83/// PBQP based allocators solve the register allocation problem by mapping
84/// register allocation problems to Partitioned Boolean Quadratic
85/// Programming problems.
86class RegAllocPBQP : public MachineFunctionPass {
87public:
88
89 static char ID;
90
91 /// Construct a PBQP register allocator.
David Blaikieba80ee32014-07-19 21:19:45 +000092 RegAllocPBQP(std::unique_ptr<PBQPBuilder> b, char *cPassID = nullptr)
93 : MachineFunctionPass(ID), builder(std::move(b)), customPassID(cPassID) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +000094 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
95 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +000096 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +000097 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +000098 }
Lang Hamesfd1bc422010-09-23 04:28:54 +000099
100 /// Return the pass name.
Craig Topper4584cd52014-03-07 09:26:03 +0000101 const char* getPassName() const override {
Lang Hamesfd1bc422010-09-23 04:28:54 +0000102 return "PBQP Register Allocator";
103 }
104
105 /// PBQP analysis usage.
Craig Topper4584cd52014-03-07 09:26:03 +0000106 void getAnalysisUsage(AnalysisUsage &au) const override;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000107
108 /// Perform register allocation
Craig Topper4584cd52014-03-07 09:26:03 +0000109 bool runOnMachineFunction(MachineFunction &MF) override;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000110
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;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000119 typedef std::set<unsigned> RegSet;
120
Ahmed Charles56440fd2014-03-06 05:51:42 +0000121 std::unique_ptr<PBQPBuilder> builder;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000122
Lang Hames934625e2011-06-17 07:09:01 +0000123 char *customPassID;
124
Lang Hamesfd1bc422010-09-23 04:28:54 +0000125 MachineFunction *mf;
126 const TargetMachine *tm;
127 const TargetRegisterInfo *tri;
128 const TargetInstrInfo *tii;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000129 MachineRegisterInfo *mri;
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000130 const MachineBlockFrequencyInfo *mbfi;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000131
Ahmed Charles56440fd2014-03-06 05:51:42 +0000132 std::unique_ptr<Spiller> spiller;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000133 LiveIntervals *lis;
134 LiveStacks *lss;
135 VirtRegMap *vrm;
136
Lang Hamesfd1bc422010-09-23 04:28:54 +0000137 RegSet vregsToAlloc, emptyIntervalVRegs;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000138
139 /// \brief Finds the initial set of vreg intervals to allocate.
140 void findVRegIntervalsToAlloc();
141
Lang Hamesfd1bc422010-09-23 04:28:54 +0000142 /// \brief Given a solved PBQP problem maps this solution back to a register
143 /// assignment.
Lang Hamesfd1bc422010-09-23 04:28:54 +0000144 bool mapPBQPToRegAlloc(const PBQPRAProblem &problem,
145 const PBQP::Solution &solution);
146
147 /// \brief Postprocessing before final spilling. Sets basic block "live in"
148 /// variables.
149 void finalizeAlloc() const;
150
151};
152
Lang Hamescb1e1012010-09-18 09:07:10 +0000153char RegAllocPBQP::ID = 0;
Evan Chengb25f4632008-10-02 18:29:27 +0000154
Lang Hamesfd1bc422010-09-23 04:28:54 +0000155} // End anonymous namespace.
156
Lang Hames18635822014-03-03 18:50:05 +0000157unsigned PBQPRAProblem::getVRegForNode(PBQPRAGraph::NodeId node) const {
Lang Hamescb1e1012010-09-18 09:07:10 +0000158 Node2VReg::const_iterator vregItr = node2VReg.find(node);
159 assert(vregItr != node2VReg.end() && "No vreg for node.");
160 return vregItr->second;
161}
Evan Chengb25f4632008-10-02 18:29:27 +0000162
Lang Hames18635822014-03-03 18:50:05 +0000163PBQPRAGraph::NodeId PBQPRAProblem::getNodeForVReg(unsigned vreg) const {
Lang Hamescb1e1012010-09-18 09:07:10 +0000164 VReg2Node::const_iterator nodeItr = vreg2Node.find(vreg);
165 assert(nodeItr != vreg2Node.end() && "No node for vreg.");
166 return nodeItr->second;
Andrew Trick9363b592012-02-10 04:10:26 +0000167
Lang Hamescb1e1012010-09-18 09:07:10 +0000168}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000169
Lang Hamescb1e1012010-09-18 09:07:10 +0000170const PBQPRAProblem::AllowedSet&
171 PBQPRAProblem::getAllowedSet(unsigned vreg) const {
172 AllowedSetMap::const_iterator allowedSetItr = allowedSets.find(vreg);
173 assert(allowedSetItr != allowedSets.end() && "No pregs for vreg.");
174 const AllowedSet &allowedSet = allowedSetItr->second;
175 return allowedSet;
176}
Evan Chengb25f4632008-10-02 18:29:27 +0000177
Lang Hamescb1e1012010-09-18 09:07:10 +0000178unsigned PBQPRAProblem::getPRegForOption(unsigned vreg, unsigned option) const {
179 assert(isPRegOption(vreg, option) && "Not a preg option.");
180
181 const AllowedSet& allowedSet = getAllowedSet(vreg);
182 assert(option <= allowedSet.size() && "Option outside allowed set.");
183 return allowedSet[option - 1];
184}
185
David Blaikie505e1b82014-09-02 17:42:01 +0000186std::unique_ptr<PBQPRAProblem>
187PBQPBuilder::build(MachineFunction *mf, const LiveIntervals *lis,
188 const MachineBlockFrequencyInfo *mbfi, const RegSet &vregs) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000189
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000190 LiveIntervals *LIS = const_cast<LiveIntervals*>(lis);
Lang Hamescb1e1012010-09-18 09:07:10 +0000191 MachineRegisterInfo *mri = &mf->getRegInfo();
Eric Christopherfc6de422014-08-05 02:39:49 +0000192 const TargetRegisterInfo *tri = mf->getSubtarget().getRegisterInfo();
Lang Hamescb1e1012010-09-18 09:07:10 +0000193
David Blaikie505e1b82014-09-02 17:42:01 +0000194 auto p = llvm::make_unique<PBQPRAProblem>();
Lang Hames18635822014-03-03 18:50:05 +0000195 PBQPRAGraph &g = p->getGraph();
Lang Hamescb1e1012010-09-18 09:07:10 +0000196 RegSet pregs;
197
198 // Collect the set of preg intervals, record that they're used in the MF.
Jakob Stoklund Olesena1f43dc2012-06-20 21:25:05 +0000199 for (unsigned Reg = 1, e = tri->getNumRegs(); Reg != e; ++Reg) {
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000200 if (mri->def_empty(Reg))
Jakob Stoklund Olesena1f43dc2012-06-20 21:25:05 +0000201 continue;
202 pregs.insert(Reg);
203 mri->setPhysRegUsed(Reg);
Lang Hamescb1e1012010-09-18 09:07:10 +0000204 }
Evan Chengb25f4632008-10-02 18:29:27 +0000205
Andrew Trick9363b592012-02-10 04:10:26 +0000206 // Iterate over vregs.
Lang Hamescb1e1012010-09-18 09:07:10 +0000207 for (RegSet::const_iterator vregItr = vregs.begin(), vregEnd = vregs.end();
208 vregItr != vregEnd; ++vregItr) {
209 unsigned vreg = *vregItr;
210 const TargetRegisterClass *trc = mri->getRegClass(vreg);
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000211 LiveInterval *vregLI = &LIS->getInterval(vreg);
212
213 // Record any overlaps with regmask operands.
Lang Hames05fee082012-10-10 06:39:48 +0000214 BitVector regMaskOverlaps;
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000215 LIS->checkRegMaskInterference(*vregLI, regMaskOverlaps);
Evan Chengb25f4632008-10-02 18:29:27 +0000216
Lang Hamescb1e1012010-09-18 09:07:10 +0000217 // Compute an initial allowed set for the current vreg.
218 typedef std::vector<unsigned> VRAllowed;
219 VRAllowed vrAllowed;
Craig Topper840beec2014-04-04 05:16:06 +0000220 ArrayRef<MCPhysReg> rawOrder = trc->getRawAllocationOrder(*mf);
Jakob Stoklund Olesen08322b72011-06-16 20:37:45 +0000221 for (unsigned i = 0; i != rawOrder.size(); ++i) {
222 unsigned preg = rawOrder[i];
Jakob Stoklund Olesenc30a9af2012-10-15 21:57:41 +0000223 if (mri->isReserved(preg))
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000224 continue;
225
226 // vregLI crosses a regmask operand that clobbers preg.
Lang Hames05fee082012-10-10 06:39:48 +0000227 if (!regMaskOverlaps.empty() && !regMaskOverlaps.test(preg))
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000228 continue;
229
230 // vregLI overlaps fixed regunit interference.
Jakob Stoklund Olesenb1b3e4a2012-06-22 16:46:44 +0000231 bool Interference = false;
232 for (MCRegUnitIterator Units(preg, tri); Units.isValid(); ++Units) {
233 if (vregLI->overlaps(LIS->getRegUnit(*Units))) {
234 Interference = true;
235 break;
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000236 }
Lang Hames211e7ce2010-07-17 06:31:41 +0000237 }
Jakob Stoklund Olesenb1b3e4a2012-06-22 16:46:44 +0000238 if (Interference)
239 continue;
Jakob Stoklund Olesenbfa664e2012-06-20 22:32:05 +0000240
241 // preg is usable for this virtual register.
242 vrAllowed.push_back(preg);
Lang Hamescb1e1012010-09-18 09:07:10 +0000243 }
Lang Hames211e7ce2010-07-17 06:31:41 +0000244
Lang Hames18635822014-03-03 18:50:05 +0000245 PBQP::Vector nodeCosts(vrAllowed.size() + 1, 0);
Evan Chengb25f4632008-10-02 18:29:27 +0000246
Lang Hamescb1e1012010-09-18 09:07:10 +0000247 PBQP::PBQPNum spillCost = (vregLI->weight != 0.0) ?
248 vregLI->weight : std::numeric_limits<PBQP::PBQPNum>::min();
Evan Chengb25f4632008-10-02 18:29:27 +0000249
Lang Hames18635822014-03-03 18:50:05 +0000250 addSpillCosts(nodeCosts, spillCost);
251
252 // Construct the node.
253 PBQPRAGraph::NodeId nId = g.addNode(std::move(nodeCosts));
254
255 // Record the mapping and allowed set in the problem.
256 p->recordVReg(vreg, nId, vrAllowed.begin(), vrAllowed.end());
257
Lang Hamescb1e1012010-09-18 09:07:10 +0000258 }
Evan Chengb25f4632008-10-02 18:29:27 +0000259
Lang Hames361de982010-09-18 09:49:08 +0000260 for (RegSet::const_iterator vr1Itr = vregs.begin(), vrEnd = vregs.end();
Lang Hamescb1e1012010-09-18 09:07:10 +0000261 vr1Itr != vrEnd; ++vr1Itr) {
262 unsigned vr1 = *vr1Itr;
263 const LiveInterval &l1 = lis->getInterval(vr1);
264 const PBQPRAProblem::AllowedSet &vr1Allowed = p->getAllowedSet(vr1);
Evan Chengb25f4632008-10-02 18:29:27 +0000265
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000266 for (RegSet::const_iterator vr2Itr = std::next(vr1Itr); vr2Itr != vrEnd;
267 ++vr2Itr) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000268 unsigned vr2 = *vr2Itr;
269 const LiveInterval &l2 = lis->getInterval(vr2);
270 const PBQPRAProblem::AllowedSet &vr2Allowed = p->getAllowedSet(vr2);
Evan Chengb25f4632008-10-02 18:29:27 +0000271
Lang Hamescb1e1012010-09-18 09:07:10 +0000272 assert(!l2.empty() && "Empty interval in vreg set?");
273 if (l1.overlaps(l2)) {
Lang Hames18635822014-03-03 18:50:05 +0000274 PBQP::Matrix edgeCosts(vr1Allowed.size()+1, vr2Allowed.size()+1, 0);
275 addInterferenceCosts(edgeCosts, vr1Allowed, vr2Allowed, tri);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000276
Lang Hames18635822014-03-03 18:50:05 +0000277 g.addEdge(p->getNodeForVReg(vr1), p->getNodeForVReg(vr2),
278 std::move(edgeCosts));
Lang Hamescb1e1012010-09-18 09:07:10 +0000279 }
280 }
281 }
Evan Chengb25f4632008-10-02 18:29:27 +0000282
David Blaikie505e1b82014-09-02 17:42:01 +0000283 return p;
Lang Hamescb1e1012010-09-18 09:07:10 +0000284}
Lang Hames49ab8bc2008-11-16 12:12:54 +0000285
Lang Hamescb1e1012010-09-18 09:07:10 +0000286void PBQPBuilder::addSpillCosts(PBQP::Vector &costVec,
287 PBQP::PBQPNum spillCost) {
288 costVec[0] = spillCost;
289}
Evan Chengb25f4632008-10-02 18:29:27 +0000290
Lang Hames0937fc42010-09-21 13:19:36 +0000291void PBQPBuilder::addInterferenceCosts(
292 PBQP::Matrix &costMat,
293 const PBQPRAProblem::AllowedSet &vr1Allowed,
294 const PBQPRAProblem::AllowedSet &vr2Allowed,
295 const TargetRegisterInfo *tri) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000296 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Matrix height mismatch.");
297 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Matrix width mismatch.");
298
Lang Hamesc702ba62010-11-12 05:47:21 +0000299 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000300 unsigned preg1 = vr1Allowed[i];
301
Lang Hamesc702ba62010-11-12 05:47:21 +0000302 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000303 unsigned preg2 = vr2Allowed[j];
304
305 if (tri->regsOverlap(preg1, preg2)) {
306 costMat[i + 1][j + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
307 }
308 }
309 }
Evan Chengb25f4632008-10-02 18:29:27 +0000310}
311
David Blaikie505e1b82014-09-02 17:42:01 +0000312std::unique_ptr<PBQPRAProblem>
313PBQPBuilderWithCoalescing::build(MachineFunction *mf, const LiveIntervals *lis,
314 const MachineBlockFrequencyInfo *mbfi,
315 const RegSet &vregs) {
Lang Hames0937fc42010-09-21 13:19:36 +0000316
David Blaikie505e1b82014-09-02 17:42:01 +0000317 std::unique_ptr<PBQPRAProblem> p = PBQPBuilder::build(mf, lis, mbfi, vregs);
Lang Hames18635822014-03-03 18:50:05 +0000318 PBQPRAGraph &g = p->getGraph();
Lang Hames0937fc42010-09-21 13:19:36 +0000319
320 const TargetMachine &tm = mf->getTarget();
Eric Christopherd9134482014-08-04 21:25:23 +0000321 CoalescerPair cp(*tm.getSubtargetImpl()->getRegisterInfo());
Lang Hames0937fc42010-09-21 13:19:36 +0000322
323 // Scan the machine function and add a coalescing cost whenever CoalescerPair
324 // gives the Ok.
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000325 for (const auto &mbb : *mf) {
326 for (const auto &mi : mbb) {
327 if (!cp.setRegisters(&mi)) {
Lang Hames0937fc42010-09-21 13:19:36 +0000328 continue; // Not coalescable.
Lang Hamesc702ba62010-11-12 05:47:21 +0000329 }
Lang Hames0937fc42010-09-21 13:19:36 +0000330
Lang Hamesc702ba62010-11-12 05:47:21 +0000331 if (cp.getSrcReg() == cp.getDstReg()) {
Lang Hames0937fc42010-09-21 13:19:36 +0000332 continue; // Already coalesced.
Lang Hamesc702ba62010-11-12 05:47:21 +0000333 }
Lang Hames0937fc42010-09-21 13:19:36 +0000334
Lang Hamesfd1bc422010-09-23 04:28:54 +0000335 unsigned dst = cp.getDstReg(),
336 src = cp.getSrcReg();
Lang Hames0937fc42010-09-21 13:19:36 +0000337
Lang Hamesfd1bc422010-09-23 04:28:54 +0000338 const float copyFactor = 0.5; // Cost of copy relative to load. Current
339 // value plucked randomly out of the air.
Andrew Trick9363b592012-02-10 04:10:26 +0000340
Lang Hamesfd1bc422010-09-23 04:28:54 +0000341 PBQP::PBQPNum cBenefit =
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000342 copyFactor * LiveIntervals::getSpillWeight(false, true, mbfi, &mi);
Lang Hames0937fc42010-09-21 13:19:36 +0000343
Lang Hamesfd1bc422010-09-23 04:28:54 +0000344 if (cp.isPhys()) {
Jakob Stoklund Olesencea596a2012-10-15 22:14:34 +0000345 if (!mf->getRegInfo().isAllocatable(dst)) {
Lang Hamesfd1bc422010-09-23 04:28:54 +0000346 continue;
Lang Hamesc702ba62010-11-12 05:47:21 +0000347 }
Lang Hames0937fc42010-09-21 13:19:36 +0000348
Lang Hamesfd1bc422010-09-23 04:28:54 +0000349 const PBQPRAProblem::AllowedSet &allowed = p->getAllowedSet(src);
Andrew Trick9363b592012-02-10 04:10:26 +0000350 unsigned pregOpt = 0;
Lang Hamesc702ba62010-11-12 05:47:21 +0000351 while (pregOpt < allowed.size() && allowed[pregOpt] != dst) {
Lang Hamesfd1bc422010-09-23 04:28:54 +0000352 ++pregOpt;
Lang Hamesc702ba62010-11-12 05:47:21 +0000353 }
Lang Hamesfd1bc422010-09-23 04:28:54 +0000354 if (pregOpt < allowed.size()) {
355 ++pregOpt; // +1 to account for spill option.
Lang Hames18635822014-03-03 18:50:05 +0000356 PBQPRAGraph::NodeId node = p->getNodeForVReg(src);
Arnaud A. de Grandmaisonefd43632014-08-28 10:15:47 +0000357 DEBUG(llvm::dbgs() << "Reading node costs for node " << node << "\n");
358 DEBUG(llvm::dbgs() << "Source node: " << &g.getNodeCosts(node) << "\n");
Lang Hames18635822014-03-03 18:50:05 +0000359 PBQP::Vector newCosts(g.getNodeCosts(node));
360 addPhysRegCoalesce(newCosts, pregOpt, cBenefit);
361 g.setNodeCosts(node, newCosts);
Lang Hames0937fc42010-09-21 13:19:36 +0000362 }
Lang Hamesfd1bc422010-09-23 04:28:54 +0000363 } else {
364 const PBQPRAProblem::AllowedSet *allowed1 = &p->getAllowedSet(dst);
365 const PBQPRAProblem::AllowedSet *allowed2 = &p->getAllowedSet(src);
Lang Hames18635822014-03-03 18:50:05 +0000366 PBQPRAGraph::NodeId node1 = p->getNodeForVReg(dst);
367 PBQPRAGraph::NodeId node2 = p->getNodeForVReg(src);
368 PBQPRAGraph::EdgeId edge = g.findEdge(node1, node2);
Lang Hamesfb826302013-11-09 03:08:56 +0000369 if (edge == g.invalidEdgeId()) {
Lang Hames18635822014-03-03 18:50:05 +0000370 PBQP::Matrix costs(allowed1->size() + 1, allowed2->size() + 1, 0);
371 addVirtRegCoalesce(costs, *allowed1, *allowed2, cBenefit);
372 g.addEdge(node1, node2, costs);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000373 } else {
Lang Hames18635822014-03-03 18:50:05 +0000374 if (g.getEdgeNode1Id(edge) == node2) {
Lang Hamesfd1bc422010-09-23 04:28:54 +0000375 std::swap(node1, node2);
376 std::swap(allowed1, allowed2);
377 }
Lang Hames18635822014-03-03 18:50:05 +0000378 PBQP::Matrix costs(g.getEdgeCosts(edge));
379 addVirtRegCoalesce(costs, *allowed1, *allowed2, cBenefit);
380 g.setEdgeCosts(edge, costs);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000381 }
Lang Hames0937fc42010-09-21 13:19:36 +0000382 }
383 }
384 }
385
David Blaikie505e1b82014-09-02 17:42:01 +0000386 return p;
Lang Hames0937fc42010-09-21 13:19:36 +0000387}
388
Lang Hames0937fc42010-09-21 13:19:36 +0000389void PBQPBuilderWithCoalescing::addPhysRegCoalesce(PBQP::Vector &costVec,
390 unsigned pregOption,
391 PBQP::PBQPNum benefit) {
392 costVec[pregOption] += -benefit;
393}
394
395void PBQPBuilderWithCoalescing::addVirtRegCoalesce(
396 PBQP::Matrix &costMat,
397 const PBQPRAProblem::AllowedSet &vr1Allowed,
398 const PBQPRAProblem::AllowedSet &vr2Allowed,
399 PBQP::PBQPNum benefit) {
400
401 assert(costMat.getRows() == vr1Allowed.size() + 1 && "Size mismatch.");
402 assert(costMat.getCols() == vr2Allowed.size() + 1 && "Size mismatch.");
403
Lang Hamesc702ba62010-11-12 05:47:21 +0000404 for (unsigned i = 0; i != vr1Allowed.size(); ++i) {
Lang Hames0937fc42010-09-21 13:19:36 +0000405 unsigned preg1 = vr1Allowed[i];
Lang Hamesc702ba62010-11-12 05:47:21 +0000406 for (unsigned j = 0; j != vr2Allowed.size(); ++j) {
Lang Hames0937fc42010-09-21 13:19:36 +0000407 unsigned preg2 = vr2Allowed[j];
408
409 if (preg1 == preg2) {
410 costMat[i + 1][j + 1] += -benefit;
Andrew Trick9363b592012-02-10 04:10:26 +0000411 }
Lang Hames0937fc42010-09-21 13:19:36 +0000412 }
413 }
414}
Evan Chengb25f4632008-10-02 18:29:27 +0000415
Lang Hamescb1e1012010-09-18 09:07:10 +0000416
417void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
Lang Hamesb13b6a02011-12-06 01:45:57 +0000418 au.setPreservesCFG();
419 au.addRequired<AliasAnalysis>();
420 au.addPreserved<AliasAnalysis>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000421 au.addRequired<SlotIndexes>();
422 au.addPreserved<SlotIndexes>();
423 au.addRequired<LiveIntervals>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000424 au.addPreserved<LiveIntervals>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000425 //au.addRequiredID(SplitCriticalEdgesID);
Lang Hames934625e2011-06-17 07:09:01 +0000426 if (customPassID)
427 au.addRequiredID(*customPassID);
Lang Hamescb1e1012010-09-18 09:07:10 +0000428 au.addRequired<LiveStacks>();
429 au.addPreserved<LiveStacks>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000430 au.addRequired<MachineBlockFrequencyInfo>();
431 au.addPreserved<MachineBlockFrequencyInfo>();
Lang Hames7d99d792013-07-01 20:47:47 +0000432 au.addRequired<MachineLoopInfo>();
433 au.addPreserved<MachineLoopInfo>();
Lang Hamesb13b6a02011-12-06 01:45:57 +0000434 au.addRequired<MachineDominatorTree>();
435 au.addPreserved<MachineDominatorTree>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000436 au.addRequired<VirtRegMap>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000437 au.addPreserved<VirtRegMap>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000438 MachineFunctionPass::getAnalysisUsage(au);
439}
440
Lang Hamescb1e1012010-09-18 09:07:10 +0000441void RegAllocPBQP::findVRegIntervalsToAlloc() {
Lang Hames49ab8bc2008-11-16 12:12:54 +0000442
443 // Iterate over all live ranges.
Jakob Stoklund Olesena1f43dc2012-06-20 21:25:05 +0000444 for (unsigned i = 0, e = mri->getNumVirtRegs(); i != e; ++i) {
445 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
446 if (mri->reg_nodbg_empty(Reg))
Lang Hames49ab8bc2008-11-16 12:12:54 +0000447 continue;
Jakob Stoklund Olesena1f43dc2012-06-20 21:25:05 +0000448 LiveInterval *li = &lis->getInterval(Reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000449
450 // If this live interval is non-empty we will use pbqp to allocate it.
451 // Empty intervals we allocate in a simple post-processing stage in
452 // finalizeAlloc.
453 if (!li->empty()) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000454 vregsToAlloc.insert(li->reg);
Lang Hamesc702ba62010-11-12 05:47:21 +0000455 } else {
Lang Hamescb1e1012010-09-18 09:07:10 +0000456 emptyIntervalVRegs.insert(li->reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000457 }
458 }
Evan Chengb25f4632008-10-02 18:29:27 +0000459}
460
Lang Hamesfd1bc422010-09-23 04:28:54 +0000461bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
462 const PBQP::Solution &solution) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000463 // Set to true if we have any spills
464 bool anotherRoundNeeded = false;
465
466 // Clear the existing allocation.
467 vrm->clearAllVirt();
468
Lang Hames18635822014-03-03 18:50:05 +0000469 const PBQPRAGraph &g = problem.getGraph();
Lang Hamescb1e1012010-09-18 09:07:10 +0000470 // Iterate over the nodes mapping the PBQP solution to a register
471 // assignment.
Lang Hames18635822014-03-03 18:50:05 +0000472 for (auto NId : g.nodeIds()) {
473 unsigned vreg = problem.getVRegForNode(NId);
474 unsigned alloc = solution.getSelection(NId);
Lang Hamescb1e1012010-09-18 09:07:10 +0000475
476 if (problem.isPRegOption(vreg, alloc)) {
Andrew Trick9363b592012-02-10 04:10:26 +0000477 unsigned preg = problem.getPRegForOption(vreg, alloc);
Patrik Hägglund94537c22012-05-23 12:12:58 +0000478 DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> "
479 << tri->getName(preg) << "\n");
Lang Hamescb1e1012010-09-18 09:07:10 +0000480 assert(preg != 0 && "Invalid preg selected.");
Andrew Trick9363b592012-02-10 04:10:26 +0000481 vrm->assignVirt2Phys(vreg, preg);
Lang Hamescb1e1012010-09-18 09:07:10 +0000482 } else if (problem.isSpillOption(vreg, alloc)) {
483 vregsToAlloc.erase(vreg);
Mark Laceyf9ea8852013-08-14 23:50:04 +0000484 SmallVector<unsigned, 8> newSpills;
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +0000485 LiveRangeEdit LRE(&lis->getInterval(vreg), newSpills, *mf, *lis, vrm);
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000486 spiller->spill(LRE);
Lang Hamescb1e1012010-09-18 09:07:10 +0000487
Patrik Hägglund94537c22012-05-23 12:12:58 +0000488 DEBUG(dbgs() << "VREG " << PrintReg(vreg, tri) << " -> SPILLED (Cost: "
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000489 << LRE.getParent().weight << ", New vregs: ");
Lang Hamescb1e1012010-09-18 09:07:10 +0000490
491 // Copy any newly inserted live intervals into the list of regs to
492 // allocate.
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000493 for (LiveRangeEdit::iterator itr = LRE.begin(), end = LRE.end();
Lang Hamescb1e1012010-09-18 09:07:10 +0000494 itr != end; ++itr) {
Mark Laceyf9ea8852013-08-14 23:50:04 +0000495 LiveInterval &li = lis->getInterval(*itr);
496 assert(!li.empty() && "Empty spill range.");
497 DEBUG(dbgs() << PrintReg(li.reg, tri) << " ");
498 vregsToAlloc.insert(li.reg);
Lang Hamescb1e1012010-09-18 09:07:10 +0000499 }
500
501 DEBUG(dbgs() << ")\n");
502
503 // We need another round if spill intervals were added.
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000504 anotherRoundNeeded |= !LRE.empty();
Lang Hamescb1e1012010-09-18 09:07:10 +0000505 } else {
Craig Topperee4dab52012-02-05 08:31:47 +0000506 llvm_unreachable("Unknown allocation option.");
Lang Hamescb1e1012010-09-18 09:07:10 +0000507 }
508 }
509
510 return !anotherRoundNeeded;
511}
512
513
514void RegAllocPBQP::finalizeAlloc() const {
Lang Hames49ab8bc2008-11-16 12:12:54 +0000515 // First allocate registers for the empty intervals.
Lang Hamescb1e1012010-09-18 09:07:10 +0000516 for (RegSet::const_iterator
517 itr = emptyIntervalVRegs.begin(), end = emptyIntervalVRegs.end();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000518 itr != end; ++itr) {
Lang Hamescb1e1012010-09-18 09:07:10 +0000519 LiveInterval *li = &lis->getInterval(*itr);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000520
Jakob Stoklund Olesen1dd82dd2012-12-04 00:30:22 +0000521 unsigned physReg = mri->getSimpleHint(li->reg);
Lang Hames88fae6f2009-08-06 23:32:48 +0000522
Lang Hames49ab8bc2008-11-16 12:12:54 +0000523 if (physReg == 0) {
524 const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
Jakob Stoklund Olesen08322b72011-06-16 20:37:45 +0000525 physReg = liRC->getRawAllocationOrder(*mf).front();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000526 }
Misha Brukmanda467482009-01-08 15:50:22 +0000527
528 vrm->assignVirt2Phys(li->reg, physReg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000529 }
Lang Hames49ab8bc2008-11-16 12:12:54 +0000530}
531
Lang Hamescb1e1012010-09-18 09:07:10 +0000532bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
Lang Hames49ab8bc2008-11-16 12:12:54 +0000533
Evan Chengb25f4632008-10-02 18:29:27 +0000534 mf = &MF;
535 tm = &mf->getTarget();
Eric Christopherd9134482014-08-04 21:25:23 +0000536 tri = tm->getSubtargetImpl()->getRegisterInfo();
537 tii = tm->getSubtargetImpl()->getInstrInfo();
Andrew Trick9363b592012-02-10 04:10:26 +0000538 mri = &mf->getRegInfo();
Evan Chengb25f4632008-10-02 18:29:27 +0000539
Lang Hames49ab8bc2008-11-16 12:12:54 +0000540 lis = &getAnalysis<LiveIntervals>();
541 lss = &getAnalysis<LiveStacks>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000542 mbfi = &getAnalysis<MachineBlockFrequencyInfo>();
Evan Chengb25f4632008-10-02 18:29:27 +0000543
Arnaud A. de Grandmaisonea3ac162013-11-11 19:04:45 +0000544 calculateSpillWeightsAndHints(*lis, MF, getAnalysis<MachineLoopInfo>(),
545 *mbfi);
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +0000546
Owen Andersond37ddf52009-03-13 05:55:11 +0000547 vrm = &getAnalysis<VirtRegMap>();
Jakob Stoklund Olesen11bb63a2011-11-12 23:17:52 +0000548 spiller.reset(createInlineSpiller(*this, MF, *vrm));
Evan Chengb25f4632008-10-02 18:29:27 +0000549
Chad Rosiered119d52012-11-28 00:21:29 +0000550 mri->freezeReservedRegs(MF);
551
Craig Toppera538d832012-08-22 06:07:19 +0000552 DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getName() << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000553
Evan Chengb25f4632008-10-02 18:29:27 +0000554 // Allocator main loop:
Misha Brukmanda467482009-01-08 15:50:22 +0000555 //
Evan Chengb25f4632008-10-02 18:29:27 +0000556 // * Map current regalloc problem to a PBQP problem
557 // * Solve the PBQP problem
558 // * Map the solution back to a register allocation
559 // * Spill if necessary
Misha Brukmanda467482009-01-08 15:50:22 +0000560 //
Evan Chengb25f4632008-10-02 18:29:27 +0000561 // This process is continued till no more spills are generated.
562
Lang Hames49ab8bc2008-11-16 12:12:54 +0000563 // Find the vreg intervals in need of allocation.
564 findVRegIntervalsToAlloc();
Misha Brukmanda467482009-01-08 15:50:22 +0000565
Craig Toppera538d832012-08-22 06:07:19 +0000566#ifndef NDEBUG
Lang Hames95e021f2012-03-26 23:07:23 +0000567 const Function* func = mf->getFunction();
568 std::string fqn =
569 func->getParent()->getModuleIdentifier() + "." +
570 func->getName().str();
Craig Toppera538d832012-08-22 06:07:19 +0000571#endif
Lang Hames95e021f2012-03-26 23:07:23 +0000572
Lang Hames49ab8bc2008-11-16 12:12:54 +0000573 // If there are non-empty intervals allocate them using pbqp.
Lang Hamescb1e1012010-09-18 09:07:10 +0000574 if (!vregsToAlloc.empty()) {
Evan Chengb25f4632008-10-02 18:29:27 +0000575
Lang Hames49ab8bc2008-11-16 12:12:54 +0000576 bool pbqpAllocComplete = false;
577 unsigned round = 0;
578
Lang Hames4108e7e2010-10-04 12:13:07 +0000579 while (!pbqpAllocComplete) {
580 DEBUG(dbgs() << " PBQP Regalloc round " << round << ":\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000581
David Blaikie505e1b82014-09-02 17:42:01 +0000582 std::unique_ptr<PBQPRAProblem> problem =
583 builder->build(mf, lis, mbfi, vregsToAlloc);
Lang Hames95e021f2012-03-26 23:07:23 +0000584
585#ifndef NDEBUG
586 if (pbqpDumpGraphs) {
587 std::ostringstream rs;
588 rs << round;
589 std::string graphFileName(fqn + "." + rs.str() + ".pbqpgraph");
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000590 std::error_code EC;
591 raw_fd_ostream os(graphFileName, EC, sys::fs::F_Text);
Lang Hames95e021f2012-03-26 23:07:23 +0000592 DEBUG(dbgs() << "Dumping graph for round " << round << " to \""
593 << graphFileName << "\"\n");
594 problem->getGraph().dump(os);
595 }
596#endif
597
Lang Hames4108e7e2010-10-04 12:13:07 +0000598 PBQP::Solution solution =
Lang Hames18635822014-03-03 18:50:05 +0000599 PBQP::RegAlloc::solve(problem->getGraph());
Lang Hames305be0e2009-08-18 23:34:50 +0000600
Lang Hames4108e7e2010-10-04 12:13:07 +0000601 pbqpAllocComplete = mapPBQPToRegAlloc(*problem, solution);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000602
Lang Hames4108e7e2010-10-04 12:13:07 +0000603 ++round;
Lang Hames49ab8bc2008-11-16 12:12:54 +0000604 }
Evan Chengb25f4632008-10-02 18:29:27 +0000605 }
606
Lang Hames49ab8bc2008-11-16 12:12:54 +0000607 // Finalise allocation, allocate empty ranges.
608 finalizeAlloc();
Lang Hamescb1e1012010-09-18 09:07:10 +0000609 vregsToAlloc.clear();
610 emptyIntervalVRegs.clear();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000611
David Greene7e256f32010-01-05 01:25:43 +0000612 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000613
Misha Brukmanda467482009-01-08 15:50:22 +0000614 return true;
Evan Chengb25f4632008-10-02 18:29:27 +0000615}
616
Ahmed Charles56440fd2014-03-06 05:51:42 +0000617FunctionPass *
David Blaikieba80ee32014-07-19 21:19:45 +0000618llvm::createPBQPRegisterAllocator(std::unique_ptr<PBQPBuilder> builder,
Ahmed Charles56440fd2014-03-06 05:51:42 +0000619 char *customPassID) {
David Blaikieba80ee32014-07-19 21:19:45 +0000620 return new RegAllocPBQP(std::move(builder), customPassID);
Evan Chengb25f4632008-10-02 18:29:27 +0000621}
622
Lang Hamesfd1bc422010-09-23 04:28:54 +0000623FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000624 std::unique_ptr<PBQPBuilder> Builder;
Andy Gibbsb23ea722013-04-15 12:06:32 +0000625 if (pbqpCoalescing)
David Blaikieba80ee32014-07-19 21:19:45 +0000626 Builder = llvm::make_unique<PBQPBuilderWithCoalescing>();
Andy Gibbsb23ea722013-04-15 12:06:32 +0000627 else
David Blaikieba80ee32014-07-19 21:19:45 +0000628 Builder = llvm::make_unique<PBQPBuilder>();
629 return createPBQPRegisterAllocator(std::move(Builder));
Lang Hamescb1e1012010-09-18 09:07:10 +0000630}
Evan Chengb25f4632008-10-02 18:29:27 +0000631
632#undef DEBUG_TYPE