blob: 69a879701fae281feb8f83b837f55ae3e514ebfb [file] [log] [blame]
Eugene Zelenko49e2fc42017-02-21 22:07:52 +00001//===- RegAllocPBQP.cpp ---- PBQP Register Allocator ----------------------===//
Evan Chengb25f4632008-10-02 18:29:27 +00002//
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 Carruth6bda14b2017-06-06 11:49:48 +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"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000035#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/BitVector.h"
37#include "llvm/ADT/DenseMap.h"
38#include "llvm/ADT/DenseSet.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000039#include "llvm/ADT/STLExtras.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000040#include "llvm/ADT/SmallPtrSet.h"
41#include "llvm/ADT/SmallVector.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000042#include "llvm/ADT/StringRef.h"
Lang Hamesb13b6a02011-12-06 01:45:57 +000043#include "llvm/Analysis/AliasAnalysis.h"
Lang Hamesd17e2962009-12-14 06:49:42 +000044#include "llvm/CodeGen/CalcSpillWeights.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000045#include "llvm/CodeGen/LiveInterval.h"
Matthias Braunf8422972017-12-13 02:51:04 +000046#include "llvm/CodeGen/LiveIntervals.h"
Pete Cooper3ca96f92012-04-02 22:44:18 +000047#include "llvm/CodeGen/LiveRangeEdit.h"
Matthias Braunef959692017-12-18 23:19:44 +000048#include "llvm/CodeGen/LiveStacks.h"
Benjamin Kramere2a1d892013-06-17 19:00:36 +000049#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Lang Hamesb13b6a02011-12-06 01:45:57 +000050#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000051#include "llvm/CodeGen/MachineFunction.h"
Misha Brukmanda467482009-01-08 15:50:22 +000052#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko7ea69232017-06-01 23:25:02 +000053#include "llvm/CodeGen/MachineInstr.h"
Lang Hames7d99d792013-07-01 20:47:47 +000054#include "llvm/CodeGen/MachineLoopInfo.h"
Misha Brukmanda467482009-01-08 15:50:22 +000055#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000056#include "llvm/CodeGen/PBQP/Graph.h"
Eugene Zelenko7ea69232017-06-01 23:25:02 +000057#include "llvm/CodeGen/PBQP/Math.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000058#include "llvm/CodeGen/PBQP/Solution.h"
59#include "llvm/CodeGen/PBQPRAConstraint.h"
Misha Brukmanda467482009-01-08 15:50:22 +000060#include "llvm/CodeGen/RegAllocRegistry.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000061#include "llvm/CodeGen/SlotIndexes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000062#include "llvm/CodeGen/TargetRegisterInfo.h"
63#include "llvm/CodeGen/TargetSubtargetInfo.h"
Jakob Stoklund Olesen26c9d702012-11-28 19:13:06 +000064#include "llvm/CodeGen/VirtRegMap.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000065#include "llvm/IR/Function.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000066#include "llvm/IR/Module.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000067#include "llvm/MC/MCRegisterInfo.h"
68#include "llvm/Pass.h"
69#include "llvm/Support/CommandLine.h"
70#include "llvm/Support/Compiler.h"
Evan Chengb25f4632008-10-02 18:29:27 +000071#include "llvm/Support/Debug.h"
Benjamin Kramerd59664f2014-04-29 23:26:49 +000072#include "llvm/Support/FileSystem.h"
Matthias Braunc07cbc82015-12-04 01:31:59 +000073#include "llvm/Support/Printable.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000074#include "llvm/Support/raw_ostream.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000075#include <algorithm>
76#include <cassert>
77#include <cstddef>
Misha Brukmanda467482009-01-08 15:50:22 +000078#include <limits>
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000079#include <map>
Misha Brukmanda467482009-01-08 15:50:22 +000080#include <memory>
Lang Hamesad0962a2014-10-18 17:26:07 +000081#include <queue>
Evan Chengb25f4632008-10-02 18:29:27 +000082#include <set>
Lang Hames95e021f2012-03-26 23:07:23 +000083#include <sstream>
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000084#include <string>
85#include <system_error>
86#include <tuple>
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000087#include <utility>
Chandler Carruth6bda14b2017-06-06 11:49:48 +000088#include <vector>
Evan Chengb25f4632008-10-02 18:29:27 +000089
Lang Hamesfd1bc422010-09-23 04:28:54 +000090using namespace llvm;
Lang Hamescb1e1012010-09-18 09:07:10 +000091
Chandler Carruth1b9dde02014-04-22 02:02:50 +000092#define DEBUG_TYPE "regalloc"
93
Evan Chengb25f4632008-10-02 18:29:27 +000094static RegisterRegAlloc
Lang Hames8f31f442014-10-09 18:20:51 +000095RegisterPBQPRepAlloc("pbqp", "PBQP register allocator",
Lang Hamesfd1bc422010-09-23 04:28:54 +000096 createDefaultPBQPRegisterAllocator);
Evan Chengb25f4632008-10-02 18:29:27 +000097
Lang Hames11732ad2009-08-19 01:36:14 +000098static cl::opt<bool>
Lang Hames8f31f442014-10-09 18:20:51 +000099PBQPCoalescing("pbqp-coalescing",
Lang Hames090c7e82010-01-26 04:49:58 +0000100 cl::desc("Attempt coalescing during PBQP register allocation."),
101 cl::init(false), cl::Hidden);
Lang Hames11732ad2009-08-19 01:36:14 +0000102
Lang Hames95e021f2012-03-26 23:07:23 +0000103#ifndef NDEBUG
104static cl::opt<bool>
Lang Hames8f31f442014-10-09 18:20:51 +0000105PBQPDumpGraphs("pbqp-dump-graphs",
Lang Hames95e021f2012-03-26 23:07:23 +0000106 cl::desc("Dump graphs for each function/round in the compilation unit."),
107 cl::init(false), cl::Hidden);
108#endif
109
Lang Hamesfd1bc422010-09-23 04:28:54 +0000110namespace {
111
112///
113/// PBQP based allocators solve the register allocation problem by mapping
114/// register allocation problems to Partitioned Boolean Quadratic
115/// Programming problems.
116class RegAllocPBQP : public MachineFunctionPass {
117public:
Lang Hamesfd1bc422010-09-23 04:28:54 +0000118 static char ID;
119
120 /// Construct a PBQP register allocator.
Lang Hames8f31f442014-10-09 18:20:51 +0000121 RegAllocPBQP(char *cPassID = nullptr)
122 : MachineFunctionPass(ID), customPassID(cPassID) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000123 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
124 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000125 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000126 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000127 }
Lang Hamesfd1bc422010-09-23 04:28:54 +0000128
129 /// Return the pass name.
Mehdi Amini117296c2016-10-01 02:56:57 +0000130 StringRef getPassName() const override { return "PBQP Register Allocator"; }
Lang Hamesfd1bc422010-09-23 04:28:54 +0000131
132 /// PBQP analysis usage.
Craig Topper4584cd52014-03-07 09:26:03 +0000133 void getAnalysisUsage(AnalysisUsage &au) const override;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000134
135 /// Perform register allocation
Craig Topper4584cd52014-03-07 09:26:03 +0000136 bool runOnMachineFunction(MachineFunction &MF) override;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000137
Matthias Braun90799ce2016-08-23 21:19:49 +0000138 MachineFunctionProperties getRequiredProperties() const override {
139 return MachineFunctionProperties().set(
140 MachineFunctionProperties::Property::NoPHIs);
141 }
142
Lang Hamesfd1bc422010-09-23 04:28:54 +0000143private:
Eugene Zelenko7ea69232017-06-01 23:25:02 +0000144 using LI2NodeMap = std::map<const LiveInterval *, unsigned>;
145 using Node2LIMap = std::vector<const LiveInterval *>;
146 using AllowedSet = std::vector<unsigned>;
147 using AllowedSetMap = std::vector<AllowedSet>;
148 using RegPair = std::pair<unsigned, unsigned>;
149 using CoalesceMap = std::map<RegPair, PBQP::PBQPNum>;
150 using RegSet = std::set<unsigned>;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000151
Lang Hames934625e2011-06-17 07:09:01 +0000152 char *customPassID;
153
Lang Hames8f31f442014-10-09 18:20:51 +0000154 RegSet VRegsToAlloc, EmptyIntervalVRegs;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000155
Wei Mi9a16d652016-04-13 03:08:27 +0000156 /// Inst which is a def of an original reg and whose defs are already all
157 /// dead after remat is saved in DeadRemats. The deletion of such inst is
158 /// postponed till all the allocations are done, so its remat expr is
159 /// always available for the remat of all the siblings of the original reg.
160 SmallPtrSet<MachineInstr *, 32> DeadRemats;
161
Lang Hamesfd1bc422010-09-23 04:28:54 +0000162 /// \brief Finds the initial set of vreg intervals to allocate.
Lang Hames8f31f442014-10-09 18:20:51 +0000163 void findVRegIntervalsToAlloc(const MachineFunction &MF, LiveIntervals &LIS);
164
165 /// \brief Constructs an initial graph.
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000166 void initializeGraph(PBQPRAGraph &G, VirtRegMap &VRM, Spiller &VRegSpiller);
167
168 /// \brief Spill the given VReg.
169 void spillVReg(unsigned VReg, SmallVectorImpl<unsigned> &NewIntervals,
170 MachineFunction &MF, LiveIntervals &LIS, VirtRegMap &VRM,
171 Spiller &VRegSpiller);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000172
Lang Hamesfd1bc422010-09-23 04:28:54 +0000173 /// \brief Given a solved PBQP problem maps this solution back to a register
174 /// assignment.
Lang Hames8f31f442014-10-09 18:20:51 +0000175 bool mapPBQPToRegAlloc(const PBQPRAGraph &G,
176 const PBQP::Solution &Solution,
177 VirtRegMap &VRM,
178 Spiller &VRegSpiller);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000179
180 /// \brief Postprocessing before final spilling. Sets basic block "live in"
181 /// variables.
Lang Hames8f31f442014-10-09 18:20:51 +0000182 void finalizeAlloc(MachineFunction &MF, LiveIntervals &LIS,
183 VirtRegMap &VRM) const;
Lang Hamesfd1bc422010-09-23 04:28:54 +0000184
Wei Mi9a16d652016-04-13 03:08:27 +0000185 void postOptimization(Spiller &VRegSpiller, LiveIntervals &LIS);
Lang Hamesfd1bc422010-09-23 04:28:54 +0000186};
187
Lang Hamescb1e1012010-09-18 09:07:10 +0000188char RegAllocPBQP::ID = 0;
Evan Chengb25f4632008-10-02 18:29:27 +0000189
Lang Hames8f31f442014-10-09 18:20:51 +0000190/// @brief Set spill costs for each node in the PBQP reg-alloc graph.
191class SpillCosts : public PBQPRAConstraint {
192public:
193 void apply(PBQPRAGraph &G) override {
194 LiveIntervals &LIS = G.getMetadata().LIS;
195
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000196 // A minimum spill costs, so that register constraints can can be set
197 // without normalization in the [0.0:MinSpillCost( interval.
198 const PBQP::PBQPNum MinSpillCost = 10.0;
199
Lang Hames8f31f442014-10-09 18:20:51 +0000200 for (auto NId : G.nodeIds()) {
201 PBQP::PBQPNum SpillCost =
202 LIS.getInterval(G.getNodeMetadata(NId).getVReg()).weight;
203 if (SpillCost == 0.0)
204 SpillCost = std::numeric_limits<PBQP::PBQPNum>::min();
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000205 else
206 SpillCost += MinSpillCost;
Lang Hames8f31f442014-10-09 18:20:51 +0000207 PBQPRAGraph::RawVector NodeCosts(G.getNodeCosts(NId));
208 NodeCosts[PBQP::RegAlloc::getSpillOptionIdx()] = SpillCost;
209 G.setNodeCosts(NId, std::move(NodeCosts));
210 }
211 }
212};
213
214/// @brief Add interference edges between overlapping vregs.
215class Interference : public PBQPRAConstraint {
Lang Hamesad0962a2014-10-18 17:26:07 +0000216private:
Eugene Zelenko7ea69232017-06-01 23:25:02 +0000217 using AllowedRegVecPtr = const PBQP::RegAlloc::AllowedRegVector *;
218 using IKey = std::pair<AllowedRegVecPtr, AllowedRegVecPtr>;
219 using IMatrixCache = DenseMap<IKey, PBQPRAGraph::MatrixPtr>;
220 using DisjointAllowedRegsCache = DenseSet<IKey>;
221 using IEdgeKey = std::pair<PBQP::GraphBase::NodeId, PBQP::GraphBase::NodeId>;
222 using IEdgeCache = DenseSet<IEdgeKey>;
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000223
224 bool haveDisjointAllowedRegs(const PBQPRAGraph &G, PBQPRAGraph::NodeId NId,
225 PBQPRAGraph::NodeId MId,
226 const DisjointAllowedRegsCache &D) const {
227 const auto *NRegs = &G.getNodeMetadata(NId).getAllowedRegs();
228 const auto *MRegs = &G.getNodeMetadata(MId).getAllowedRegs();
229
230 if (NRegs == MRegs)
231 return false;
232
233 if (NRegs < MRegs)
234 return D.count(IKey(NRegs, MRegs)) > 0;
Arnaud A. de Grandmaisona57ca812015-03-01 21:22:50 +0000235
236 return D.count(IKey(MRegs, NRegs)) > 0;
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000237 }
238
239 void setDisjointAllowedRegs(const PBQPRAGraph &G, PBQPRAGraph::NodeId NId,
240 PBQPRAGraph::NodeId MId,
241 DisjointAllowedRegsCache &D) {
242 const auto *NRegs = &G.getNodeMetadata(NId).getAllowedRegs();
243 const auto *MRegs = &G.getNodeMetadata(MId).getAllowedRegs();
244
245 assert(NRegs != MRegs && "AllowedRegs can not be disjoint with itself");
246
247 if (NRegs < MRegs)
248 D.insert(IKey(NRegs, MRegs));
249 else
250 D.insert(IKey(MRegs, NRegs));
251 }
Lang Hames5fe30ca2014-10-27 17:44:25 +0000252
Lang Hamesad0962a2014-10-18 17:26:07 +0000253 // Holds (Interval, CurrentSegmentID, and NodeId). The first two are required
254 // for the fast interference graph construction algorithm. The last is there
255 // to save us from looking up node ids via the VRegToNode map in the graph
256 // metadata.
Eugene Zelenko7ea69232017-06-01 23:25:02 +0000257 using IntervalInfo =
258 std::tuple<LiveInterval*, size_t, PBQP::GraphBase::NodeId>;
Lang Hamesad0962a2014-10-18 17:26:07 +0000259
260 static SlotIndex getStartPoint(const IntervalInfo &I) {
261 return std::get<0>(I)->segments[std::get<1>(I)].start;
262 }
263
264 static SlotIndex getEndPoint(const IntervalInfo &I) {
265 return std::get<0>(I)->segments[std::get<1>(I)].end;
266 }
267
268 static PBQP::GraphBase::NodeId getNodeId(const IntervalInfo &I) {
269 return std::get<2>(I);
270 }
271
272 static bool lowestStartPoint(const IntervalInfo &I1,
273 const IntervalInfo &I2) {
274 // Condition reversed because priority queue has the *highest* element at
275 // the front, rather than the lowest.
276 return getStartPoint(I1) > getStartPoint(I2);
277 }
278
279 static bool lowestEndPoint(const IntervalInfo &I1,
280 const IntervalInfo &I2) {
281 SlotIndex E1 = getEndPoint(I1);
282 SlotIndex E2 = getEndPoint(I2);
283
284 if (E1 < E2)
285 return true;
286
287 if (E1 > E2)
288 return false;
289
290 // If two intervals end at the same point, we need a way to break the tie or
291 // the set will assume they're actually equal and refuse to insert a
292 // "duplicate". Just compare the vregs - fast and guaranteed unique.
293 return std::get<0>(I1)->reg < std::get<0>(I2)->reg;
294 }
295
296 static bool isAtLastSegment(const IntervalInfo &I) {
297 return std::get<1>(I) == std::get<0>(I)->size() - 1;
298 }
299
300 static IntervalInfo nextSegment(const IntervalInfo &I) {
301 return std::make_tuple(std::get<0>(I), std::get<1>(I) + 1, std::get<2>(I));
302 }
303
Lang Hames8f31f442014-10-09 18:20:51 +0000304public:
Lang Hames8f31f442014-10-09 18:20:51 +0000305 void apply(PBQPRAGraph &G) override {
Lang Hamesad0962a2014-10-18 17:26:07 +0000306 // The following is loosely based on the linear scan algorithm introduced in
307 // "Linear Scan Register Allocation" by Poletto and Sarkar. This version
308 // isn't linear, because the size of the active set isn't bound by the
309 // number of registers, but rather the size of the largest clique in the
310 // graph. Still, we expect this to be better than N^2.
Lang Hames8f31f442014-10-09 18:20:51 +0000311 LiveIntervals &LIS = G.getMetadata().LIS;
Lang Hames5fe30ca2014-10-27 17:44:25 +0000312
313 // Interferenc matrices are incredibly regular - they're only a function of
314 // the allowed sets, so we cache them to avoid the overhead of constructing
315 // and uniquing them.
316 IMatrixCache C;
Lang Hames8f31f442014-10-09 18:20:51 +0000317
Arnaud A. de Grandmaisond8ed0d32015-03-05 09:12:59 +0000318 // Finding an edge is expensive in the worst case (O(max_clique(G))). So
319 // cache locally edges we have already seen.
320 IEdgeCache EC;
321
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000322 // Cache known disjoint allowed registers pairs
323 DisjointAllowedRegsCache D;
324
Eugene Zelenko7ea69232017-06-01 23:25:02 +0000325 using IntervalSet = std::set<IntervalInfo, decltype(&lowestEndPoint)>;
326 using IntervalQueue =
327 std::priority_queue<IntervalInfo, std::vector<IntervalInfo>,
328 decltype(&lowestStartPoint)>;
Lang Hamesad0962a2014-10-18 17:26:07 +0000329 IntervalSet Active(lowestEndPoint);
330 IntervalQueue Inactive(lowestStartPoint);
Lang Hames8f31f442014-10-09 18:20:51 +0000331
Lang Hamesad0962a2014-10-18 17:26:07 +0000332 // Start by building the inactive set.
333 for (auto NId : G.nodeIds()) {
334 unsigned VReg = G.getNodeMetadata(NId).getVReg();
335 LiveInterval &LI = LIS.getInterval(VReg);
336 assert(!LI.empty() && "PBQP graph contains node for empty interval");
337 Inactive.push(std::make_tuple(&LI, 0, NId));
338 }
Lang Hames8f31f442014-10-09 18:20:51 +0000339
Lang Hamesad0962a2014-10-18 17:26:07 +0000340 while (!Inactive.empty()) {
341 // Tentatively grab the "next" interval - this choice may be overriden
342 // below.
343 IntervalInfo Cur = Inactive.top();
344
345 // Retire any active intervals that end before Cur starts.
346 IntervalSet::iterator RetireItr = Active.begin();
347 while (RetireItr != Active.end() &&
348 (getEndPoint(*RetireItr) <= getStartPoint(Cur))) {
349 // If this interval has subsequent segments, add the next one to the
350 // inactive list.
351 if (!isAtLastSegment(*RetireItr))
352 Inactive.push(nextSegment(*RetireItr));
353
354 ++RetireItr;
Lang Hames8f31f442014-10-09 18:20:51 +0000355 }
Lang Hamesad0962a2014-10-18 17:26:07 +0000356 Active.erase(Active.begin(), RetireItr);
357
358 // One of the newly retired segments may actually start before the
359 // Cur segment, so re-grab the front of the inactive list.
360 Cur = Inactive.top();
361 Inactive.pop();
362
363 // At this point we know that Cur overlaps all active intervals. Add the
364 // interference edges.
365 PBQP::GraphBase::NodeId NId = getNodeId(Cur);
366 for (const auto &A : Active) {
367 PBQP::GraphBase::NodeId MId = getNodeId(A);
368
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000369 // Do not add an edge when the nodes' allowed registers do not
370 // intersect: there is obviously no interference.
371 if (haveDisjointAllowedRegs(G, NId, MId, D))
372 continue;
373
Lang Hamesad0962a2014-10-18 17:26:07 +0000374 // Check that we haven't already added this edge
Arnaud A. de Grandmaisond8ed0d32015-03-05 09:12:59 +0000375 IEdgeKey EK(std::min(NId, MId), std::max(NId, MId));
376 if (EC.count(EK))
Lang Hamesad0962a2014-10-18 17:26:07 +0000377 continue;
378
379 // This is a new edge - add it to the graph.
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000380 if (!createInterferenceEdge(G, NId, MId, C))
381 setDisjointAllowedRegs(G, NId, MId, D);
Arnaud A. de Grandmaisond8ed0d32015-03-05 09:12:59 +0000382 else
383 EC.insert(EK);
Lang Hamesad0962a2014-10-18 17:26:07 +0000384 }
385
386 // Finally, add Cur to the Active set.
387 Active.insert(Cur);
Lang Hames8f31f442014-10-09 18:20:51 +0000388 }
389 }
390
391private:
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000392 // Create an Interference edge and add it to the graph, unless it is
393 // a null matrix, meaning the nodes' allowed registers do not have any
394 // interference. This case occurs frequently between integer and floating
395 // point registers for example.
396 // return true iff both nodes interferes.
397 bool createInterferenceEdge(PBQPRAGraph &G,
398 PBQPRAGraph::NodeId NId, PBQPRAGraph::NodeId MId,
399 IMatrixCache &C) {
Lang Hames5fe30ca2014-10-27 17:44:25 +0000400 const TargetRegisterInfo &TRI =
Eric Christopher7592b0c2015-01-27 08:27:06 +0000401 *G.getMetadata().MF.getSubtarget().getRegisterInfo();
Lang Hames5fe30ca2014-10-27 17:44:25 +0000402 const auto &NRegs = G.getNodeMetadata(NId).getAllowedRegs();
403 const auto &MRegs = G.getNodeMetadata(MId).getAllowedRegs();
404
405 // Try looking the edge costs up in the IMatrixCache first.
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000406 IKey K(&NRegs, &MRegs);
Lang Hames5fe30ca2014-10-27 17:44:25 +0000407 IMatrixCache::iterator I = C.find(K);
408 if (I != C.end()) {
409 G.addEdgeBypassingCostAllocator(NId, MId, I->second);
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000410 return true;
Lang Hames5fe30ca2014-10-27 17:44:25 +0000411 }
412
413 PBQPRAGraph::RawMatrix M(NRegs.size() + 1, MRegs.size() + 1, 0);
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000414 bool NodesInterfere = false;
Lang Hames5fe30ca2014-10-27 17:44:25 +0000415 for (unsigned I = 0; I != NRegs.size(); ++I) {
416 unsigned PRegN = NRegs[I];
417 for (unsigned J = 0; J != MRegs.size(); ++J) {
418 unsigned PRegM = MRegs[J];
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000419 if (TRI.regsOverlap(PRegN, PRegM)) {
Lang Hames8f31f442014-10-09 18:20:51 +0000420 M[I + 1][J + 1] = std::numeric_limits<PBQP::PBQPNum>::infinity();
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000421 NodesInterfere = true;
422 }
Lang Hames8f31f442014-10-09 18:20:51 +0000423 }
424 }
425
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000426 if (!NodesInterfere)
427 return false;
428
Lang Hames5fe30ca2014-10-27 17:44:25 +0000429 PBQPRAGraph::EdgeId EId = G.addEdge(NId, MId, std::move(M));
430 C[K] = G.getEdgeCostsPtr(EId);
Arnaud A. de Grandmaison21fa0982015-03-01 20:39:34 +0000431
432 return true;
Lang Hames8f31f442014-10-09 18:20:51 +0000433 }
434};
435
Lang Hames8f31f442014-10-09 18:20:51 +0000436class Coalescing : public PBQPRAConstraint {
437public:
438 void apply(PBQPRAGraph &G) override {
439 MachineFunction &MF = G.getMetadata().MF;
440 MachineBlockFrequencyInfo &MBFI = G.getMetadata().MBFI;
Eric Christopher7592b0c2015-01-27 08:27:06 +0000441 CoalescerPair CP(*MF.getSubtarget().getRegisterInfo());
Lang Hames8f31f442014-10-09 18:20:51 +0000442
443 // Scan the machine function and add a coalescing cost whenever CoalescerPair
444 // gives the Ok.
445 for (const auto &MBB : MF) {
446 for (const auto &MI : MBB) {
Lang Hames8f31f442014-10-09 18:20:51 +0000447 // Skip not-coalescable or already coalesced copies.
448 if (!CP.setRegisters(&MI) || CP.getSrcReg() == CP.getDstReg())
449 continue;
450
451 unsigned DstReg = CP.getDstReg();
452 unsigned SrcReg = CP.getSrcReg();
453
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000454 const float Scale = 1.0f / MBFI.getEntryFreq();
455 PBQP::PBQPNum CBenefit = MBFI.getBlockFreq(&MBB).getFrequency() * Scale;
Lang Hames8f31f442014-10-09 18:20:51 +0000456
457 if (CP.isPhys()) {
458 if (!MF.getRegInfo().isAllocatable(DstReg))
459 continue;
460
461 PBQPRAGraph::NodeId NId = G.getMetadata().getNodeIdForVReg(SrcReg);
462
Lang Hames5fe30ca2014-10-27 17:44:25 +0000463 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed =
464 G.getNodeMetadata(NId).getAllowedRegs();
Lang Hames8f31f442014-10-09 18:20:51 +0000465
466 unsigned PRegOpt = 0;
467 while (PRegOpt < Allowed.size() && Allowed[PRegOpt] != DstReg)
468 ++PRegOpt;
469
470 if (PRegOpt < Allowed.size()) {
471 PBQPRAGraph::RawVector NewCosts(G.getNodeCosts(NId));
Arnaud A. de Grandmaisond3648d02014-10-21 16:24:15 +0000472 NewCosts[PRegOpt + 1] -= CBenefit;
Lang Hames8f31f442014-10-09 18:20:51 +0000473 G.setNodeCosts(NId, std::move(NewCosts));
474 }
475 } else {
476 PBQPRAGraph::NodeId N1Id = G.getMetadata().getNodeIdForVReg(DstReg);
477 PBQPRAGraph::NodeId N2Id = G.getMetadata().getNodeIdForVReg(SrcReg);
Lang Hames5fe30ca2014-10-27 17:44:25 +0000478 const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed1 =
479 &G.getNodeMetadata(N1Id).getAllowedRegs();
480 const PBQPRAGraph::NodeMetadata::AllowedRegVector *Allowed2 =
481 &G.getNodeMetadata(N2Id).getAllowedRegs();
Lang Hames8f31f442014-10-09 18:20:51 +0000482
483 PBQPRAGraph::EdgeId EId = G.findEdge(N1Id, N2Id);
484 if (EId == G.invalidEdgeId()) {
485 PBQPRAGraph::RawMatrix Costs(Allowed1->size() + 1,
486 Allowed2->size() + 1, 0);
487 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
488 G.addEdge(N1Id, N2Id, std::move(Costs));
489 } else {
490 if (G.getEdgeNode1Id(EId) == N2Id) {
491 std::swap(N1Id, N2Id);
492 std::swap(Allowed1, Allowed2);
493 }
494 PBQPRAGraph::RawMatrix Costs(G.getEdgeCosts(EId));
495 addVirtRegCoalesce(Costs, *Allowed1, *Allowed2, CBenefit);
Arnaud A. de Grandmaisonde790262015-02-11 08:25:36 +0000496 G.updateEdgeCosts(EId, std::move(Costs));
Lang Hames8f31f442014-10-09 18:20:51 +0000497 }
498 }
499 }
500 }
501 }
502
503private:
Lang Hames8f31f442014-10-09 18:20:51 +0000504 void addVirtRegCoalesce(
Lang Hames5fe30ca2014-10-27 17:44:25 +0000505 PBQPRAGraph::RawMatrix &CostMat,
506 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed1,
507 const PBQPRAGraph::NodeMetadata::AllowedRegVector &Allowed2,
508 PBQP::PBQPNum Benefit) {
Lang Hames8f31f442014-10-09 18:20:51 +0000509 assert(CostMat.getRows() == Allowed1.size() + 1 && "Size mismatch.");
510 assert(CostMat.getCols() == Allowed2.size() + 1 && "Size mismatch.");
511 for (unsigned I = 0; I != Allowed1.size(); ++I) {
512 unsigned PReg1 = Allowed1[I];
513 for (unsigned J = 0; J != Allowed2.size(); ++J) {
514 unsigned PReg2 = Allowed2[J];
515 if (PReg1 == PReg2)
Arnaud A. de Grandmaisond3648d02014-10-21 16:24:15 +0000516 CostMat[I + 1][J + 1] -= Benefit;
Lang Hames8f31f442014-10-09 18:20:51 +0000517 }
518 }
519 }
Lang Hames8f31f442014-10-09 18:20:51 +0000520};
521
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000522} // end anonymous namespace
Lang Hamesfd1bc422010-09-23 04:28:54 +0000523
Lang Hames8f31f442014-10-09 18:20:51 +0000524// Out-of-line destructor/anchor for PBQPRAConstraint.
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000525PBQPRAConstraint::~PBQPRAConstraint() = default;
526
Lang Hames8f31f442014-10-09 18:20:51 +0000527void PBQPRAConstraint::anchor() {}
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000528
Lang Hames8f31f442014-10-09 18:20:51 +0000529void PBQPRAConstraintList::anchor() {}
Lang Hamescb1e1012010-09-18 09:07:10 +0000530
531void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
Lang Hamesb13b6a02011-12-06 01:45:57 +0000532 au.setPreservesCFG();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000533 au.addRequired<AAResultsWrapperPass>();
534 au.addPreserved<AAResultsWrapperPass>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000535 au.addRequired<SlotIndexes>();
536 au.addPreserved<SlotIndexes>();
537 au.addRequired<LiveIntervals>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000538 au.addPreserved<LiveIntervals>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000539 //au.addRequiredID(SplitCriticalEdgesID);
Lang Hames934625e2011-06-17 07:09:01 +0000540 if (customPassID)
541 au.addRequiredID(*customPassID);
Lang Hamescb1e1012010-09-18 09:07:10 +0000542 au.addRequired<LiveStacks>();
543 au.addPreserved<LiveStacks>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000544 au.addRequired<MachineBlockFrequencyInfo>();
545 au.addPreserved<MachineBlockFrequencyInfo>();
Lang Hames7d99d792013-07-01 20:47:47 +0000546 au.addRequired<MachineLoopInfo>();
547 au.addPreserved<MachineLoopInfo>();
Lang Hamesb13b6a02011-12-06 01:45:57 +0000548 au.addRequired<MachineDominatorTree>();
549 au.addPreserved<MachineDominatorTree>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000550 au.addRequired<VirtRegMap>();
Lang Hames8ce99f22012-10-04 04:50:53 +0000551 au.addPreserved<VirtRegMap>();
Lang Hamescb1e1012010-09-18 09:07:10 +0000552 MachineFunctionPass::getAnalysisUsage(au);
553}
554
Lang Hames8f31f442014-10-09 18:20:51 +0000555void RegAllocPBQP::findVRegIntervalsToAlloc(const MachineFunction &MF,
556 LiveIntervals &LIS) {
557 const MachineRegisterInfo &MRI = MF.getRegInfo();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000558
559 // Iterate over all live ranges.
Lang Hames8f31f442014-10-09 18:20:51 +0000560 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
561 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
562 if (MRI.reg_nodbg_empty(Reg))
Lang Hames49ab8bc2008-11-16 12:12:54 +0000563 continue;
Lang Hames8f31f442014-10-09 18:20:51 +0000564 LiveInterval &LI = LIS.getInterval(Reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000565
566 // If this live interval is non-empty we will use pbqp to allocate it.
567 // Empty intervals we allocate in a simple post-processing stage in
568 // finalizeAlloc.
Lang Hames8f31f442014-10-09 18:20:51 +0000569 if (!LI.empty()) {
570 VRegsToAlloc.insert(LI.reg);
Lang Hamesc702ba62010-11-12 05:47:21 +0000571 } else {
Lang Hames8f31f442014-10-09 18:20:51 +0000572 EmptyIntervalVRegs.insert(LI.reg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000573 }
574 }
Evan Chengb25f4632008-10-02 18:29:27 +0000575}
576
Arnaud A. de Grandmaisona11cab32014-11-04 20:51:29 +0000577static bool isACalleeSavedRegister(unsigned reg, const TargetRegisterInfo &TRI,
578 const MachineFunction &MF) {
Oren Ben Simhonfe34c5e2017-03-14 09:09:26 +0000579 const MCPhysReg *CSR = MF.getRegInfo().getCalleeSavedRegs();
Arnaud A. de Grandmaisona11cab32014-11-04 20:51:29 +0000580 for (unsigned i = 0; CSR[i] != 0; ++i)
581 if (TRI.regsOverlap(reg, CSR[i]))
582 return true;
583 return false;
584}
585
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000586void RegAllocPBQP::initializeGraph(PBQPRAGraph &G, VirtRegMap &VRM,
587 Spiller &VRegSpiller) {
Lang Hames8f31f442014-10-09 18:20:51 +0000588 MachineFunction &MF = G.getMetadata().MF;
589
590 LiveIntervals &LIS = G.getMetadata().LIS;
591 const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
592 const TargetRegisterInfo &TRI =
Eric Christopher7592b0c2015-01-27 08:27:06 +0000593 *G.getMetadata().MF.getSubtarget().getRegisterInfo();
Lang Hames8f31f442014-10-09 18:20:51 +0000594
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000595 std::vector<unsigned> Worklist(VRegsToAlloc.begin(), VRegsToAlloc.end());
596
597 while (!Worklist.empty()) {
598 unsigned VReg = Worklist.back();
599 Worklist.pop_back();
600
Lang Hames8f31f442014-10-09 18:20:51 +0000601 const TargetRegisterClass *TRC = MRI.getRegClass(VReg);
602 LiveInterval &VRegLI = LIS.getInterval(VReg);
603
604 // Record any overlaps with regmask operands.
605 BitVector RegMaskOverlaps;
606 LIS.checkRegMaskInterference(VRegLI, RegMaskOverlaps);
607
608 // Compute an initial allowed set for the current vreg.
609 std::vector<unsigned> VRegAllowed;
610 ArrayRef<MCPhysReg> RawPRegOrder = TRC->getRawAllocationOrder(MF);
611 for (unsigned I = 0; I != RawPRegOrder.size(); ++I) {
612 unsigned PReg = RawPRegOrder[I];
613 if (MRI.isReserved(PReg))
614 continue;
615
616 // vregLI crosses a regmask operand that clobbers preg.
617 if (!RegMaskOverlaps.empty() && !RegMaskOverlaps.test(PReg))
618 continue;
619
620 // vregLI overlaps fixed regunit interference.
621 bool Interference = false;
622 for (MCRegUnitIterator Units(PReg, &TRI); Units.isValid(); ++Units) {
623 if (VRegLI.overlaps(LIS.getRegUnit(*Units))) {
624 Interference = true;
625 break;
626 }
627 }
628 if (Interference)
629 continue;
630
631 // preg is usable for this virtual register.
632 VRegAllowed.push_back(PReg);
633 }
634
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000635 // Check for vregs that have no allowed registers. These should be
636 // pre-spilled and the new vregs added to the worklist.
637 if (VRegAllowed.empty()) {
638 SmallVector<unsigned, 8> NewVRegs;
639 spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000640 Worklist.insert(Worklist.end(), NewVRegs.begin(), NewVRegs.end());
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000641 continue;
642 }
643
Lang Hames8f31f442014-10-09 18:20:51 +0000644 PBQPRAGraph::RawVector NodeCosts(VRegAllowed.size() + 1, 0);
Arnaud A. de Grandmaisona11cab32014-11-04 20:51:29 +0000645
646 // Tweak cost of callee saved registers, as using then force spilling and
647 // restoring them. This would only happen in the prologue / epilogue though.
648 for (unsigned i = 0; i != VRegAllowed.size(); ++i)
649 if (isACalleeSavedRegister(VRegAllowed[i], TRI, MF))
650 NodeCosts[1 + i] += 1.0;
651
Lang Hames8f31f442014-10-09 18:20:51 +0000652 PBQPRAGraph::NodeId NId = G.addNode(std::move(NodeCosts));
653 G.getNodeMetadata(NId).setVReg(VReg);
Lang Hames5fe30ca2014-10-27 17:44:25 +0000654 G.getNodeMetadata(NId).setAllowedRegs(
655 G.getMetadata().getAllowedRegs(std::move(VRegAllowed)));
Lang Hames8f31f442014-10-09 18:20:51 +0000656 G.getMetadata().setNodeIdForVReg(VReg, NId);
657 }
658}
659
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000660void RegAllocPBQP::spillVReg(unsigned VReg,
661 SmallVectorImpl<unsigned> &NewIntervals,
662 MachineFunction &MF, LiveIntervals &LIS,
663 VirtRegMap &VRM, Spiller &VRegSpiller) {
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000664 VRegsToAlloc.erase(VReg);
Wei Mi9a16d652016-04-13 03:08:27 +0000665 LiveRangeEdit LRE(&LIS.getInterval(VReg), NewIntervals, MF, LIS, &VRM,
666 nullptr, &DeadRemats);
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000667 VRegSpiller.spill(LRE);
668
669 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
670 (void)TRI;
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +0000671 DEBUG(dbgs() << "VREG " << printReg(VReg, &TRI) << " -> SPILLED (Cost: "
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000672 << LRE.getParent().weight << ", New vregs: ");
673
674 // Copy any newly inserted live intervals into the list of regs to
675 // allocate.
676 for (LiveRangeEdit::iterator I = LRE.begin(), E = LRE.end();
677 I != E; ++I) {
678 const LiveInterval &LI = LIS.getInterval(*I);
679 assert(!LI.empty() && "Empty spill range.");
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +0000680 DEBUG(dbgs() << printReg(LI.reg, &TRI) << " ");
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000681 VRegsToAlloc.insert(LI.reg);
682 }
683
684 DEBUG(dbgs() << ")\n");
685}
686
Lang Hames8f31f442014-10-09 18:20:51 +0000687bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAGraph &G,
688 const PBQP::Solution &Solution,
689 VirtRegMap &VRM,
690 Spiller &VRegSpiller) {
691 MachineFunction &MF = G.getMetadata().MF;
692 LiveIntervals &LIS = G.getMetadata().LIS;
Eric Christopher7592b0c2015-01-27 08:27:06 +0000693 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
Lang Hames8f31f442014-10-09 18:20:51 +0000694 (void)TRI;
695
Lang Hamescb1e1012010-09-18 09:07:10 +0000696 // Set to true if we have any spills
Lang Hames8f31f442014-10-09 18:20:51 +0000697 bool AnotherRoundNeeded = false;
Lang Hamescb1e1012010-09-18 09:07:10 +0000698
699 // Clear the existing allocation.
Lang Hames8f31f442014-10-09 18:20:51 +0000700 VRM.clearAllVirt();
Lang Hamescb1e1012010-09-18 09:07:10 +0000701
Lang Hamescb1e1012010-09-18 09:07:10 +0000702 // Iterate over the nodes mapping the PBQP solution to a register
703 // assignment.
Lang Hames8f31f442014-10-09 18:20:51 +0000704 for (auto NId : G.nodeIds()) {
705 unsigned VReg = G.getNodeMetadata(NId).getVReg();
706 unsigned AllocOption = Solution.getSelection(NId);
Lang Hamescb1e1012010-09-18 09:07:10 +0000707
Lang Hames8f31f442014-10-09 18:20:51 +0000708 if (AllocOption != PBQP::RegAlloc::getSpillOptionIdx()) {
Lang Hames5fe30ca2014-10-27 17:44:25 +0000709 unsigned PReg = G.getNodeMetadata(NId).getAllowedRegs()[AllocOption - 1];
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +0000710 DEBUG(dbgs() << "VREG " << printReg(VReg, &TRI) << " -> "
Lang Hames8f31f442014-10-09 18:20:51 +0000711 << TRI.getName(PReg) << "\n");
712 assert(PReg != 0 && "Invalid preg selected.");
713 VRM.assignVirt2Phys(VReg, PReg);
714 } else {
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000715 // Spill VReg. If this introduces new intervals we'll need another round
716 // of allocation.
717 SmallVector<unsigned, 8> NewVRegs;
718 spillVReg(VReg, NewVRegs, MF, LIS, VRM, VRegSpiller);
719 AnotherRoundNeeded |= !NewVRegs.empty();
Lang Hamescb1e1012010-09-18 09:07:10 +0000720 }
721 }
722
Lang Hames8f31f442014-10-09 18:20:51 +0000723 return !AnotherRoundNeeded;
Lang Hamescb1e1012010-09-18 09:07:10 +0000724}
725
Lang Hames8f31f442014-10-09 18:20:51 +0000726void RegAllocPBQP::finalizeAlloc(MachineFunction &MF,
727 LiveIntervals &LIS,
728 VirtRegMap &VRM) const {
729 MachineRegisterInfo &MRI = MF.getRegInfo();
730
Lang Hames49ab8bc2008-11-16 12:12:54 +0000731 // First allocate registers for the empty intervals.
Lang Hamescb1e1012010-09-18 09:07:10 +0000732 for (RegSet::const_iterator
Lang Hames8f31f442014-10-09 18:20:51 +0000733 I = EmptyIntervalVRegs.begin(), E = EmptyIntervalVRegs.end();
734 I != E; ++I) {
735 LiveInterval &LI = LIS.getInterval(*I);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000736
Lang Hames8f31f442014-10-09 18:20:51 +0000737 unsigned PReg = MRI.getSimpleHint(LI.reg);
Lang Hames88fae6f2009-08-06 23:32:48 +0000738
Lang Hames8f31f442014-10-09 18:20:51 +0000739 if (PReg == 0) {
740 const TargetRegisterClass &RC = *MRI.getRegClass(LI.reg);
Matthias Braun1ee25e02017-06-08 21:30:54 +0000741 const ArrayRef<MCPhysReg> RawPRegOrder = RC.getRawAllocationOrder(MF);
742 for (unsigned CandidateReg : RawPRegOrder) {
743 if (!VRM.getRegInfo().isReserved(CandidateReg)) {
744 PReg = CandidateReg;
745 break;
746 }
747 }
748 assert(PReg &&
749 "No un-reserved physical registers in this register class");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000750 }
Misha Brukmanda467482009-01-08 15:50:22 +0000751
Lang Hames8f31f442014-10-09 18:20:51 +0000752 VRM.assignVirt2Phys(LI.reg, PReg);
Lang Hames49ab8bc2008-11-16 12:12:54 +0000753 }
Lang Hames49ab8bc2008-11-16 12:12:54 +0000754}
755
Wei Mi9a16d652016-04-13 03:08:27 +0000756void RegAllocPBQP::postOptimization(Spiller &VRegSpiller, LiveIntervals &LIS) {
757 VRegSpiller.postOptimization();
758 /// Remove dead defs because of rematerialization.
759 for (auto DeadInst : DeadRemats) {
760 LIS.RemoveMachineInstrFromMaps(*DeadInst);
761 DeadInst->eraseFromParent();
762 }
763 DeadRemats.clear();
764}
765
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +0000766static inline float normalizePBQPSpillWeight(float UseDefFreq, unsigned Size,
767 unsigned NumInstr) {
768 // All intervals have a spill weight that is mostly proportional to the number
769 // of uses, with uses in loops having a bigger weight.
770 return NumInstr * normalizeSpillWeight(UseDefFreq, Size, 1);
771}
772
Lang Hamescb1e1012010-09-18 09:07:10 +0000773bool RegAllocPBQP::runOnMachineFunction(MachineFunction &MF) {
Lang Hames8f31f442014-10-09 18:20:51 +0000774 LiveIntervals &LIS = getAnalysis<LiveIntervals>();
775 MachineBlockFrequencyInfo &MBFI =
776 getAnalysis<MachineBlockFrequencyInfo>();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000777
Lang Hames8f31f442014-10-09 18:20:51 +0000778 VirtRegMap &VRM = getAnalysis<VirtRegMap>();
Evan Chengb25f4632008-10-02 18:29:27 +0000779
Robert Lougher11a44b72015-08-10 11:59:44 +0000780 calculateSpillWeightsAndHints(LIS, MF, &VRM, getAnalysis<MachineLoopInfo>(),
781 MBFI, normalizePBQPSpillWeight);
782
Lang Hames8f31f442014-10-09 18:20:51 +0000783 std::unique_ptr<Spiller> VRegSpiller(createInlineSpiller(*this, MF, VRM));
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +0000784
Lang Hames8f31f442014-10-09 18:20:51 +0000785 MF.getRegInfo().freezeReservedRegs(MF);
Evan Chengb25f4632008-10-02 18:29:27 +0000786
Lang Hames8f31f442014-10-09 18:20:51 +0000787 DEBUG(dbgs() << "PBQP Register Allocating for " << MF.getName() << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000788
Evan Chengb25f4632008-10-02 18:29:27 +0000789 // Allocator main loop:
Misha Brukmanda467482009-01-08 15:50:22 +0000790 //
Evan Chengb25f4632008-10-02 18:29:27 +0000791 // * Map current regalloc problem to a PBQP problem
792 // * Solve the PBQP problem
793 // * Map the solution back to a register allocation
794 // * Spill if necessary
Misha Brukmanda467482009-01-08 15:50:22 +0000795 //
Evan Chengb25f4632008-10-02 18:29:27 +0000796 // This process is continued till no more spills are generated.
797
Lang Hames49ab8bc2008-11-16 12:12:54 +0000798 // Find the vreg intervals in need of allocation.
Lang Hames8f31f442014-10-09 18:20:51 +0000799 findVRegIntervalsToAlloc(MF, LIS);
Misha Brukmanda467482009-01-08 15:50:22 +0000800
Craig Toppera538d832012-08-22 06:07:19 +0000801#ifndef NDEBUG
Matthias Braunf1caa282017-12-15 22:22:58 +0000802 const Function &F = MF.getFunction();
Lang Hames8f31f442014-10-09 18:20:51 +0000803 std::string FullyQualifiedName =
804 F.getParent()->getModuleIdentifier() + "." + F.getName().str();
Craig Toppera538d832012-08-22 06:07:19 +0000805#endif
Lang Hames95e021f2012-03-26 23:07:23 +0000806
Lang Hames49ab8bc2008-11-16 12:12:54 +0000807 // If there are non-empty intervals allocate them using pbqp.
Lang Hames8f31f442014-10-09 18:20:51 +0000808 if (!VRegsToAlloc.empty()) {
Eric Christopher7592b0c2015-01-27 08:27:06 +0000809 const TargetSubtargetInfo &Subtarget = MF.getSubtarget();
Lang Hames8f31f442014-10-09 18:20:51 +0000810 std::unique_ptr<PBQPRAConstraintList> ConstraintsRoot =
811 llvm::make_unique<PBQPRAConstraintList>();
812 ConstraintsRoot->addConstraint(llvm::make_unique<SpillCosts>());
813 ConstraintsRoot->addConstraint(llvm::make_unique<Interference>());
814 if (PBQPCoalescing)
815 ConstraintsRoot->addConstraint(llvm::make_unique<Coalescing>());
816 ConstraintsRoot->addConstraint(Subtarget.getCustomPBQPConstraints());
Lang Hames49ab8bc2008-11-16 12:12:54 +0000817
Lang Hames8f31f442014-10-09 18:20:51 +0000818 bool PBQPAllocComplete = false;
819 unsigned Round = 0;
Lang Hames49ab8bc2008-11-16 12:12:54 +0000820
Lang Hames8f31f442014-10-09 18:20:51 +0000821 while (!PBQPAllocComplete) {
822 DEBUG(dbgs() << " PBQP Regalloc round " << Round << ":\n");
823
824 PBQPRAGraph G(PBQPRAGraph::GraphMetadata(MF, LIS, MBFI));
Lang Hamesd48bf3f2015-02-03 06:14:06 +0000825 initializeGraph(G, VRM, *VRegSpiller);
Lang Hames8f31f442014-10-09 18:20:51 +0000826 ConstraintsRoot->apply(G);
Lang Hames95e021f2012-03-26 23:07:23 +0000827
828#ifndef NDEBUG
Lang Hames8f31f442014-10-09 18:20:51 +0000829 if (PBQPDumpGraphs) {
830 std::ostringstream RS;
831 RS << Round;
832 std::string GraphFileName = FullyQualifiedName + "." + RS.str() +
833 ".pbqpgraph";
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000834 std::error_code EC;
Lang Hames8f31f442014-10-09 18:20:51 +0000835 raw_fd_ostream OS(GraphFileName, EC, sys::fs::F_Text);
836 DEBUG(dbgs() << "Dumping graph for round " << Round << " to \""
837 << GraphFileName << "\"\n");
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000838 G.dump(OS);
Lang Hames95e021f2012-03-26 23:07:23 +0000839 }
840#endif
841
Lang Hames8f31f442014-10-09 18:20:51 +0000842 PBQP::Solution Solution = PBQP::RegAlloc::solve(G);
843 PBQPAllocComplete = mapPBQPToRegAlloc(G, Solution, VRM, *VRegSpiller);
844 ++Round;
Lang Hames49ab8bc2008-11-16 12:12:54 +0000845 }
Evan Chengb25f4632008-10-02 18:29:27 +0000846 }
847
Lang Hames49ab8bc2008-11-16 12:12:54 +0000848 // Finalise allocation, allocate empty ranges.
Lang Hames8f31f442014-10-09 18:20:51 +0000849 finalizeAlloc(MF, LIS, VRM);
Wei Mi9a16d652016-04-13 03:08:27 +0000850 postOptimization(*VRegSpiller, LIS);
Lang Hames8f31f442014-10-09 18:20:51 +0000851 VRegsToAlloc.clear();
852 EmptyIntervalVRegs.clear();
Lang Hames49ab8bc2008-11-16 12:12:54 +0000853
Lang Hames8f31f442014-10-09 18:20:51 +0000854 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << VRM << "\n");
Lang Hames49ab8bc2008-11-16 12:12:54 +0000855
Misha Brukmanda467482009-01-08 15:50:22 +0000856 return true;
Evan Chengb25f4632008-10-02 18:29:27 +0000857}
858
Matthias Braunc07cbc82015-12-04 01:31:59 +0000859/// Create Printable object for node and register info.
860static Printable PrintNodeInfo(PBQP::RegAlloc::PBQPRAGraph::NodeId NId,
861 const PBQP::RegAlloc::PBQPRAGraph &G) {
862 return Printable([NId, &G](raw_ostream &OS) {
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000863 const MachineRegisterInfo &MRI = G.getMetadata().MF.getRegInfo();
864 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
865 unsigned VReg = G.getNodeMetadata(NId).getVReg();
866 const char *RegClassName = TRI->getRegClassName(MRI.getRegClass(VReg));
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +0000867 OS << NId << " (" << RegClassName << ':' << printReg(VReg, TRI) << ')';
Matthias Braunc07cbc82015-12-04 01:31:59 +0000868 });
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000869}
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000870
Aaron Ballman615eb472017-10-15 14:32:27 +0000871#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +0000872LLVM_DUMP_METHOD void PBQP::RegAlloc::PBQPRAGraph::dump(raw_ostream &OS) const {
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000873 for (auto NId : nodeIds()) {
874 const Vector &Costs = getNodeCosts(NId);
875 assert(Costs.getLength() != 0 && "Empty vector in graph.");
876 OS << PrintNodeInfo(NId, *this) << ": " << Costs << '\n';
877 }
878 OS << '\n';
879
880 for (auto EId : edgeIds()) {
881 NodeId N1Id = getEdgeNode1Id(EId);
882 NodeId N2Id = getEdgeNode2Id(EId);
883 assert(N1Id != N2Id && "PBQP graphs should not have self-edges.");
884 const Matrix &M = getEdgeCosts(EId);
885 assert(M.getRows() != 0 && "No rows in matrix.");
886 assert(M.getCols() != 0 && "No cols in matrix.");
887 OS << PrintNodeInfo(N1Id, *this) << ' ' << M.getRows() << " rows / ";
888 OS << PrintNodeInfo(N2Id, *this) << ' ' << M.getCols() << " cols:\n";
889 OS << M << '\n';
890 }
891}
892
Matthias Braun8c209aa2017-01-28 02:02:38 +0000893LLVM_DUMP_METHOD void PBQP::RegAlloc::PBQPRAGraph::dump() const {
894 dump(dbgs());
895}
896#endif
Arnaud A. de Grandmaison10797c52015-02-03 23:40:24 +0000897
898void PBQP::RegAlloc::PBQPRAGraph::printDot(raw_ostream &OS) const {
899 OS << "graph {\n";
900 for (auto NId : nodeIds()) {
901 OS << " node" << NId << " [ label=\""
902 << PrintNodeInfo(NId, *this) << "\\n"
903 << getNodeCosts(NId) << "\" ]\n";
904 }
905
906 OS << " edge [ len=" << nodeIds().size() << " ]\n";
907 for (auto EId : edgeIds()) {
908 OS << " node" << getEdgeNode1Id(EId)
909 << " -- node" << getEdgeNode2Id(EId)
910 << " [ label=\"";
911 const Matrix &EdgeCosts = getEdgeCosts(EId);
912 for (unsigned i = 0; i < EdgeCosts.getRows(); ++i) {
913 OS << EdgeCosts.getRowAsVector(i) << "\\n";
914 }
915 OS << "\" ]\n";
916 }
917 OS << "}\n";
918}
919
Lang Hames8f31f442014-10-09 18:20:51 +0000920FunctionPass *llvm::createPBQPRegisterAllocator(char *customPassID) {
921 return new RegAllocPBQP(customPassID);
Evan Chengb25f4632008-10-02 18:29:27 +0000922}
923
Lang Hamesfd1bc422010-09-23 04:28:54 +0000924FunctionPass* llvm::createDefaultPBQPRegisterAllocator() {
Lang Hames8f31f442014-10-09 18:20:51 +0000925 return createPBQPRegisterAllocator();
Lang Hamescb1e1012010-09-18 09:07:10 +0000926}