blob: d1221ec59bd42c46d2a05bc3d176cf66ec85e49b [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"
Matthias Braunc07cbc82015-12-04 01:31:59 +000050#include "llvm/Support/Printable.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000051#include "llvm/Support/raw_ostream.h"
Misha Brukmanda467482009-01-08 15:50:22 +000052#include "llvm/Target/TargetInstrInfo.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>
Lang Hamesad0962a2014-10-18 17:26:07 +000056#include <queue>
Evan Chengb25f4632008-10-02 18:29:27 +000057#include <set>
Lang Hames95e021f2012-03-26 23:07:23 +000058#include <sstream>
Evan Chengb25f4632008-10-02 18:29:27 +000059#include <vector>
Evan Chengb25f4632008-10-02 18:29:27 +000060
Lang Hamesfd1bc422010-09-23 04:28:54 +000061using namespace llvm;
Lang Hamescb1e1012010-09-18 09:07:10 +000062
Chandler Carruth1b9dde02014-04-22 02:02:50 +000063#define DEBUG_TYPE "regalloc"
64
Evan Chengb25f4632008-10-02 18:29:27 +000065static RegisterRegAlloc
Lang Hames8f31f442014-10-09 18:20:51 +000066RegisterPBQPRepAlloc("pbqp", "PBQP register allocator",
Lang Hamesfd1bc422010-09-23 04:28:54 +000067 createDefaultPBQPRegisterAllocator);
Evan Chengb25f4632008-10-02 18:29:27 +000068
Lang Hames11732ad2009-08-19 01:36:14 +000069static cl::opt<bool>
Lang Hames8f31f442014-10-09 18:20:51 +000070PBQPCoalescing("pbqp-coalescing",
Lang Hames090c7e82010-01-26 04:49:58 +000071 cl::desc("Attempt coalescing during PBQP register allocation."),
72 cl::init(false), cl::Hidden);
Lang Hames11732ad2009-08-19 01:36:14 +000073
Lang Hames95e021f2012-03-26 23:07:23 +000074#ifndef NDEBUG
75static cl::opt<bool>
Lang Hames8f31f442014-10-09 18:20:51 +000076PBQPDumpGraphs("pbqp-dump-graphs",
Lang Hames95e021f2012-03-26 23:07:23 +000077 cl::desc("Dump graphs for each function/round in the compilation unit."),
78 cl::init(false), cl::Hidden);
79#endif
80
Lang Hamesfd1bc422010-09-23 04:28:54 +000081namespace {
82
83///
84/// PBQP based allocators solve the register allocation problem by mapping
85/// register allocation problems to Partitioned Boolean Quadratic
86/// Programming problems.
87class RegAllocPBQP : public MachineFunctionPass {
88public:
89
90 static char ID;
91
92 /// Construct a PBQP register allocator.
Lang Hames8f31f442014-10-09 18:20:51 +000093 RegAllocPBQP(char *cPassID = nullptr)
94 : MachineFunctionPass(ID), customPassID(cPassID) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +000095 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
96 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +000097 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +000098 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +000099 }
Lang Hamesfd1bc422010-09-23 04:28:54 +0000100
101 /// Return the pass name.
Craig Topper4584cd52014-03-07 09:26:03 +0000102 const char* getPassName() const override {
Lang Hamesfd1bc422010-09-23 04:28:54 +0000103 return "PBQP Register Allocator";
104 }
105
106 /// PBQP analysis usage.
Craig Topper4584cd52014-03-07 09:26:03 +0000107 void getAnalysisUsage(AnalysisUsage &au) const override;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000108
109 /// Perform register allocation
Craig Topper4584cd52014-03-07 09:26:03 +0000110 bool runOnMachineFunction(MachineFunction &MF) override;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000111
112private:
113
114 typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
115 typedef std::vector<const LiveInterval*> Node2LIMap;
116 typedef std::vector<unsigned> AllowedSet;
117 typedef std::vector<AllowedSet> AllowedSetMap;
118 typedef std::pair<unsigned, unsigned> RegPair;
119 typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000120 typedef std::set<unsigned> RegSet;
121
Lang Hames934625e2011-06-17 07:09:01 +0000122 char *customPassID;
123
Lang Hames8f31f442014-10-09 18:20:51 +0000124 RegSet VRegsToAlloc, EmptyIntervalVRegs;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000125
Wei Mi9a16d652016-04-13 03:08:27 +0000126 /// Inst which is a def of an original reg and whose defs are already all
127 /// dead after remat is saved in DeadRemats. The deletion of such inst is
128 /// postponed till all the allocations are done, so its remat expr is
129 /// always available for the remat of all the siblings of the original reg.
130 SmallPtrSet<MachineInstr *, 32> DeadRemats;
131
Lang Hamesfd1bc422010-09-23 04:28:54 +0000132 /// \brief Finds the initial set of vreg intervals to allocate.
Lang Hames8f31f442014-10-09 18:20:51 +0000133 void findVRegIntervalsToAlloc(const MachineFunction &MF, LiveIntervals &LIS);
134
135 /// \brief Constructs an initial graph.
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000136 void initializeGraph(PBQPRAGraph &G, VirtRegMap &VRM, Spiller &VRegSpiller);
137
138 /// \brief Spill the given VReg.
139 void spillVReg(unsigned VReg, SmallVectorImpl<unsigned> &NewIntervals,
140 MachineFunction &MF, LiveIntervals &LIS, VirtRegMap &VRM,
141 Spiller &VRegSpiller);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000142
Lang Hamesfd1bc422010-09-23 04:28:54 +0000143 /// \brief Given a solved PBQP problem maps this solution back to a register
144 /// assignment.
Lang Hames8f31f442014-10-09 18:20:51 +0000145 bool mapPBQPToRegAlloc(const PBQPRAGraph &G,
146 const PBQP::Solution &Solution,
147 VirtRegMap &VRM,
148 Spiller &VRegSpiller);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000149
150 /// \brief Postprocessing before final spilling. Sets basic block "live in"
151 /// variables.
Lang Hames8f31f442014-10-09 18:20:51 +0000152 void finalizeAlloc(MachineFunction &MF, LiveIntervals &LIS,
153 VirtRegMap &VRM) const;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000154
Wei Mi9a16d652016-04-13 03:08:27 +0000155 void postOptimization(Spiller &VRegSpiller, LiveIntervals &LIS);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000156};
157
Lang Hamescb1e1012010-09-18 09:07:10 +0000158char RegAllocPBQP::ID = 0;
Evan Chengb25f4632008-10-02 18:29:27 +0000159
Lang Hames8f31f442014-10-09 18:20:51 +0000160/// @brief Set spill costs for each node in the PBQP reg-alloc graph.
161class SpillCosts : public PBQPRAConstraint {
162public:
163 void apply(PBQPRAGraph &G) override {
164 LiveIntervals &LIS = G.getMetadata().LIS;
165
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000166 // A minimum spill costs, so that register constraints can can be set
167 // without normalization in the [0.0:MinSpillCost( interval.
168 const PBQP::PBQPNum MinSpillCost = 10.0;
169
Lang Hames8f31f442014-10-09 18:20:51 +0000170 for (auto NId : G.nodeIds()) {
171 PBQP::PBQPNum SpillCost =
172 LIS.getInterval(G.getNodeMetadata(NId).getVReg()).weight;
173 if (SpillCost == 0.0)
174 SpillCost = std::numeric_limits<PBQP::PBQPNum>::min();
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000175 else
176 SpillCost += MinSpillCost;
Lang Hames8f31f442014-10-09 18:20:51 +0000177 PBQPRAGraph::RawVector NodeCosts(G.getNodeCosts(NId));
178 NodeCosts[PBQP::RegAlloc::getSpillOptionIdx()] = SpillCost;
179 G.setNodeCosts(NId, std::move(NodeCosts));
180 }
181 }
182};
183
184/// @brief Add interference edges between overlapping vregs.
185class Interference : public PBQPRAConstraint {
Lang Hamesad0962a2014-10-18 17:26:07 +0000186private:
187
Lang Hames5fe30ca2014-10-27 17:44:25 +0000188 typedef const PBQP::RegAlloc::AllowedRegVector* AllowedRegVecPtr;
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000189 typedef std::pair<AllowedRegVecPtr, AllowedRegVecPtr> IKey;
190 typedef DenseMap<IKey, PBQPRAGraph::MatrixPtr> IMatrixCache;
191 typedef DenseSet<IKey> DisjointAllowedRegsCache;
Arnaud A. de Grandmaisond8ed0d32015-03-05 09:12:59 +0000192 typedef std::pair<PBQP::GraphBase::NodeId, PBQP::GraphBase::NodeId> IEdgeKey;
193 typedef DenseSet<IEdgeKey> IEdgeCache;
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000194
195 bool haveDisjointAllowedRegs(const PBQPRAGraph &G, PBQPRAGraph::NodeId NId,
196 PBQPRAGraph::NodeId MId,
197 const DisjointAllowedRegsCache &D) const {
198 const auto *NRegs = &G.getNodeMetadata(NId).getAllowedRegs();
199 const auto *MRegs = &G.getNodeMetadata(MId).getAllowedRegs();
200
201 if (NRegs == MRegs)
202 return false;
203
204 if (NRegs < MRegs)
205 return D.count(IKey(NRegs, MRegs)) > 0;
Arnaud A. de Grandmaisona57ca812015-03-01 21:22:50 +0000206
207 return D.count(IKey(MRegs, NRegs)) > 0;
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000208 }
209
210 void setDisjointAllowedRegs(const PBQPRAGraph &G, PBQPRAGraph::NodeId NId,
211 PBQPRAGraph::NodeId MId,
212 DisjointAllowedRegsCache &D) {
213 const auto *NRegs = &G.getNodeMetadata(NId).getAllowedRegs();
214 const auto *MRegs = &G.getNodeMetadata(MId).getAllowedRegs();
215
216 assert(NRegs != MRegs && "AllowedRegs can not be disjoint with itself");
217
218 if (NRegs < MRegs)
219 D.insert(IKey(NRegs, MRegs));
220 else
221 D.insert(IKey(MRegs, NRegs));
222 }
Lang Hames5fe30ca2014-10-27 17:44:25 +0000223
Lang Hamesad0962a2014-10-18 17:26:07 +0000224 // Holds (Interval, CurrentSegmentID, and NodeId). The first two are required
225 // for the fast interference graph construction algorithm. The last is there
226 // to save us from looking up node ids via the VRegToNode map in the graph
227 // metadata.
228 typedef std::tuple<LiveInterval*, size_t, PBQP::GraphBase::NodeId>
229 IntervalInfo;
230
231 static SlotIndex getStartPoint(const IntervalInfo &I) {
232 return std::get<0>(I)->segments[std::get<1>(I)].start;
233 }
234
235 static SlotIndex getEndPoint(const IntervalInfo &I) {
236 return std::get<0>(I)->segments[std::get<1>(I)].end;
237 }
238
239 static PBQP::GraphBase::NodeId getNodeId(const IntervalInfo &I) {
240 return std::get<2>(I);
241 }
242
243 static bool lowestStartPoint(const IntervalInfo &I1,
244 const IntervalInfo &I2) {
245 // Condition reversed because priority queue has the *highest* element at
246 // the front, rather than the lowest.
247 return getStartPoint(I1) > getStartPoint(I2);
248 }
249
250 static bool lowestEndPoint(const IntervalInfo &I1,
251 const IntervalInfo &I2) {
252 SlotIndex E1 = getEndPoint(I1);
253 SlotIndex E2 = getEndPoint(I2);
254
255 if (E1 < E2)
256 return true;
257
258 if (E1 > E2)
259 return false;
260
261 // If two intervals end at the same point, we need a way to break the tie or
262 // the set will assume they're actually equal and refuse to insert a
263 // "duplicate". Just compare the vregs - fast and guaranteed unique.
264 return std::get<0>(I1)->reg < std::get<0>(I2)->reg;
265 }
266
267 static bool isAtLastSegment(const IntervalInfo &I) {
268 return std::get<1>(I) == std::get<0>(I)->size() - 1;
269 }
270
271 static IntervalInfo nextSegment(const IntervalInfo &I) {
272 return std::make_tuple(std::get<0>(I), std::get<1>(I) + 1, std::get<2>(I));
273 }
274
Lang Hames8f31f442014-10-09 18:20:51 +0000275public:
276
277 void apply(PBQPRAGraph &G) override {
Lang Hamesad0962a2014-10-18 17:26:07 +0000278 // The following is loosely based on the linear scan algorithm introduced in
279 // "Linear Scan Register Allocation" by Poletto and Sarkar. This version
280 // isn't linear, because the size of the active set isn't bound by the
281 // number of registers, but rather the size of the largest clique in the
282 // graph. Still, we expect this to be better than N^2.
Lang Hames8f31f442014-10-09 18:20:51 +0000283 LiveIntervals &LIS = G.getMetadata().LIS;
Lang Hames5fe30ca2014-10-27 17:44:25 +0000284
285 // Interferenc matrices are incredibly regular - they're only a function of
286 // the allowed sets, so we cache them to avoid the overhead of constructing
287 // and uniquing them.
288 IMatrixCache C;
Lang Hames8f31f442014-10-09 18:20:51 +0000289
Arnaud A. de Grandmaisond8ed0d32015-03-05 09:12:59 +0000290 // Finding an edge is expensive in the worst case (O(max_clique(G))). So
291 // cache locally edges we have already seen.
292 IEdgeCache EC;
293
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000294 // Cache known disjoint allowed registers pairs
295 DisjointAllowedRegsCache D;
296
Lang Hamesad0962a2014-10-18 17:26:07 +0000297 typedef std::set<IntervalInfo, decltype(&lowestEndPoint)> IntervalSet;
298 typedef std::priority_queue<IntervalInfo, std::vector<IntervalInfo>,
299 decltype(&lowestStartPoint)> IntervalQueue;
300 IntervalSet Active(lowestEndPoint);
301 IntervalQueue Inactive(lowestStartPoint);
Lang Hames8f31f442014-10-09 18:20:51 +0000302
Lang Hamesad0962a2014-10-18 17:26:07 +0000303 // Start by building the inactive set.
304 for (auto NId : G.nodeIds()) {
305 unsigned VReg = G.getNodeMetadata(NId).getVReg();
306 LiveInterval &LI = LIS.getInterval(VReg);
307 assert(!LI.empty() && "PBQP graph contains node for empty interval");
308 Inactive.push(std::make_tuple(&LI, 0, NId));
309 }
Lang Hames8f31f442014-10-09 18:20:51 +0000310
Lang Hamesad0962a2014-10-18 17:26:07 +0000311 while (!Inactive.empty()) {
312 // Tentatively grab the "next" interval - this choice may be overriden
313 // below.
314 IntervalInfo Cur = Inactive.top();
315
316 // Retire any active intervals that end before Cur starts.
317 IntervalSet::iterator RetireItr = Active.begin();
318 while (RetireItr != Active.end() &&
319 (getEndPoint(*RetireItr) <= getStartPoint(Cur))) {
320 // If this interval has subsequent segments, add the next one to the
321 // inactive list.
322 if (!isAtLastSegment(*RetireItr))
323 Inactive.push(nextSegment(*RetireItr));
324
325 ++RetireItr;
Lang Hames8f31f442014-10-09 18:20:51 +0000326 }
Lang Hamesad0962a2014-10-18 17:26:07 +0000327 Active.erase(Active.begin(), RetireItr);
328
329 // One of the newly retired segments may actually start before the
330 // Cur segment, so re-grab the front of the inactive list.
331 Cur = Inactive.top();
332 Inactive.pop();
333
334 // At this point we know that Cur overlaps all active intervals. Add the
335 // interference edges.
336 PBQP::GraphBase::NodeId NId = getNodeId(Cur);
337 for (const auto &A : Active) {
338 PBQP::GraphBase::NodeId MId = getNodeId(A);
339
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000340 // Do not add an edge when the nodes' allowed registers do not
341 // intersect: there is obviously no interference.
342 if (haveDisjointAllowedRegs(G, NId, MId, D))
343 continue;
344
Lang Hamesad0962a2014-10-18 17:26:07 +0000345 // Check that we haven't already added this edge
Arnaud A. de Grandmaisond8ed0d32015-03-05 09:12:59 +0000346 IEdgeKey EK(std::min(NId, MId), std::max(NId, MId));
347 if (EC.count(EK))
Lang Hamesad0962a2014-10-18 17:26:07 +0000348 continue;
349
350 // This is a new edge - add it to the graph.
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000351 if (!createInterferenceEdge(G, NId, MId, C))
352 setDisjointAllowedRegs(G, NId, MId, D);
Arnaud A. de Grandmaisond8ed0d32015-03-05 09:12:59 +0000353 else
354 EC.insert(EK);
Lang Hamesad0962a2014-10-18 17:26:07 +0000355 }
356
357 // Finally, add Cur to the Active set.
358 Active.insert(Cur);
Lang Hames8f31f442014-10-09 18:20:51 +0000359 }
360 }
361
362private:
363
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000364 // Create an Interference edge and add it to the graph, unless it is
365 // a null matrix, meaning the nodes' allowed registers do not have any
366 // interference. This case occurs frequently between integer and floating
367 // point registers for example.
368 // return true iff both nodes interferes.
369 bool createInterferenceEdge(PBQPRAGraph &G,
370 PBQPRAGraph::NodeId NId, PBQPRAGraph::NodeId MId,
371 IMatrixCache &C) {
Lang Hames5fe30ca2014-10-27 17:44:25 +0000372
373 const TargetRegisterInfo &TRI =
Eric Christopher7592b0c2015-01-27 08:27:06 +0000374 *G.getMetadata().MF.getSubtarget().getRegisterInfo();
Lang Hames5fe30ca2014-10-27 17:44:25 +0000375 const auto &NRegs = G.getNodeMetadata(NId).getAllowedRegs();
376 const auto &MRegs = G.getNodeMetadata(MId).getAllowedRegs();
377
378 // Try looking the edge costs up in the IMatrixCache first.
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000379 IKey K(&NRegs, &MRegs);
Lang Hames5fe30ca2014-10-27 17:44:25 +0000380 IMatrixCache::iterator I = C.find(K);
381 if (I != C.end()) {
382 G.addEdgeBypassingCostAllocator(NId, MId, I->second);
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000383 return true;
Lang Hames5fe30ca2014-10-27 17:44:25 +0000384 }
385
386 PBQPRAGraph::RawMatrix M(NRegs.size() + 1, MRegs.size() + 1, 0);
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000387 bool NodesInterfere = false;
Lang Hames5fe30ca2014-10-27 17:44:25 +0000388 for (unsigned I = 0; I != NRegs.size(); ++I) {
389 unsigned PRegN = NRegs[I];
390 for (unsigned J = 0; J != MRegs.size(); ++J) {
391 unsigned PRegM = MRegs[J];
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000392 if (TRI.regsOverlap(PRegN, PRegM)) {
Lang Hames8f31f442014-10-09 18:20:51 +0000393 M[I + 1][J + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000394 NodesInterfere = true;
395 }
Lang Hames8f31f442014-10-09 18:20:51 +0000396 }
397 }
398
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000399 if (!NodesInterfere)
400 return false;
401
Lang Hames5fe30ca2014-10-27 17:44:25 +0000402 PBQPRAGraph::EdgeId EId = G.addEdge(NId, MId, std::move(M));
403 C[K] = G.getEdgeCostsPtr(EId);
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000404
405 return true;
Lang Hames8f31f442014-10-09 18:20:51 +0000406 }
407};
408
409
410class Coalescing : public PBQPRAConstraint {
411public:
412 void apply(PBQPRAGraph &G) override {
413 MachineFunction &MF = G.getMetadata().MF;
414 MachineBlockFrequencyInfo &MBFI = G.getMetadata().MBFI;
Eric Christopher7592b0c2015-01-27 08:27:06 +0000415 CoalescerPair CP(*MF.getSubtarget().getRegisterInfo());
Lang Hames8f31f442014-10-09 18:20:51 +0000416
417 // Scan the machine function and add a coalescing cost whenever CoalescerPair
418 // gives the Ok.
419 for (const auto &MBB : MF) {
420 for (const auto &MI : MBB) {
421
422 // Skip not-coalescable or already coalesced copies.
423 if (!CP.setRegisters(&MI) || CP.getSrcReg() == CP.getDstReg())
424 continue;
425
426 unsigned DstReg = CP.getDstReg();
427 unsigned SrcReg = CP.getSrcReg();
428
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000429 const float Scale = 1.0f / MBFI.getEntryFreq();
430 PBQP::PBQPNum CBenefit = MBFI.getBlockFreq(&MBB).getFrequency() * Scale;
Lang Hames8f31f442014-10-09 18:20:51 +0000431
432 if (CP.isPhys()) {
433 if (!MF.getRegInfo().isAllocatable(DstReg))
434 continue;
435
436 PBQPRAGraph::NodeId NId = G.getMetadata().getNodeIdForVReg(SrcReg);
437
Lang Hames5fe30ca2014-10-27 17:44:25 +0000438 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed =
439 G.getNodeMetadata(NId).getAllowedRegs();
Lang Hames8f31f442014-10-09 18:20:51 +0000440
441 unsigned PRegOpt = 0;
442 while (PRegOpt < Allowed.size() && Allowed[PRegOpt] != DstReg)
443 ++PRegOpt;
444
445 if (PRegOpt < Allowed.size()) {
446 PBQPRAGraph::RawVector NewCosts(G.getNodeCosts(NId));
Arnaud A. de Grandmaisond3648d02014-10-21 16:24:15 +0000447 NewCosts[PRegOpt + 1] -= CBenefit;
Lang Hames8f31f442014-10-09 18:20:51 +0000448 G.setNodeCosts(NId, std::move(NewCosts));
449 }
450 } else {
451 PBQPRAGraph::NodeId N1Id = G.getMetadata().getNodeIdForVReg(DstReg);
452 PBQPRAGraph::NodeId N2Id = G.getMetadata().getNodeIdForVReg(SrcReg);
Lang Hames5fe30ca2014-10-27 17:44:25 +0000453 const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed1 =
454 &G.getNodeMetadata(N1Id).getAllowedRegs();
455 const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed2 =
456 &G.getNodeMetadata(N2Id).getAllowedRegs();
Lang Hames8f31f442014-10-09 18:20:51 +0000457
458 PBQPRAGraph::EdgeId EId = G.findEdge(N1Id, N2Id);
459 if (EId == G.invalidEdgeId()) {
460 PBQPRAGraph::RawMatrix Costs(Allowed1->size() + 1,
461 Allowed2->size() + 1, 0);
462 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
463 G.addEdge(N1Id, N2Id, std::move(Costs));
464 } else {
465 if (G.getEdgeNode1Id(EId) == N2Id) {
466 std::swap(N1Id, N2Id);
467 std::swap(Allowed1, Allowed2);
468 }
469 PBQPRAGraph::RawMatrix Costs(G.getEdgeCosts(EId));
470 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
Arnaud A. de Grandmaisonde790262015-02-11 08:25:36 +0000471 G.updateEdgeCosts(EId, std::move(Costs));
Lang Hames8f31f442014-10-09 18:20:51 +0000472 }
473 }
474 }
475 }
476 }
477
478private:
479
480 void addVirtRegCoalesce(
Lang Hames5fe30ca2014-10-27 17:44:25 +0000481 PBQPRAGraph::RawMatrix &CostMat,
482 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed1,
483 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed2,
484 PBQP::PBQPNum Benefit) {
Lang Hames8f31f442014-10-09 18:20:51 +0000485 assert(CostMat.getRows() == Allowed1.size() + 1 && "Size mismatch.");
486 assert(CostMat.getCols() == Allowed2.size() + 1 && "Size mismatch.");
487 for (unsigned I = 0; I != Allowed1.size(); ++I) {
488 unsigned PReg1 = Allowed1[I];
489 for (unsigned J = 0; J != Allowed2.size(); ++J) {
490 unsigned PReg2 = Allowed2[J];
491 if (PReg1 == PReg2)
Arnaud A. de Grandmaisond3648d02014-10-21 16:24:15 +0000492 CostMat[I + 1][J + 1] -= Benefit;
Lang Hames8f31f442014-10-09 18:20:51 +0000493 }
494 }
495 }
496
497};
498
Lang Hamesfd1bc422010-09-23 04:28:54 +0000499} // End anonymous namespace.
500
Lang Hames8f31f442014-10-09 18:20:51 +0000501// Out-of-line destructor/anchor for PBQPRAConstraint.
502PBQPRAConstraint::~PBQPRAConstraint() {}
503void PBQPRAConstraint::anchor() {}
504void PBQPRAConstraintList::anchor() {}
Lang Hamescb1e1012010-09-18 09:07:10 +0000505
506void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
Lang Hamesb13b6a02011-12-06 01:45:57 +0000507 au.setPreservesCFG();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000508 au.addRequired<AAResultsWrapperPass>();
509 au.addPreserved<AAResultsWrapperPass>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000510 au.addRequired<SlotIndexes>();
511 au.addPreserved<SlotIndexes>();
512 au.addRequired<LiveIntervals>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000513 au.addPreserved<LiveIntervals>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000514 //au.addRequiredID(SplitCriticalEdgesID);
Lang Hames934625e2011-06-17 07:09:01 +0000515 if (customPassID)
516 au.addRequiredID(*customPassID);
Lang Hamescb1e1012010-09-18 09:07:10 +0000517 au.addRequired<LiveStacks>();
518 au.addPreserved<LiveStacks>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000519 au.addRequired<MachineBlockFrequencyInfo>();
520 au.addPreserved<MachineBlockFrequencyInfo>();
Lang Hames7d99d792013-07-01 20:47:47 +0000521 au.addRequired<MachineLoopInfo>();
522 au.addPreserved<MachineLoopInfo>();
Lang Hamesb13b6a02011-12-06 01:45:57 +0000523 au.addRequired<MachineDominatorTree>();
524 au.addPreserved<MachineDominatorTree>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000525 au.addRequired<VirtRegMap>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000526 au.addPreserved<VirtRegMap>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000527 MachineFunctionPass::getAnalysisUsage(au);
528}
529
Lang Hames8f31f442014-10-09 18:20:51 +0000530void RegAllocPBQP::findVRegIntervalsToAlloc(const MachineFunction &MF,
531 LiveIntervals &LIS) {
532 const MachineRegisterInfo &MRI = MF.getRegInfo();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000533
534 // Iterate over all live ranges.
Lang Hames8f31f442014-10-09 18:20:51 +0000535 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
536 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
537 if (MRI.reg_nodbg_empty(Reg))
Lang Hames49ab8bc2008-11-16 12:12:54 +0000538 continue;
Lang Hames8f31f442014-10-09 18:20:51 +0000539 LiveInterval &LI = LIS.getInterval(Reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000540
541 // If this live interval is non-empty we will use pbqp to allocate it.
542 // Empty intervals we allocate in a simple post-processing stage in
543 // finalizeAlloc.
Lang Hames8f31f442014-10-09 18:20:51 +0000544 if (!LI.empty()) {
545 VRegsToAlloc.insert(LI.reg);
Lang Hamesc702ba62010-11-12 05:47:21 +0000546 } else {
Lang Hames8f31f442014-10-09 18:20:51 +0000547 EmptyIntervalVRegs.insert(LI.reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000548 }
549 }
Evan Chengb25f4632008-10-02 18:29:27 +0000550}
551
Arnaud A. de Grandmaisona11cab32014-11-04 20:51:29 +0000552static bool isACalleeSavedRegister(unsigned reg, const TargetRegisterInfo &TRI,
553 const MachineFunction &MF) {
554 const MCPhysReg *CSR = TRI.getCalleeSavedRegs(&MF);
555 for (unsigned i = 0; CSR[i] != 0; ++i)
556 if (TRI.regsOverlap(reg, CSR[i]))
557 return true;
558 return false;
559}
560
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000561void RegAllocPBQP::initializeGraph(PBQPRAGraph &G, VirtRegMap &VRM,
562 Spiller &VRegSpiller) {
Lang Hames8f31f442014-10-09 18:20:51 +0000563 MachineFunction &MF = G.getMetadata().MF;
564
565 LiveIntervals &LIS = G.getMetadata().LIS;
566 const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
567 const TargetRegisterInfo &TRI =
Eric Christopher7592b0c2015-01-27 08:27:06 +0000568 *G.getMetadata().MF.getSubtarget().getRegisterInfo();
Lang Hames8f31f442014-10-09 18:20:51 +0000569
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000570 std::vector<unsigned> Worklist(VRegsToAlloc.begin(), VRegsToAlloc.end());
571
572 while (!Worklist.empty()) {
573 unsigned VReg = Worklist.back();
574 Worklist.pop_back();
575
Lang Hames8f31f442014-10-09 18:20:51 +0000576 const TargetRegisterClass *TRC = MRI.getRegClass(VReg);
577 LiveInterval &VRegLI = LIS.getInterval(VReg);
578
579 // Record any overlaps with regmask operands.
580 BitVector RegMaskOverlaps;
581 LIS.checkRegMaskInterference(VRegLI, RegMaskOverlaps);
582
583 // Compute an initial allowed set for the current vreg.
584 std::vector<unsigned> VRegAllowed;
585 ArrayRef<MCPhysReg> RawPRegOrder = TRC->getRawAllocationOrder(MF);
586 for (unsigned I = 0; I != RawPRegOrder.size(); ++I) {
587 unsigned PReg = RawPRegOrder[I];
588 if (MRI.isReserved(PReg))
589 continue;
590
591 // vregLI crosses a regmask operand that clobbers preg.
592 if (!RegMaskOverlaps.empty() && !RegMaskOverlaps.test(PReg))
593 continue;
594
595 // vregLI overlaps fixed regunit interference.
596 bool Interference = false;
597 for (MCRegUnitIterator Units(PReg, &TRI); Units.isValid(); ++Units) {
598 if (VRegLI.overlaps(LIS.getRegUnit(*Units))) {
599 Interference = true;
600 break;
601 }
602 }
603 if (Interference)
604 continue;
605
606 // preg is usable for this virtual register.
607 VRegAllowed.push_back(PReg);
608 }
609
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000610 // Check for vregs that have no allowed registers. These should be
611 // pre-spilled and the new vregs added to the worklist.
612 if (VRegAllowed.empty()) {
613 SmallVector<unsigned, 8> NewVRegs;
614 spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000615 Worklist.insert(Worklist.end(), NewVRegs.begin(), NewVRegs.end());
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000616 continue;
617 }
618
Lang Hames8f31f442014-10-09 18:20:51 +0000619 PBQPRAGraph::RawVector NodeCosts(VRegAllowed.size() + 1, 0);
Arnaud A. de Grandmaisona11cab32014-11-04 20:51:29 +0000620
621 // Tweak cost of callee saved registers, as using then force spilling and
622 // restoring them. This would only happen in the prologue / epilogue though.
623 for (unsigned i = 0; i != VRegAllowed.size(); ++i)
624 if (isACalleeSavedRegister(VRegAllowed[i], TRI, MF))
625 NodeCosts[1 + i] += 1.0;
626
Lang Hames8f31f442014-10-09 18:20:51 +0000627 PBQPRAGraph::NodeId NId = G.addNode(std::move(NodeCosts));
628 G.getNodeMetadata(NId).setVReg(VReg);
Lang Hames5fe30ca2014-10-27 17:44:25 +0000629 G.getNodeMetadata(NId).setAllowedRegs(
630 G.getMetadata().getAllowedRegs(std::move(VRegAllowed)));
Lang Hames8f31f442014-10-09 18:20:51 +0000631 G.getMetadata().setNodeIdForVReg(VReg, NId);
632 }
633}
634
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000635void RegAllocPBQP::spillVReg(unsigned VReg,
636 SmallVectorImpl<unsigned> &NewIntervals,
637 MachineFunction &MF, LiveIntervals &LIS,
638 VirtRegMap &VRM, Spiller &VRegSpiller) {
639
640 VRegsToAlloc.erase(VReg);
Wei Mi9a16d652016-04-13 03:08:27 +0000641 LiveRangeEdit LRE(&LIS.getInterval(VReg), NewIntervals, MF, LIS, &VRM,
642 nullptr, &DeadRemats);
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000643 VRegSpiller.spill(LRE);
644
645 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
646 (void)TRI;
647 DEBUG(dbgs() << "VREG " << PrintReg(VReg, &TRI) << " -> SPILLED (Cost: "
648 << LRE.getParent().weight << ", New vregs: ");
649
650 // Copy any newly inserted live intervals into the list of regs to
651 // allocate.
652 for (LiveRangeEdit::iterator I = LRE.begin(), E = LRE.end();
653 I != E; ++I) {
654 const LiveInterval &LI = LIS.getInterval(*I);
655 assert(!LI.empty() && "Empty spill range.");
656 DEBUG(dbgs() << PrintReg(LI.reg, &TRI) << " ");
657 VRegsToAlloc.insert(LI.reg);
658 }
659
660 DEBUG(dbgs() << ")\n");
661}
662
Lang Hames8f31f442014-10-09 18:20:51 +0000663bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAGraph &G,
664 const PBQP::Solution &Solution,
665 VirtRegMap &VRM,
666 Spiller &VRegSpiller) {
667 MachineFunction &MF = G.getMetadata().MF;
668 LiveIntervals &LIS = G.getMetadata().LIS;
Eric Christopher7592b0c2015-01-27 08:27:06 +0000669 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
Lang Hames8f31f442014-10-09 18:20:51 +0000670 (void)TRI;
671
Lang Hamescb1e1012010-09-18 09:07:10 +0000672 // Set to true if we have any spills
Lang Hames8f31f442014-10-09 18:20:51 +0000673 bool AnotherRoundNeeded = false;
Lang Hamescb1e1012010-09-18 09:07:10 +0000674
675 // Clear the existing allocation.
Lang Hames8f31f442014-10-09 18:20:51 +0000676 VRM.clearAllVirt();
Lang Hamescb1e1012010-09-18 09:07:10 +0000677
Lang Hamescb1e1012010-09-18 09:07:10 +0000678 // Iterate over the nodes mapping the PBQP solution to a register
679 // assignment.
Lang Hames8f31f442014-10-09 18:20:51 +0000680 for (auto NId : G.nodeIds()) {
681 unsigned VReg = G.getNodeMetadata(NId).getVReg();
682 unsigned AllocOption = Solution.getSelection(NId);
Lang Hamescb1e1012010-09-18 09:07:10 +0000683
Lang Hames8f31f442014-10-09 18:20:51 +0000684 if (AllocOption != PBQP::RegAlloc::getSpillOptionIdx()) {
Lang Hames5fe30ca2014-10-27 17:44:25 +0000685 unsigned PReg = G.getNodeMetadata(NId).getAllowedRegs()[AllocOption - 1];
Lang Hames8f31f442014-10-09 18:20:51 +0000686 DEBUG(dbgs() << "VREG " << PrintReg(VReg, &TRI) << " -> "
687 << TRI.getName(PReg) << "\n");
688 assert(PReg != 0 && "Invalid preg selected.");
689 VRM.assignVirt2Phys(VReg, PReg);
690 } else {
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000691 // Spill VReg. If this introduces new intervals we'll need another round
692 // of allocation.
693 SmallVector<unsigned, 8> NewVRegs;
694 spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
695 AnotherRoundNeeded |= !NewVRegs.empty();
Lang Hamescb1e1012010-09-18 09:07:10 +0000696 }
697 }
698
Lang Hames8f31f442014-10-09 18:20:51 +0000699 return !AnotherRoundNeeded;
Lang Hamescb1e1012010-09-18 09:07:10 +0000700}
701
Lang Hames8f31f442014-10-09 18:20:51 +0000702void RegAllocPBQP::finalizeAlloc(MachineFunction &MF,
703 LiveIntervals &LIS,
704 VirtRegMap &VRM) const {
705 MachineRegisterInfo &MRI = MF.getRegInfo();
706
Lang Hames49ab8bc2008-11-16 12:12:54 +0000707 // First allocate registers for the empty intervals.
Lang Hamescb1e1012010-09-18 09:07:10 +0000708 for (RegSet::const_iterator
Lang Hames8f31f442014-10-09 18:20:51 +0000709 I = EmptyIntervalVRegs.begin(), E = EmptyIntervalVRegs.end();
710 I != E; ++I) {
711 LiveInterval &LI = LIS.getInterval(*I);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000712
Lang Hames8f31f442014-10-09 18:20:51 +0000713 unsigned PReg = MRI.getSimpleHint(LI.reg);
Lang Hames88fae6f2009-08-06 23:32:48 +0000714
Lang Hames8f31f442014-10-09 18:20:51 +0000715 if (PReg == 0) {
716 const TargetRegisterClass &RC = *MRI.getRegClass(LI.reg);
717 PReg = RC.getRawAllocationOrder(MF).front();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000718 }
Misha Brukmanda467482009-01-08 15:50:22 +0000719
Lang Hames8f31f442014-10-09 18:20:51 +0000720 VRM.assignVirt2Phys(LI.reg, PReg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000721 }
Lang Hames49ab8bc2008-11-16 12:12:54 +0000722}
723
Wei Mi9a16d652016-04-13 03:08:27 +0000724void RegAllocPBQP::postOptimization(Spiller &VRegSpiller, LiveIntervals &LIS) {
725 VRegSpiller.postOptimization();
726 /// Remove dead defs because of rematerialization.
727 for (auto DeadInst : DeadRemats) {
728 LIS.RemoveMachineInstrFromMaps(*DeadInst);
729 DeadInst->eraseFromParent();
730 }
731 DeadRemats.clear();
732}
733
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000734static inline float normalizePBQPSpillWeight(float UseDefFreq, unsigned Size,
735 unsigned NumInstr) {
736 // All intervals have a spill weight that is mostly proportional to the number
737 // of uses, with uses in loops having a bigger weight.
738 return NumInstr * normalizeSpillWeight(UseDefFreq, Size, 1);
739}
740
Lang Hamescb1e1012010-09-18 09:07:10 +0000741bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
Lang Hames8f31f442014-10-09 18:20:51 +0000742 LiveIntervals &LIS = getAnalysis<LiveIntervals>();
743 MachineBlockFrequencyInfo &MBFI =
744 getAnalysis<MachineBlockFrequencyInfo>();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000745
Lang Hames8f31f442014-10-09 18:20:51 +0000746 VirtRegMap &VRM = getAnalysis<VirtRegMap>();
Evan Chengb25f4632008-10-02 18:29:27 +0000747
Robert Lougher11a44b72015-08-10 11:59:44 +0000748 calculateSpillWeightsAndHints(LIS, MF, &VRM, getAnalysis<MachineLoopInfo>(),
749 MBFI, normalizePBQPSpillWeight);
750
Lang Hames8f31f442014-10-09 18:20:51 +0000751 std::unique_ptr<Spiller> VRegSpiller(createInlineSpiller(*this, MF, VRM));
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +0000752
Lang Hames8f31f442014-10-09 18:20:51 +0000753 MF.getRegInfo().freezeReservedRegs(MF);
Evan Chengb25f4632008-10-02 18:29:27 +0000754
Lang Hames8f31f442014-10-09 18:20:51 +0000755 DEBUG(dbgs() << "PBQP Register Allocating for " << MF.getName() << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000756
Evan Chengb25f4632008-10-02 18:29:27 +0000757 // Allocator main loop:
Misha Brukmanda467482009-01-08 15:50:22 +0000758 //
Evan Chengb25f4632008-10-02 18:29:27 +0000759 // * Map current regalloc problem to a PBQP problem
760 // * Solve the PBQP problem
761 // * Map the solution back to a register allocation
762 // * Spill if necessary
Misha Brukmanda467482009-01-08 15:50:22 +0000763 //
Evan Chengb25f4632008-10-02 18:29:27 +0000764 // This process is continued till no more spills are generated.
765
Lang Hames49ab8bc2008-11-16 12:12:54 +0000766 // Find the vreg intervals in need of allocation.
Lang Hames8f31f442014-10-09 18:20:51 +0000767 findVRegIntervalsToAlloc(MF, LIS);
Misha Brukmanda467482009-01-08 15:50:22 +0000768
Craig Toppera538d832012-08-22 06:07:19 +0000769#ifndef NDEBUG
Lang Hames8f31f442014-10-09 18:20:51 +0000770 const Function &F = *MF.getFunction();
771 std::string FullyQualifiedName =
772 F.getParent()->getModuleIdentifier() + "." + F.getName().str();
Craig Toppera538d832012-08-22 06:07:19 +0000773#endif
Lang Hames95e021f2012-03-26 23:07:23 +0000774
Lang Hames49ab8bc2008-11-16 12:12:54 +0000775 // If there are non-empty intervals allocate them using pbqp.
Lang Hames8f31f442014-10-09 18:20:51 +0000776 if (!VRegsToAlloc.empty()) {
Evan Chengb25f4632008-10-02 18:29:27 +0000777
Eric Christopher7592b0c2015-01-27 08:27:06 +0000778 const TargetSubtargetInfo &Subtarget = MF.getSubtarget();
Lang Hames8f31f442014-10-09 18:20:51 +0000779 std::unique_ptr<PBQPRAConstraintList> ConstraintsRoot =
780 llvm::make_unique<PBQPRAConstraintList>();
781 ConstraintsRoot->addConstraint(llvm::make_unique<SpillCosts>());
782 ConstraintsRoot->addConstraint(llvm::make_unique<Interference>());
783 if (PBQPCoalescing)
784 ConstraintsRoot->addConstraint(llvm::make_unique<Coalescing>());
785 ConstraintsRoot->addConstraint(Subtarget.getCustomPBQPConstraints());
Lang Hames49ab8bc2008-11-16 12:12:54 +0000786
Lang Hames8f31f442014-10-09 18:20:51 +0000787 bool PBQPAllocComplete = false;
788 unsigned Round = 0;
Lang Hames49ab8bc2008-11-16 12:12:54 +0000789
Lang Hames8f31f442014-10-09 18:20:51 +0000790 while (!PBQPAllocComplete) {
791 DEBUG(dbgs() << " PBQP Regalloc round " << Round << ":\n");
792
793 PBQPRAGraph G(PBQPRAGraph::GraphMetadata(MF, LIS, MBFI));
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000794 initializeGraph(G, VRM, *VRegSpiller);
Lang Hames8f31f442014-10-09 18:20:51 +0000795 ConstraintsRoot->apply(G);
Lang Hames95e021f2012-03-26 23:07:23 +0000796
797#ifndef NDEBUG
Lang Hames8f31f442014-10-09 18:20:51 +0000798 if (PBQPDumpGraphs) {
799 std::ostringstream RS;
800 RS << Round;
801 std::string GraphFileName = FullyQualifiedName + "." + RS.str() +
802 ".pbqpgraph";
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000803 std::error_code EC;
Lang Hames8f31f442014-10-09 18:20:51 +0000804 raw_fd_ostream OS(GraphFileName, EC, sys::fs::F_Text);
805 DEBUG(dbgs() << "Dumping graph for round " << Round << " to \""
806 << GraphFileName << "\"\n");
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000807 G.dump(OS);
Lang Hames95e021f2012-03-26 23:07:23 +0000808 }
809#endif
810
Lang Hames8f31f442014-10-09 18:20:51 +0000811 PBQP::Solution Solution = PBQP::RegAlloc::solve(G);
812 PBQPAllocComplete = mapPBQPToRegAlloc(G, Solution, VRM, *VRegSpiller);
813 ++Round;
Lang Hames49ab8bc2008-11-16 12:12:54 +0000814 }
Evan Chengb25f4632008-10-02 18:29:27 +0000815 }
816
Lang Hames49ab8bc2008-11-16 12:12:54 +0000817 // Finalise allocation, allocate empty ranges.
Lang Hames8f31f442014-10-09 18:20:51 +0000818 finalizeAlloc(MF, LIS, VRM);
Wei Mi9a16d652016-04-13 03:08:27 +0000819 postOptimization(*VRegSpiller, LIS);
Lang Hames8f31f442014-10-09 18:20:51 +0000820 VRegsToAlloc.clear();
821 EmptyIntervalVRegs.clear();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000822
Lang Hames8f31f442014-10-09 18:20:51 +0000823 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << VRM << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000824
Misha Brukmanda467482009-01-08 15:50:22 +0000825 return true;
Evan Chengb25f4632008-10-02 18:29:27 +0000826}
827
Matthias Braunc07cbc82015-12-04 01:31:59 +0000828/// Create Printable object for node and register info.
829static Printable PrintNodeInfo(PBQP::RegAlloc::PBQPRAGraph::NodeId NId,
830 const PBQP::RegAlloc::PBQPRAGraph &G) {
831 return Printable([NId, &G](raw_ostream &OS) {
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000832 const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
833 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
834 unsigned VReg = G.getNodeMetadata(NId).getVReg();
835 const char *RegClassName = TRI->getRegClassName(MRI.getRegClass(VReg));
836 OS << NId << " (" << RegClassName << ':' << PrintReg(VReg, TRI) << ')';
Matthias Braunc07cbc82015-12-04 01:31:59 +0000837 });
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000838}
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000839
840void PBQP::RegAlloc::PBQPRAGraph::dump(raw_ostream &OS) const {
841 for (auto NId : nodeIds()) {
842 const Vector &Costs = getNodeCosts(NId);
843 assert(Costs.getLength() != 0 && "Empty vector in graph.");
844 OS << PrintNodeInfo(NId, *this) << ": " << Costs << '\n';
845 }
846 OS << '\n';
847
848 for (auto EId : edgeIds()) {
849 NodeId N1Id = getEdgeNode1Id(EId);
850 NodeId N2Id = getEdgeNode2Id(EId);
851 assert(N1Id != N2Id && "PBQP graphs should not have self-edges.");
852 const Matrix &M = getEdgeCosts(EId);
853 assert(M.getRows() != 0 && "No rows in matrix.");
854 assert(M.getCols() != 0 && "No cols in matrix.");
855 OS << PrintNodeInfo(N1Id, *this) << ' ' << M.getRows() << " rows / ";
856 OS << PrintNodeInfo(N2Id, *this) << ' ' << M.getCols() << " cols:\n";
857 OS << M << '\n';
858 }
859}
860
Yaron Kereneb2a2542016-01-29 20:50:44 +0000861LLVM_DUMP_METHOD void PBQP::RegAlloc::PBQPRAGraph::dump() const { dump(dbgs()); }
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000862
863void PBQP::RegAlloc::PBQPRAGraph::printDot(raw_ostream &OS) const {
864 OS << "graph {\n";
865 for (auto NId : nodeIds()) {
866 OS << " node" << NId << " [ label=\""
867 << PrintNodeInfo(NId, *this) << "\\n"
868 << getNodeCosts(NId) << "\" ]\n";
869 }
870
871 OS << " edge [ len=" << nodeIds().size() << " ]\n";
872 for (auto EId : edgeIds()) {
873 OS << " node" << getEdgeNode1Id(EId)
874 << " -- node" << getEdgeNode2Id(EId)
875 << " [ label=\"";
876 const Matrix &EdgeCosts = getEdgeCosts(EId);
877 for (unsigned i = 0; i < EdgeCosts.getRows(); ++i) {
878 OS << EdgeCosts.getRowAsVector(i) << "\\n";
879 }
880 OS << "\" ]\n";
881 }
882 OS << "}\n";
883}
884
Lang Hames8f31f442014-10-09 18:20:51 +0000885FunctionPass *llvm::createPBQPRegisterAllocator(char *customPassID) {
886 return new RegAllocPBQP(customPassID);
Evan Chengb25f4632008-10-02 18:29:27 +0000887}
888
Lang Hamesfd1bc422010-09-23 04:28:54 +0000889FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
Lang Hames8f31f442014-10-09 18:20:51 +0000890 return createPBQPRegisterAllocator();
Lang Hamescb1e1012010-09-18 09:07:10 +0000891}
Evan Chengb25f4632008-10-02 18:29:27 +0000892
893#undef DEBUG_TYPE