blob: a4f6b682a23f39ccc15a38309ca86d331f408241 [file] [log] [blame]
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00001//===-- RegAllocGreedy.cpp - greedy register allocator --------------------===//
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//===----------------------------------------------------------------------===//
9//
10// This file defines the RAGreedy function pass for register allocation in
11// optimized builds.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "regalloc"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesen4d7432e2010-12-10 22:21:05 +000017#include "AllocationOrder.h"
Jakob Stoklund Olesen91cbcaf2011-04-02 06:03:35 +000018#include "InterferenceCache.h"
Jakob Stoklund Olesen6aa0fbf2011-04-05 21:40:37 +000019#include "LiveDebugVariables.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000020#include "RegAllocBase.h"
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +000021#include "SpillPlacement.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "Spiller.h"
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +000023#include "SplitKit.h"
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000024#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000025#include "llvm/Analysis/AliasAnalysis.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000026#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +000027#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000028#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper3ca96f92012-04-02 22:44:18 +000029#include "llvm/CodeGen/LiveRangeEdit.h"
Jakob Stoklund Olesen26c9d702012-11-28 19:13:06 +000030#include "llvm/CodeGen/LiveRegMatrix.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000031#include "llvm/CodeGen/LiveStackAnalysis.h"
Benjamin Kramere2a1d892013-06-17 19:00:36 +000032#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +000033#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000034#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000035#include "llvm/CodeGen/MachineLoopInfo.h"
36#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000037#include "llvm/CodeGen/RegAllocRegistry.h"
Quentin Colombet1fb3362a2014-01-02 22:47:22 +000038#include "llvm/CodeGen/RegisterClassInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000039#include "llvm/CodeGen/VirtRegMap.h"
40#include "llvm/PassAnalysisSupport.h"
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +000041#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000042#include "llvm/Support/Debug.h"
43#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen92da7052010-12-11 00:19:56 +000044#include "llvm/Support/Timer.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000045#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +000046#include <queue>
47
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000048using namespace llvm;
49
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000050STATISTIC(NumGlobalSplits, "Number of split global live ranges");
51STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000052STATISTIC(NumEvicted, "Number of interferences evicted");
53
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +000054static cl::opt<SplitEditor::ComplementSpillMode>
55SplitSpillMode("split-spill-mode", cl::Hidden,
56 cl::desc("Spill mode for splitting live ranges"),
57 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
58 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
59 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
60 clEnumValEnd),
61 cl::init(SplitEditor::SM_Partition));
62
Quentin Colombet87769712014-02-05 22:13:59 +000063static cl::opt<unsigned>
64LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden,
65 cl::desc("Last chance recoloring max depth"),
66 cl::init(5));
67
68static cl::opt<unsigned> LastChanceRecoloringMaxInterference(
69 "lcr-max-interf", cl::Hidden,
70 cl::desc("Last chance recoloring maximum number of considered"
71 " interference at a time"),
72 cl::init(8));
73
Manman Ren78cf02a2014-03-25 00:16:25 +000074// FIXME: Find a good default for this flag and remove the flag.
75static cl::opt<unsigned>
76CSRFirstTimeCost("regalloc-csr-first-time-cost",
77 cl::desc("Cost for first time use of callee-saved register."),
78 cl::init(0), cl::Hidden);
79
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000080static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
81 createGreedyRegisterAllocator);
82
83namespace {
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +000084class RAGreedy : public MachineFunctionPass,
85 public RegAllocBase,
86 private LiveRangeEdit::Delegate {
Quentin Colombet87769712014-02-05 22:13:59 +000087 // Convenient shortcuts.
88 typedef std::priority_queue<std::pair<unsigned, unsigned> > PQueue;
89 typedef SmallPtrSet<LiveInterval *, 4> SmallLISet;
90 typedef SmallSet<unsigned, 16> SmallVirtRegSet;
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +000091
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000092 // context
93 MachineFunction *MF;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000094
Quentin Colombet1fb3362a2014-01-02 22:47:22 +000095 // Shortcuts to some useful interface.
96 const TargetInstrInfo *TII;
97 const TargetRegisterInfo *TRI;
98 RegisterClassInfo RCI;
99
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000100 // analyses
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000101 SlotIndexes *Indexes;
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000102 MachineBlockFrequencyInfo *MBFI;
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000103 MachineDominatorTree *DomTree;
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +0000104 MachineLoopInfo *Loops;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000105 EdgeBundles *Bundles;
106 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000107 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000108
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000109 // state
Ahmed Charles56440fd2014-03-06 05:51:42 +0000110 std::unique_ptr<Spiller> SpillerInstance;
Quentin Colombet87769712014-02-05 22:13:59 +0000111 PQueue Queue;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000112 unsigned NextCascade;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000113
114 // Live ranges pass through a number of stages as we try to allocate them.
115 // Some of the stages may also create new live ranges:
116 //
117 // - Region splitting.
118 // - Per-block splitting.
119 // - Local splitting.
120 // - Spilling.
121 //
122 // Ranges produced by one of the stages skip the previous stages when they are
123 // dequeued. This improves performance because we can skip interference checks
124 // that are unlikely to give any results. It also guarantees that the live
125 // range splitting algorithm terminates, something that is otherwise hard to
126 // ensure.
127 enum LiveRangeStage {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000128 /// Newly created live range that has never been queued.
129 RS_New,
130
131 /// Only attempt assignment and eviction. Then requeue as RS_Split.
132 RS_Assign,
133
134 /// Attempt live range splitting if assignment is impossible.
135 RS_Split,
136
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000137 /// Attempt more aggressive live range splitting that is guaranteed to make
138 /// progress. This is used for split products that may not be making
139 /// progress.
140 RS_Split2,
141
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000142 /// Live range will be spilled. No more splitting will be attempted.
143 RS_Spill,
144
145 /// There is nothing more we can do to this live range. Abort compilation
146 /// if it can't be assigned.
147 RS_Done
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000148 };
149
Eli Friedman78bffa52013-09-10 23:18:14 +0000150#ifndef NDEBUG
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000151 static const char *const StageName[];
Eli Friedman78bffa52013-09-10 23:18:14 +0000152#endif
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000153
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000154 // RegInfo - Keep additional information about each live range.
155 struct RegInfo {
156 LiveRangeStage Stage;
157
158 // Cascade - Eviction loop prevention. See canEvictInterference().
159 unsigned Cascade;
160
161 RegInfo() : Stage(RS_New), Cascade(0) {}
162 };
163
164 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000165
166 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000167 return ExtraRegInfo[VirtReg.reg].Stage;
168 }
169
170 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
171 ExtraRegInfo.resize(MRI->getNumVirtRegs());
172 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000173 }
174
175 template<typename Iterator>
176 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000177 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000178 for (;Begin != End; ++Begin) {
Mark Laceyf9ea8852013-08-14 23:50:04 +0000179 unsigned Reg = *Begin;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000180 if (ExtraRegInfo[Reg].Stage == RS_New)
181 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000182 }
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000183 }
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000184
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000185 /// Cost of evicting interference.
186 struct EvictionCost {
187 unsigned BrokenHints; ///< Total number of broken hints.
188 float MaxWeight; ///< Maximum spill weight evicted.
189
Andrew Trick3621b8a2013-11-22 19:07:38 +0000190 EvictionCost(): BrokenHints(0), MaxWeight(0) {}
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000191
Andrew Trick84852572013-07-25 18:35:14 +0000192 bool isMax() const { return BrokenHints == ~0u; }
193
Andrew Trick3621b8a2013-11-22 19:07:38 +0000194 void setMax() { BrokenHints = ~0u; }
195
196 void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
197
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000198 bool operator<(const EvictionCost &O) const {
Benjamin Kramerb2f034b2014-03-03 19:58:30 +0000199 return std::tie(BrokenHints, MaxWeight) <
200 std::tie(O.BrokenHints, O.MaxWeight);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000201 }
202 };
203
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000204 // splitting state.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000205 std::unique_ptr<SplitAnalysis> SA;
206 std::unique_ptr<SplitEditor> SE;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000207
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000208 /// Cached per-block interference maps
209 InterferenceCache IntfCache;
210
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000211 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000212 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000213
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000214 /// Global live range splitting candidate info.
215 struct GlobalSplitCandidate {
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000216 // Register intended for assignment, or 0.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000217 unsigned PhysReg;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000218
219 // SplitKit interval index for this candidate.
220 unsigned IntvIdx;
221
222 // Interference for PhysReg.
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000223 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000224
225 // Bundles where this candidate should be live.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000226 BitVector LiveBundles;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000227 SmallVector<unsigned, 8> ActiveBlocks;
228
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000229 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000230 PhysReg = Reg;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000231 IntvIdx = 0;
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000232 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000233 LiveBundles.clear();
234 ActiveBlocks.clear();
235 }
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000236
237 // Set B[i] = C for every live bundle where B[i] was NoCand.
238 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
239 unsigned Count = 0;
240 for (int i = LiveBundles.find_first(); i >= 0;
241 i = LiveBundles.find_next(i))
242 if (B[i] == NoCand) {
243 B[i] = C;
244 Count++;
245 }
246 return Count;
247 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000248 };
249
Aditya Nandakumarc1fd0dd2013-11-19 23:51:32 +0000250 /// Candidate info for each PhysReg in AllocationOrder.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000251 /// This vector never shrinks, but grows to the size of the largest register
252 /// class.
253 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
254
Alp Toker61007d82014-03-02 03:20:38 +0000255 enum : unsigned { NoCand = ~0u };
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000256
257 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
258 /// NoCand which indicates the stack interval.
259 SmallVector<unsigned, 32> BundleCand;
260
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000261public:
262 RAGreedy();
263
264 /// Return the pass name.
Craig Topper4584cd52014-03-07 09:26:03 +0000265 const char* getPassName() const override {
Jakob Stoklund Olesen92da7052010-12-11 00:19:56 +0000266 return "Greedy Register Allocator";
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000267 }
268
269 /// RAGreedy analysis usage.
Craig Topper4584cd52014-03-07 09:26:03 +0000270 void getAnalysisUsage(AnalysisUsage &AU) const override;
271 void releaseMemory() override;
272 Spiller &spiller() override { return *SpillerInstance; }
273 void enqueue(LiveInterval *LI) override;
274 LiveInterval *dequeue() override;
275 unsigned selectOrSplit(LiveInterval&, SmallVectorImpl<unsigned>&) override;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000276
277 /// Perform register allocation.
Craig Topper4584cd52014-03-07 09:26:03 +0000278 bool runOnMachineFunction(MachineFunction &mf) override;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000279
280 static char ID;
Andrew Trickccef0982010-12-09 18:15:21 +0000281
282private:
Quentin Colombet87769712014-02-05 22:13:59 +0000283 unsigned selectOrSplitImpl(LiveInterval &, SmallVectorImpl<unsigned> &,
284 SmallVirtRegSet &, unsigned = 0);
285
Craig Topper4584cd52014-03-07 09:26:03 +0000286 bool LRE_CanEraseVirtReg(unsigned) override;
287 void LRE_WillShrinkVirtReg(unsigned) override;
288 void LRE_DidCloneVirtReg(unsigned, unsigned) override;
Quentin Colombet87769712014-02-05 22:13:59 +0000289 void enqueue(PQueue &CurQueue, LiveInterval *LI);
290 LiveInterval *dequeue(PQueue &CurQueue);
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000291
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000292 BlockFrequency calcSpillCost();
293 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000294 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000295 void growRegion(GlobalSplitCandidate &Cand);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000296 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +0000297 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000298 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +0000299 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Andrew Trick8bb0a252013-07-25 18:35:19 +0000300 unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000301 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
302 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
303 void evictInterference(LiveInterval&, unsigned,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000304 SmallVectorImpl<unsigned>&);
Quentin Colombet87769712014-02-05 22:13:59 +0000305 bool mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
306 SmallLISet &RecoloringCandidates,
307 const SmallVirtRegSet &FixedRegisters);
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +0000308
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000309 unsigned tryAssign(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000310 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000311 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000312 SmallVectorImpl<unsigned>&, unsigned = ~0u);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000313 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000314 SmallVectorImpl<unsigned>&);
Manman Ren9db66b32014-03-24 23:23:42 +0000315 /// Calculate cost of region splitting.
316 unsigned calculateRegionSplitCost(LiveInterval &VirtReg,
317 AllocationOrder &Order,
318 BlockFrequency &BestCost,
Manman Ren78cf02a2014-03-25 00:16:25 +0000319 unsigned &NumCands, bool IgnoreCSR);
Manman Ren9db66b32014-03-24 23:23:42 +0000320 /// Perform region splitting.
321 unsigned doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
322 bool HasCompact,
323 SmallVectorImpl<unsigned> &NewVRegs);
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +0000324 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000325 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +0000326 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000327 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +0000328 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000329 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +0000330 unsigned trySplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000331 SmallVectorImpl<unsigned>&);
Quentin Colombet87769712014-02-05 22:13:59 +0000332 unsigned tryLastChanceRecoloring(LiveInterval &, AllocationOrder &,
333 SmallVectorImpl<unsigned> &,
334 SmallVirtRegSet &, unsigned);
335 bool tryRecoloringCandidates(PQueue &, SmallVectorImpl<unsigned> &,
336 SmallVirtRegSet &, unsigned);
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000337};
338} // end anonymous namespace
339
340char RAGreedy::ID = 0;
341
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000342#ifndef NDEBUG
343const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000344 "RS_New",
345 "RS_Assign",
346 "RS_Split",
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000347 "RS_Split2",
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000348 "RS_Spill",
349 "RS_Done"
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000350};
351#endif
352
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000353// Hysteresis to use when comparing floats.
354// This helps stabilize decisions based on float comparisons.
NAKAMURA Takumia71003a2014-02-04 06:29:38 +0000355const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000356
357
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000358FunctionPass* llvm::createGreedyRegisterAllocator() {
359 return new RAGreedy();
360}
361
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000362RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesen6aa0fbf2011-04-05 21:40:37 +0000363 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000364 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000365 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
366 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Rafael Espindola676c4052011-06-26 22:34:10 +0000367 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Tricke1c034f2012-01-17 06:55:03 +0000368 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000369 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
370 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
371 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
372 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000373 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000374 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
375 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000376}
377
378void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
379 AU.setPreservesCFG();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000380 AU.addRequired<MachineBlockFrequencyInfo>();
381 AU.addPreserved<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000382 AU.addRequired<AliasAnalysis>();
383 AU.addPreserved<AliasAnalysis>();
384 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesen12243122012-06-08 23:44:45 +0000385 AU.addPreserved<LiveIntervals>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000386 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000387 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesen6aa0fbf2011-04-05 21:40:37 +0000388 AU.addRequired<LiveDebugVariables>();
389 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000390 AU.addRequired<LiveStacks>();
391 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000392 AU.addRequired<MachineDominatorTree>();
393 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000394 AU.addRequired<MachineLoopInfo>();
395 AU.addPreserved<MachineLoopInfo>();
396 AU.addRequired<VirtRegMap>();
397 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000398 AU.addRequired<LiveRegMatrix>();
399 AU.addPreserved<LiveRegMatrix>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000400 AU.addRequired<EdgeBundles>();
401 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000402 MachineFunctionPass::getAnalysisUsage(AU);
403}
404
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000405
406//===----------------------------------------------------------------------===//
407// LiveRangeEdit delegate methods
408//===----------------------------------------------------------------------===//
409
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000410bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000411 if (VRM->hasPhys(VirtReg)) {
412 Matrix->unassign(LIS->getInterval(VirtReg));
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000413 return true;
414 }
415 // Unassigned virtreg is probably in the priority queue.
416 // RegAllocBase will erase it after dequeueing.
417 return false;
418}
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000419
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000420void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000421 if (!VRM->hasPhys(VirtReg))
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000422 return;
423
424 // Register is assigned, put it back on the queue for reassignment.
425 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000426 Matrix->unassign(LI);
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000427 enqueue(&LI);
428}
429
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000430void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen811b9c42011-09-14 17:34:37 +0000431 // Cloning a register we haven't even heard about yet? Just ignore it.
432 if (!ExtraRegInfo.inBounds(Old))
433 return;
434
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000435 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen5387bd32011-07-26 00:54:56 +0000436 // be split into connected components. The new components are much smaller
437 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000438 // same stage as the parent.
Jakob Stoklund Olesen5387bd32011-07-26 00:54:56 +0000439 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000440 ExtraRegInfo.grow(New);
441 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000442}
443
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000444void RAGreedy::releaseMemory() {
445 SpillerInstance.reset(0);
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000446 ExtraRegInfo.clear();
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000447 GlobalCand.clear();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000448}
449
Quentin Colombet87769712014-02-05 22:13:59 +0000450void RAGreedy::enqueue(LiveInterval *LI) { enqueue(Queue, LI); }
451
452void RAGreedy::enqueue(PQueue &CurQueue, LiveInterval *LI) {
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000453 // Prioritize live ranges by size, assigning larger ranges first.
454 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +0000455 const unsigned Size = LI->getSize();
456 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000457 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
458 "Can only enqueue virtual registers");
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +0000459 unsigned Prio;
Jakob Stoklund Oleseneaa650a2010-12-08 22:57:16 +0000460
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000461 ExtraRegInfo.grow(Reg);
462 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000463 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000464
Jakob Stoklund Olesencad845f2011-07-28 20:48:23 +0000465 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000466 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesen45df7e02011-09-12 16:54:42 +0000467 // everything else has been allocated.
468 Prio = Size;
Jakob Stoklund Olesencad845f2011-07-28 20:48:23 +0000469 } else {
Andrew Trick52a00932014-02-26 22:07:26 +0000470 // Giant live ranges fall back to the global assignment heuristic, which
471 // prevents excessive spilling in pathological cases.
472 bool ReverseLocal = TRI->reverseLocalAssignment();
Andrew Trickb1531e52014-02-27 21:37:33 +0000473 bool ForceGlobal = !ReverseLocal && TRI->mayOverrideLocalAssignment() &&
Andrew Trick52a00932014-02-26 22:07:26 +0000474 (Size / SlotIndex::InstrDist) > (2 * MRI->getRegClass(Reg)->getNumRegs());
475
476 if (ExtraRegInfo[Reg].Stage == RS_Assign && !ForceGlobal && !LI->empty() &&
Andrew Trick84852572013-07-25 18:35:14 +0000477 LIS->intervalIsInOneMBB(*LI)) {
478 // Allocate original local ranges in linear instruction order. Since they
479 // are singly defined, this produces optimal coloring in the absence of
480 // global interference and other constraints.
Andrew Trick52a00932014-02-26 22:07:26 +0000481 if (!ReverseLocal)
Andrew Trick2d8826a2013-12-11 03:40:15 +0000482 Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
483 else {
484 // Allocating bottom up may allow many short LRGs to be assigned first
485 // to one of the cheap registers. This could be much faster for very
486 // large blocks on targets with many physical registers.
487 Prio = Indexes->getZeroIndex().getInstrDistance(LI->beginIndex());
488 }
Andrew Trick84852572013-07-25 18:35:14 +0000489 }
490 else {
491 // Allocate global and split ranges in long->short order. Long ranges that
492 // don't fit should be spilled (or split) ASAP so they don't create
493 // interference. Mark a bit to prioritize global above local ranges.
494 Prio = (1u << 29) + Size;
495 }
496 // Mark a higher bit to prioritize global and local above RS_Split.
497 Prio |= (1u << 31);
Jakob Stoklund Olesenb51f65c2011-02-23 00:56:56 +0000498
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000499 // Boost ranges that have a physical register hint.
Jakob Stoklund Olesen74052b02012-12-03 23:23:50 +0000500 if (VRM->hasKnownPreference(Reg))
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000501 Prio |= (1u << 30);
502 }
Andrew Trickf4b1ee32013-07-25 18:35:22 +0000503 // The virtual register number is a tie breaker for same-sized ranges.
504 // Give lower vreg numbers higher priority to assign them first.
Quentin Colombet87769712014-02-05 22:13:59 +0000505 CurQueue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Oleseneaa650a2010-12-08 22:57:16 +0000506}
507
Quentin Colombet87769712014-02-05 22:13:59 +0000508LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); }
509
510LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
511 if (CurQueue.empty())
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000512 return 0;
Quentin Colombet87769712014-02-05 22:13:59 +0000513 LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
514 CurQueue.pop();
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000515 return LI;
516}
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000517
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000518
519//===----------------------------------------------------------------------===//
520// Direct Assignment
521//===----------------------------------------------------------------------===//
522
523/// tryAssign - Try to assign VirtReg to an available register.
524unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
525 AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000526 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000527 Order.rewind();
528 unsigned PhysReg;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000529 while ((PhysReg = Order.next()))
530 if (!Matrix->checkInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000531 break;
Jakob Stoklund Olesen3cb2cb82012-12-04 22:25:16 +0000532 if (!PhysReg || Order.isHint())
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000533 return PhysReg;
534
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000535 // PhysReg is available, but there may be a better choice.
536
537 // If we missed a simple hint, try to cheaply evict interference from the
538 // preferred register.
539 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000540 if (Order.isHint(Hint)) {
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000541 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
Andrew Trick3621b8a2013-11-22 19:07:38 +0000542 EvictionCost MaxCost;
543 MaxCost.setBrokenHints(1);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000544 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
545 evictInterference(VirtReg, Hint, NewVRegs);
546 return Hint;
547 }
548 }
549
550 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000551 unsigned Cost = TRI->getCostPerUse(PhysReg);
552
553 // Most registers have 0 additional cost.
554 if (!Cost)
555 return PhysReg;
556
557 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
558 << '\n');
559 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
560 return CheapReg ? CheapReg : PhysReg;
561}
562
563
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000564//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000565// Interference eviction
566//===----------------------------------------------------------------------===//
567
Andrew Trick8bb0a252013-07-25 18:35:19 +0000568unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
569 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
570 unsigned PhysReg;
571 while ((PhysReg = Order.next())) {
572 if (PhysReg == PrevReg)
573 continue;
574
575 MCRegUnitIterator Units(PhysReg, TRI);
576 for (; Units.isValid(); ++Units) {
577 // Instantiate a "subquery", not to be confused with the Queries array.
578 LiveIntervalUnion::Query subQ(&VirtReg, &Matrix->getLiveUnions()[*Units]);
579 if (subQ.checkInterference())
580 break;
581 }
582 // If no units have interference, break out with the current PhysReg.
583 if (!Units.isValid())
584 break;
585 }
586 if (PhysReg)
587 DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
588 << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
589 << '\n');
590 return PhysReg;
591}
592
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000593/// shouldEvict - determine if A should evict the assigned live range B. The
594/// eviction policy defined by this function together with the allocation order
595/// defined by enqueue() decides which registers ultimately end up being split
596/// and spilled.
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000597///
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000598/// Cascade numbers are used to prevent infinite loops if this function is a
599/// cyclic relation.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000600///
601/// @param A The live range to be assigned.
602/// @param IsHint True when A is about to be assigned to its preferred
603/// register.
604/// @param B The live range to be evicted.
605/// @param BreaksHint True when B is already assigned to its preferred register.
606bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
607 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000608 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000609
610 // Be fairly aggressive about following hints as long as the evictee can be
611 // split.
612 if (CanSplit && IsHint && !BreaksHint)
613 return true;
614
Andrew Trick059e8002013-11-22 19:07:42 +0000615 if (A.weight > B.weight) {
616 DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight << '\n');
617 return true;
618 }
619 return false;
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000620}
621
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000622/// canEvictInterference - Return true if all interferences between VirtReg and
Manman Renfa32ca12014-02-25 19:47:15 +0000623/// PhysReg can be evicted.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000624///
625/// @param VirtReg Live range that is about to be assigned.
626/// @param PhysReg Desired register for assignment.
Dmitri Gribenko881929c2012-09-12 16:59:47 +0000627/// @param IsHint True when PhysReg is VirtReg's preferred register.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000628/// @param MaxCost Only look for cheaper candidates and update with new cost
629/// when returning true.
630/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000631bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000632 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000633 // It is only possible to evict virtual register interference.
634 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
635 return false;
636
Andrew Trick84852572013-07-25 18:35:14 +0000637 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
638
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000639 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
640 // involved in an eviction before. If a cascade number was assigned, deny
641 // evicting anything with the same or a newer cascade number. This prevents
642 // infinite eviction loops.
643 //
644 // This works out so a register without a cascade number is allowed to evict
645 // anything, and it can be evicted by anything.
646 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
647 if (!Cascade)
648 Cascade = NextCascade;
649
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000650 EvictionCost Cost;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000651 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
652 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen0f175eb2011-04-11 21:47:01 +0000653 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000654 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000655 return false;
656
Jakob Stoklund Olesen0f175eb2011-04-11 21:47:01 +0000657 // Check if any interfering live range is heavier than MaxWeight.
658 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
659 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000660 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
661 "Only expecting virtual register interference from query");
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000662 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000663 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000664 return false;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000665 // Once a live range becomes small enough, it is urgent that we find a
666 // register for it. This is indicated by an infinite spill weight. These
667 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen05e22452012-05-30 21:46:58 +0000668 //
669 // Also allow urgent evictions of unspillable ranges from a strictly
670 // larger allocation order.
671 bool Urgent = !VirtReg.isSpillable() &&
672 (Intf->isSpillable() ||
673 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
674 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000675 // Only evict older cascades or live ranges without a cascade.
676 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
677 if (Cascade <= IntfCascade) {
678 if (!Urgent)
679 return false;
680 // We permit breaking cascades for urgent evictions. It should be the
681 // last resort, though, so make it really expensive.
682 Cost.BrokenHints += 10;
683 }
684 // Would this break a satisfied hint?
685 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
686 // Update eviction cost.
687 Cost.BrokenHints += BreaksHint;
688 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
689 // Abort if this would be too expensive.
690 if (!(Cost < MaxCost))
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000691 return false;
Andrew Trick84852572013-07-25 18:35:14 +0000692 if (Urgent)
693 continue;
Andrew Trickc2ab53a2013-11-29 23:49:38 +0000694 // Apply the eviction policy for non-urgent evictions.
695 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
696 return false;
Andrew Trick84852572013-07-25 18:35:14 +0000697 // If !MaxCost.isMax(), then we're just looking for a cheap register.
698 // Evicting another local live range in this case could lead to suboptimal
699 // coloring.
Andrew Trick8bb0a252013-07-25 18:35:19 +0000700 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
701 !canReassign(*Intf, PhysReg)) {
Andrew Trick84852572013-07-25 18:35:14 +0000702 return false;
Andrew Trick8bb0a252013-07-25 18:35:19 +0000703 }
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000704 }
705 }
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000706 MaxCost = Cost;
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000707 return true;
708}
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000709
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000710/// evictInterference - Evict any interferring registers that prevent VirtReg
711/// from being assigned to Physreg. This assumes that canEvictInterference
712/// returned true.
713void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000714 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000715 // Make sure that VirtReg has a cascade number, and assign that cascade
716 // number to every evicted register. These live ranges than then only be
717 // evicted by a newer cascade, preventing infinite loops.
718 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
719 if (!Cascade)
720 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
721
722 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
723 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000724
725 // Collect all interfering virtregs first.
726 SmallVector<LiveInterval*, 8> Intfs;
727 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
728 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000729 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000730 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
731 Intfs.append(IVR.begin(), IVR.end());
732 }
733
734 // Evict them second. This will invalidate the queries.
735 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
736 LiveInterval *Intf = Intfs[i];
737 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
738 if (!VRM->hasPhys(Intf->reg))
739 continue;
740 Matrix->unassign(*Intf);
741 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
742 VirtReg.isSpillable() < Intf->isSpillable()) &&
743 "Cannot decrease cascade number, illegal eviction");
744 ExtraRegInfo[Intf->reg].Cascade = Cascade;
745 ++NumEvicted;
Mark Laceyf9ea8852013-08-14 23:50:04 +0000746 NewVRegs.push_back(Intf->reg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000747 }
748}
749
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000750/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +0000751/// @param VirtReg Currently unassigned virtual register.
752/// @param Order Physregs to try.
753/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000754unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
755 AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000756 SmallVectorImpl<unsigned> &NewVRegs,
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000757 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000758 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
759
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000760 // Keep track of the cheapest interference seen so far.
Andrew Trick3621b8a2013-11-22 19:07:38 +0000761 EvictionCost BestCost;
762 BestCost.setMax();
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000763 unsigned BestPhys = 0;
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +0000764 unsigned OrderLimit = Order.getOrder().size();
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000765
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000766 // When we are just looking for a reduced cost per use, don't break any
767 // hints, and only evict smaller spill weights.
768 if (CostPerUseLimit < ~0u) {
769 BestCost.BrokenHints = 0;
770 BestCost.MaxWeight = VirtReg.weight;
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +0000771
772 // Check of any registers in RC are below CostPerUseLimit.
773 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
774 unsigned MinCost = RegClassInfo.getMinCost(RC);
775 if (MinCost >= CostPerUseLimit) {
776 DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
777 << ", no cheaper registers to be found.\n");
778 return 0;
779 }
780
781 // It is normal for register classes to have a long tail of registers with
782 // the same cost. We don't need to look at them if they're too expensive.
783 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
784 OrderLimit = RegClassInfo.getLastCostChange(RC);
785 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
786 }
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000787 }
788
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000789 Order.rewind();
Aditya Nandakumar73f3d332013-12-05 21:18:40 +0000790 while (unsigned PhysReg = Order.next(OrderLimit)) {
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000791 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
792 continue;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000793 // The first use of a callee-saved register in a function has cost 1.
794 // Don't start using a CSR when the CostPerUseLimit is low.
795 if (CostPerUseLimit == 1)
796 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
797 if (!MRI->isPhysRegUsed(CSR)) {
798 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
799 << PrintReg(CSR, TRI) << '\n');
800 continue;
801 }
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000802
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000803 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000804 continue;
805
806 // Best so far.
807 BestPhys = PhysReg;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000808
Jakob Stoklund Olesen9918b332011-02-25 01:04:22 +0000809 // Stop if the hint can be used.
Jakob Stoklund Olesen3cb2cb82012-12-04 22:25:16 +0000810 if (Order.isHint())
Jakob Stoklund Olesen9918b332011-02-25 01:04:22 +0000811 break;
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000812 }
813
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000814 if (!BestPhys)
815 return 0;
816
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000817 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000818 return BestPhys;
Andrew Trickccef0982010-12-09 18:15:21 +0000819}
820
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000821
822//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000823// Region Splitting
824//===----------------------------------------------------------------------===//
825
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000826/// addSplitConstraints - Fill out the SplitConstraints vector based on the
827/// interference pattern in Physreg and its aliases. Add the constraints to
828/// SpillPlacement and return the static cost of this split in Cost, assuming
829/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000830/// Return false if there are no bundles with positive bias.
831bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000832 BlockFrequency &Cost) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000833 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000834
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000835 // Reset interference dependent info.
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000836 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000837 BlockFrequency StaticCost = 0;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000838 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
839 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000840 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000841
Jakob Stoklund Olesenb1b76ad2011-02-09 22:50:26 +0000842 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000843 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000844 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
845 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
David Blaikie041f1aa2013-05-15 07:36:59 +0000846 BC.ChangesValue = BI.FirstDef.isValid();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000847
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000848 if (!Intf.hasInterference())
849 continue;
850
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000851 // Number of spill code instructions to insert.
852 unsigned Ins = 0;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000853
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000854 // Interference for the live-in value.
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000855 if (BI.LiveIn) {
Jakob Stoklund Olesen89339072011-04-04 15:32:15 +0000856 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000857 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +0000858 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000859 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +0000860 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000861 ++Ins;
Jakob Stoklund Olesenf248b202011-02-08 23:02:58 +0000862 }
863
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000864 // Interference for the live-out value.
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000865 if (BI.LiveOut) {
Jakob Stoklund Olesend93b0e32011-04-05 04:20:29 +0000866 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000867 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +0000868 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000869 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +0000870 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000871 ++Ins;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000872 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000873
874 // Accumulate the total frequency of inserted spill code.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000875 while (Ins--)
876 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000877 }
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000878 Cost = StaticCost;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000879
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000880 // Add constraints for use-blocks. Note that these are the only constraints
881 // that may add a positive bias, it is downhill from here.
882 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000883 return SpillPlacer->scanActiveBundles();
884}
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000885
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000886
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000887/// addThroughConstraints - Add constraints and links to SpillPlacer from the
888/// live-through blocks in Blocks.
889void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
890 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000891 const unsigned GroupSize = 8;
892 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000893 unsigned TBS[GroupSize];
894 unsigned B = 0, T = 0;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000895
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000896 for (unsigned i = 0; i != Blocks.size(); ++i) {
897 unsigned Number = Blocks[i];
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000898 Intf.moveToBlock(Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000899
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000900 if (!Intf.hasInterference()) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000901 assert(T < GroupSize && "Array overflow");
902 TBS[T] = Number;
903 if (++T == GroupSize) {
Frits van Bommel717d7ed2011-07-18 12:00:32 +0000904 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000905 T = 0;
906 }
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000907 continue;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000908 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000909
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000910 assert(B < GroupSize && "Array overflow");
911 BCS[B].Number = Number;
912
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000913 // Interference for the live-in value.
914 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
915 BCS[B].Entry = SpillPlacement::MustSpill;
916 else
917 BCS[B].Entry = SpillPlacement::PrefSpill;
918
919 // Interference for the live-out value.
920 if (Intf.last() >= SA->getLastSplitPoint(Number))
921 BCS[B].Exit = SpillPlacement::MustSpill;
922 else
923 BCS[B].Exit = SpillPlacement::PrefSpill;
924
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000925 if (++B == GroupSize) {
926 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
927 SpillPlacer->addConstraints(Array);
928 B = 0;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000929 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000930 }
931
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000932 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
933 SpillPlacer->addConstraints(Array);
Frits van Bommel717d7ed2011-07-18 12:00:32 +0000934 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000935}
936
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000937void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000938 // Keep track of through blocks that have not been added to SpillPlacer.
939 BitVector Todo = SA->getThroughBlocks();
940 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
941 unsigned AddedTo = 0;
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000942#ifndef NDEBUG
943 unsigned Visited = 0;
944#endif
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000945
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000946 for (;;) {
947 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000948 // Find new through blocks in the periphery of PrefRegBundles.
949 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
950 unsigned Bundle = NewBundles[i];
951 // Look at all blocks connected to Bundle in the full graph.
952 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
953 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
954 I != E; ++I) {
955 unsigned Block = *I;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000956 if (!Todo.test(Block))
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000957 continue;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000958 Todo.reset(Block);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000959 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000960 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000961#ifndef NDEBUG
962 ++Visited;
963#endif
964 }
965 }
966 // Any new blocks to add?
Jakob Stoklund Olesen91f3a302011-07-05 18:46:42 +0000967 if (ActiveBlocks.size() == AddedTo)
968 break;
Jakob Stoklund Olesena953bf12011-07-23 03:22:33 +0000969
970 // Compute through constraints from the interference, or assume that all
971 // through blocks prefer spilling when forming compact regions.
972 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
973 if (Cand.PhysReg)
974 addThroughConstraints(Cand.Intf, NewBlocks);
975 else
Jakob Stoklund Olesen86954522011-08-03 23:09:38 +0000976 // Provide a strong negative bias on through blocks to prevent unwanted
977 // liveness on loop backedges.
978 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen91f3a302011-07-05 18:46:42 +0000979 AddedTo = ActiveBlocks.size();
980
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000981 // Perhaps iterating can enable more bundles?
982 SpillPlacer->iterate();
983 }
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000984 DEBUG(dbgs() << ", v=" << Visited);
985}
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000986
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +0000987/// calcCompactRegion - Compute the set of edge bundles that should be live
988/// when splitting the current live range into compact regions. Compact
989/// regions can be computed without looking at interference. They are the
990/// regions formed by removing all the live-through blocks from the live range.
991///
992/// Returns false if the current live range is already compact, or if the
993/// compact regions would form single block regions anyway.
994bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
995 // Without any through blocks, the live range is already compact.
996 if (!SA->getNumThroughBlocks())
997 return false;
998
999 // Compact regions don't correspond to any physreg.
1000 Cand.reset(IntfCache, 0);
1001
1002 DEBUG(dbgs() << "Compact region bundles");
1003
1004 // Use the spill placer to determine the live bundles. GrowRegion pretends
1005 // that all the through blocks have interference when PhysReg is unset.
1006 SpillPlacer->prepare(Cand.LiveBundles);
1007
1008 // The static split cost will be zero since Cand.Intf reports no interference.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001009 BlockFrequency Cost;
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +00001010 if (!addSplitConstraints(Cand.Intf, Cost)) {
1011 DEBUG(dbgs() << ", none.\n");
1012 return false;
1013 }
1014
1015 growRegion(Cand);
1016 SpillPlacer->finish();
1017
1018 if (!Cand.LiveBundles.any()) {
1019 DEBUG(dbgs() << ", none.\n");
1020 return false;
1021 }
1022
1023 DEBUG({
1024 for (int i = Cand.LiveBundles.find_first(); i>=0;
1025 i = Cand.LiveBundles.find_next(i))
1026 dbgs() << " EB#" << i;
1027 dbgs() << ".\n";
1028 });
1029 return true;
1030}
1031
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001032/// calcSpillCost - Compute how expensive it would be to split the live range in
1033/// SA around all use blocks instead of forming bundle regions.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001034BlockFrequency RAGreedy::calcSpillCost() {
1035 BlockFrequency Cost = 0;
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001036 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1037 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1038 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1039 unsigned Number = BI.MBB->getNumber();
1040 // We normally only need one spill instruction - a load or a store.
1041 Cost += SpillPlacer->getBlockFrequency(Number);
1042
1043 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3c145052011-08-02 23:04:08 +00001044 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
1045 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001046 }
1047 return Cost;
1048}
1049
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001050/// calcGlobalSplitCost - Return the global split cost of following the split
1051/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001052/// interference pattern in SplitConstraints.
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001053///
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001054BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
1055 BlockFrequency GlobalCost = 0;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001056 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001057 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1058 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1059 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001060 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001061 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
1062 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
1063 unsigned Ins = 0;
1064
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001065 if (BI.LiveIn)
1066 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
1067 if (BI.LiveOut)
1068 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001069 while (Ins--)
1070 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001071 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001072
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001073 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1074 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001075 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
1076 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen8ce2f432011-04-06 21:32:41 +00001077 if (!RegIn && !RegOut)
1078 continue;
1079 if (RegIn && RegOut) {
1080 // We need double spill code if this block has interference.
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001081 Cand.Intf.moveToBlock(Number);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001082 if (Cand.Intf.hasInterference()) {
1083 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1084 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1085 }
Jakob Stoklund Olesen8ce2f432011-04-06 21:32:41 +00001086 continue;
1087 }
1088 // live-in / stack-out or stack-in live-out.
1089 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001090 }
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001091 return GlobalCost;
1092}
1093
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001094/// splitAroundRegion - Split the current live range around the regions
1095/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001096///
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001097/// Before calling this function, GlobalCand and BundleCand must be initialized
1098/// so each bundle is assigned to a valid candidate, or NoCand for the
1099/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1100/// objects must be initialized for the current live range, and intervals
1101/// created for the used candidates.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001102///
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001103/// @param LREdit The LiveRangeEdit object handling the current split.
1104/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1105/// must appear in this list.
1106void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1107 ArrayRef<unsigned> UsedCands) {
1108 // These are the intervals created for new global ranges. We may create more
1109 // intervals for local ranges.
1110 const unsigned NumGlobalIntvs = LREdit.size();
1111 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1112 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001113
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001114 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen22f37a12011-08-06 18:20:24 +00001115 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001116 // is all copies.
1117 unsigned Reg = SA->getParent().reg;
1118 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1119
Jakob Stoklund Olesenadc6a4c2011-06-30 01:30:39 +00001120 // First handle all the blocks with uses.
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001121 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1122 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1123 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001124 unsigned Number = BI.MBB->getNumber();
1125 unsigned IntvIn = 0, IntvOut = 0;
1126 SlotIndex IntfIn, IntfOut;
1127 if (BI.LiveIn) {
1128 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1129 if (CandIn != NoCand) {
1130 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1131 IntvIn = Cand.IntvIdx;
1132 Cand.Intf.moveToBlock(Number);
1133 IntfIn = Cand.Intf.first();
1134 }
1135 }
1136 if (BI.LiveOut) {
1137 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1138 if (CandOut != NoCand) {
1139 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1140 IntvOut = Cand.IntvIdx;
1141 Cand.Intf.moveToBlock(Number);
1142 IntfOut = Cand.Intf.last();
1143 }
1144 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001145
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001146 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001147 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001148 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001149 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesenadc6a4c2011-06-30 01:30:39 +00001150 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001151 continue;
1152 }
1153
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001154 if (IntvIn && IntvOut)
1155 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1156 else if (IntvIn)
1157 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesen795da1c2011-07-15 21:47:57 +00001158 else
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001159 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001160 }
1161
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001162 // Handle live-through blocks. The relevant live-through blocks are stored in
1163 // the ActiveBlocks list with each candidate. We need to filter out
1164 // duplicates.
1165 BitVector Todo = SA->getThroughBlocks();
1166 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1167 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1168 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1169 unsigned Number = Blocks[i];
1170 if (!Todo.test(Number))
1171 continue;
1172 Todo.reset(Number);
1173
1174 unsigned IntvIn = 0, IntvOut = 0;
1175 SlotIndex IntfIn, IntfOut;
1176
1177 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1178 if (CandIn != NoCand) {
1179 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1180 IntvIn = Cand.IntvIdx;
1181 Cand.Intf.moveToBlock(Number);
1182 IntfIn = Cand.Intf.first();
1183 }
1184
1185 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1186 if (CandOut != NoCand) {
1187 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1188 IntvOut = Cand.IntvIdx;
1189 Cand.Intf.moveToBlock(Number);
1190 IntfOut = Cand.Intf.last();
1191 }
1192 if (!IntvIn && !IntvOut)
1193 continue;
1194 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1195 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001196 }
1197
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +00001198 ++NumGlobalSplits;
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001199
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001200 SmallVector<unsigned, 8> IntvMap;
1201 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001202 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001203
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001204 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesen5cc91b22011-05-28 02:32:57 +00001205 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001206
1207 // Sort out the new intervals created by splitting. We get four kinds:
1208 // - Remainder intervals should not be split again.
1209 // - Candidate intervals can be assigned to Cand.PhysReg.
1210 // - Block-local splits are candidates for local splitting.
1211 // - DCE leftovers should go back on the queue.
1212 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001213 LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001214
1215 // Ignore old intervals from DCE.
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001216 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001217 continue;
1218
1219 // Remainder interval. Don't try splitting again, spill if it doesn't
1220 // allocate.
1221 if (IntvMap[i] == 0) {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001222 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001223 continue;
1224 }
1225
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001226 // Global intervals. Allow repeated splitting as long as the number of live
1227 // blocks is strictly decreasing.
1228 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001229 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Oleseneef23272011-04-26 22:33:12 +00001230 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1231 << " blocks as original.\n");
1232 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001233 setStage(Reg, RS_Split2);
Jakob Stoklund Oleseneef23272011-04-26 22:33:12 +00001234 }
1235 continue;
1236 }
1237
1238 // Other intervals are treated as new. This includes local intervals created
1239 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001240 }
1241
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +00001242 if (VerifyEnabled)
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001243 MF->verify(this, "After splitting live range around region");
1244}
1245
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001246unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001247 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001248 unsigned NumCands = 0;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001249 BlockFrequency BestCost;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001250
1251 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesen45df7e02011-09-12 16:54:42 +00001252 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001253 if (HasCompact) {
1254 // Yes, keep GlobalCand[0] as the compact region candidate.
1255 NumCands = 1;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001256 BestCost = BlockFrequency::getMaxFrequency();
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001257 } else {
1258 // No benefit from the compact region, our fallback will be per-block
1259 // splitting. Make sure we find a solution that is cheaper than spilling.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001260 BestCost = calcSpillCost();
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001261 DEBUG(dbgs() << "Cost of isolating all blocks = ";
1262 MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001263 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001264
Manman Ren9db66b32014-03-24 23:23:42 +00001265 unsigned BestCand =
Manman Ren78cf02a2014-03-25 00:16:25 +00001266 calculateRegionSplitCost(VirtReg, Order, BestCost, NumCands,
1267 false/*IgnoreCSR*/);
Manman Ren9db66b32014-03-24 23:23:42 +00001268
1269 // No solutions found, fall back to single block splitting.
1270 if (!HasCompact && BestCand == NoCand)
1271 return 0;
1272
1273 return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
1274}
1275
1276unsigned RAGreedy::calculateRegionSplitCost(LiveInterval &VirtReg,
1277 AllocationOrder &Order,
1278 BlockFrequency &BestCost,
Manman Ren78cf02a2014-03-25 00:16:25 +00001279 unsigned &NumCands,
1280 bool IgnoreCSR) {
Manman Ren9db66b32014-03-24 23:23:42 +00001281 unsigned BestCand = NoCand;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001282 Order.rewind();
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001283 while (unsigned PhysReg = Order.next()) {
Manman Ren78cf02a2014-03-25 00:16:25 +00001284 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
1285 if (IgnoreCSR && !MRI->isPhysRegUsed(CSR))
1286 continue;
1287
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001288 // Discard bad candidates before we run out of interference cache cursors.
1289 // This will only affect register classes with a lot of registers (>32).
1290 if (NumCands == IntfCache.getMaxCursors()) {
1291 unsigned WorstCount = ~0u;
1292 unsigned Worst = 0;
1293 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001294 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001295 continue;
1296 unsigned Count = GlobalCand[i].LiveBundles.count();
1297 if (Count < WorstCount)
1298 Worst = i, WorstCount = Count;
1299 }
1300 --NumCands;
1301 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen559d4dc2011-11-01 00:02:31 +00001302 if (BestCand == NumCands)
1303 BestCand = Worst;
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001304 }
1305
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001306 if (GlobalCand.size() <= NumCands)
1307 GlobalCand.resize(NumCands+1);
1308 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1309 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001310
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001311 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001312 BlockFrequency Cost;
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001313 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001314 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001315 continue;
1316 }
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001317 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = ";
1318 MBFI->printBlockFreq(dbgs(), Cost));
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001319 if (Cost >= BestCost) {
1320 DEBUG({
1321 if (BestCand == NoCand)
1322 dbgs() << " worse than no bundles\n";
1323 else
1324 dbgs() << " worse than "
1325 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1326 });
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001327 continue;
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001328 }
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001329 growRegion(Cand);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001330
Jakob Stoklund Olesen36b5d8a2011-04-06 19:13:57 +00001331 SpillPlacer->finish();
1332
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001333 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001334 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001335 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001336 continue;
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001337 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001338
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001339 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001340 DEBUG({
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001341 dbgs() << ", total = "; MBFI->printBlockFreq(dbgs(), Cost)
1342 << " with bundles";
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001343 for (int i = Cand.LiveBundles.find_first(); i>=0;
1344 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001345 dbgs() << " EB#" << i;
1346 dbgs() << ".\n";
1347 });
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001348 if (Cost < BestCost) {
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001349 BestCand = NumCands;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001350 BestCost = Cost;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001351 }
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001352 ++NumCands;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001353 }
Manman Ren9db66b32014-03-24 23:23:42 +00001354 return BestCand;
1355}
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001356
Manman Ren9db66b32014-03-24 23:23:42 +00001357unsigned RAGreedy::doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
1358 bool HasCompact,
1359 SmallVectorImpl<unsigned> &NewVRegs) {
1360 SmallVector<unsigned, 8> UsedCands;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001361 // Prepare split editor.
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +00001362 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +00001363 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001364
1365 // Assign all edge bundles to the preferred candidate, or NoCand.
1366 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1367
1368 // Assign bundles for the best candidate region.
1369 if (BestCand != NoCand) {
1370 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1371 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1372 UsedCands.push_back(BestCand);
1373 Cand.IntvIdx = SE->openIntv();
1374 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1375 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth77eb5a02011-08-03 23:07:27 +00001376 (void)B;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001377 }
1378 }
1379
1380 // Assign bundles for the compact region.
1381 if (HasCompact) {
1382 GlobalSplitCandidate &Cand = GlobalCand.front();
1383 assert(!Cand.PhysReg && "Compact region has no physreg");
1384 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1385 UsedCands.push_back(0);
1386 Cand.IntvIdx = SE->openIntv();
1387 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1388 << Cand.IntvIdx << ".\n");
Chandler Carruth77eb5a02011-08-03 23:07:27 +00001389 (void)B;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001390 }
1391 }
1392
1393 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001394 return 0;
1395}
1396
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001397
1398//===----------------------------------------------------------------------===//
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001399// Per-Block Splitting
1400//===----------------------------------------------------------------------===//
1401
1402/// tryBlockSplit - Split a global live range around every block with uses. This
1403/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1404/// they don't allocate.
1405unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001406 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001407 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1408 unsigned Reg = VirtReg.reg;
1409 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +00001410 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +00001411 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001412 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1413 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1414 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1415 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1416 SE->splitSingleBlock(BI);
1417 }
1418 // No blocks were split.
1419 if (LREdit.empty())
1420 return 0;
1421
1422 // We did split for some blocks.
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001423 SmallVector<unsigned, 8> IntvMap;
1424 SE->finish(&IntvMap);
Jakob Stoklund Olesen0de95ef2011-08-05 23:10:40 +00001425
1426 // Tell LiveDebugVariables about the new ranges.
Mark Laceyf9ea8852013-08-14 23:50:04 +00001427 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen0de95ef2011-08-05 23:10:40 +00001428
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001429 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1430
1431 // Sort out the new intervals created by splitting. The remainder interval
1432 // goes straight to spilling, the new local ranges get to stay RS_New.
1433 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001434 LiveInterval &LI = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001435 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1436 setStage(LI, RS_Spill);
1437 }
1438
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001439 if (VerifyEnabled)
1440 MF->verify(this, "After splitting live range around basic blocks");
1441 return 0;
1442}
1443
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001444
1445//===----------------------------------------------------------------------===//
1446// Per-Instruction Splitting
1447//===----------------------------------------------------------------------===//
1448
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001449/// Get the number of allocatable registers that match the constraints of \p Reg
1450/// on \p MI and that are also in \p SuperRC.
1451static unsigned getNumAllocatableRegsForConstraints(
1452 const MachineInstr *MI, unsigned Reg, const TargetRegisterClass *SuperRC,
1453 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1454 const RegisterClassInfo &RCI) {
1455 assert(SuperRC && "Invalid register class");
1456
1457 const TargetRegisterClass *ConstrainedRC =
1458 MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI,
1459 /* ExploreBundle */ true);
1460 if (!ConstrainedRC)
1461 return 0;
1462 return RCI.getNumAllocatableRegs(ConstrainedRC);
1463}
1464
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001465/// tryInstructionSplit - Split a live range around individual instructions.
1466/// This is normally not worthwhile since the spiller is doing essentially the
1467/// same thing. However, when the live range is in a constrained register
1468/// class, it may help to insert copies such that parts of the live range can
1469/// be moved to a larger register class.
1470///
1471/// This is similar to spilling to a larger register class.
1472unsigned
1473RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001474 SmallVectorImpl<unsigned> &NewVRegs) {
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001475 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001476 // There is no point to this if there are no larger sub-classes.
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001477 if (!RegClassInfo.isProperSubClass(CurRC))
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001478 return 0;
1479
1480 // Always enable split spill mode, since we're effectively spilling to a
1481 // register.
1482 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1483 SE->reset(LREdit, SplitEditor::SM_Size);
1484
1485 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1486 if (Uses.size() <= 1)
1487 return 0;
1488
1489 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1490
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001491 const TargetRegisterClass *SuperRC = TRI->getLargestLegalSuperClass(CurRC);
1492 unsigned SuperRCNumAllocatableRegs = RCI.getNumAllocatableRegs(SuperRC);
1493 // Split around every non-copy instruction if this split will relax
1494 // the constraints on the virtual register.
1495 // Otherwise, splitting just inserts uncoalescable copies that do not help
1496 // the allocation.
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001497 for (unsigned i = 0; i != Uses.size(); ++i) {
1498 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001499 if (MI->isFullCopy() ||
1500 SuperRCNumAllocatableRegs ==
1501 getNumAllocatableRegsForConstraints(MI, VirtReg.reg, SuperRC, TII,
1502 TRI, RCI)) {
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001503 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1504 continue;
1505 }
1506 SE->openIntv();
1507 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1508 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1509 SE->useIntv(SegStart, SegStop);
1510 }
1511
1512 if (LREdit.empty()) {
1513 DEBUG(dbgs() << "All uses were copies.\n");
1514 return 0;
1515 }
1516
1517 SmallVector<unsigned, 8> IntvMap;
1518 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001519 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001520 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1521
1522 // Assign all new registers to RS_Spill. This was the last chance.
1523 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1524 return 0;
1525}
1526
1527
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001528//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001529// Local Splitting
1530//===----------------------------------------------------------------------===//
1531
1532
1533/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1534/// in order to use PhysReg between two entries in SA->UseSlots.
1535///
1536/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1537///
1538void RAGreedy::calcGapWeights(unsigned PhysReg,
1539 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001540 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1541 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00001542 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001543 const unsigned NumGaps = Uses.size()-1;
1544
1545 // Start and end points for the interference check.
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00001546 SlotIndex StartIdx =
1547 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1548 SlotIndex StopIdx =
1549 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001550
1551 GapWeight.assign(NumGaps, 0.0f);
1552
1553 // Add interference from each overlapping register.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001554 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1555 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1556 .checkInterference())
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001557 continue;
1558
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00001559 // We know that VirtReg is a continuous interval from FirstInstr to
1560 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001561 //
1562 // Interference that overlaps an instruction is counted in both gaps
1563 // surrounding the instruction. The exception is interference before
1564 // StartIdx and after StopIdx.
1565 //
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001566 LiveIntervalUnion::SegmentIter IntI =
1567 Matrix->getLiveUnions()[*Units] .find(StartIdx);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001568 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1569 // Skip the gaps before IntI.
1570 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1571 if (++Gap == NumGaps)
1572 break;
1573 if (Gap == NumGaps)
1574 break;
1575
1576 // Update the gaps covered by IntI.
1577 const float weight = IntI.value()->weight;
1578 for (; Gap != NumGaps; ++Gap) {
1579 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1580 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1581 break;
1582 }
1583 if (Gap == NumGaps)
1584 break;
1585 }
1586 }
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001587
1588 // Add fixed interference.
1589 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
Matthias Braun34e1be92013-10-10 21:29:02 +00001590 const LiveRange &LR = LIS->getRegUnit(*Units);
1591 LiveRange::const_iterator I = LR.find(StartIdx);
1592 LiveRange::const_iterator E = LR.end();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001593
1594 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1595 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1596 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1597 if (++Gap == NumGaps)
1598 break;
1599 if (Gap == NumGaps)
1600 break;
1601
1602 for (; Gap != NumGaps; ++Gap) {
Aaron Ballman04999042013-11-13 00:15:44 +00001603 GapWeight[Gap] = llvm::huge_valf;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001604 if (Uses[Gap+1].getBaseIndex() >= I->end)
1605 break;
1606 }
1607 if (Gap == NumGaps)
1608 break;
1609 }
1610 }
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001611}
1612
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001613/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1614/// basic block.
1615///
1616unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001617 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001618 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1619 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001620
1621 // Note that it is possible to have an interval that is live-in or live-out
1622 // while only covering a single block - A phi-def can use undef values from
1623 // predecessors, and the block could be a single-block loop.
1624 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00001625 // that the interval is continuous from FirstInstr to LastInstr. We should
1626 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001627
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00001628 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001629 if (Uses.size() <= 2)
1630 return 0;
1631 const unsigned NumGaps = Uses.size()-1;
1632
1633 DEBUG({
1634 dbgs() << "tryLocalSplit: ";
1635 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00001636 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001637 dbgs() << '\n';
1638 });
1639
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001640 // If VirtReg is live across any register mask operands, compute a list of
1641 // gaps with register masks.
1642 SmallVector<unsigned, 8> RegMaskGaps;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001643 if (Matrix->checkRegMaskInterference(VirtReg)) {
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001644 // Get regmask slots for the whole block.
1645 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001646 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001647 // Constrain to VirtReg's live range.
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001648 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1649 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001650 unsigned re = RMS.size();
1651 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001652 // Look for Uses[i] <= RMS <= Uses[i+1].
1653 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1654 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001655 continue;
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001656 // Skip a regmask on the same instruction as the last use. It doesn't
1657 // overlap the live range.
1658 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1659 break;
1660 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001661 RegMaskGaps.push_back(i);
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001662 // Advance ri to the next gap. A regmask on one of the uses counts in
1663 // both gaps.
1664 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1665 ++ri;
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001666 }
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001667 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001668 }
1669
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001670 // Since we allow local split results to be split again, there is a risk of
1671 // creating infinite loops. It is tempting to require that the new live
1672 // ranges have less instructions than the original. That would guarantee
1673 // convergence, but it is too strict. A live range with 3 instructions can be
1674 // split 2+3 (including the COPY), and we want to allow that.
1675 //
1676 // Instead we use these rules:
1677 //
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001678 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001679 // noop split, of course).
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001680 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001681 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001682 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001683 // smaller ranges are marked RS_New.
1684 //
1685 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1686 // excessive splitting and infinite loops.
1687 //
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001688 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001689
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001690 // Best split candidate.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001691 unsigned BestBefore = NumGaps;
1692 unsigned BestAfter = 0;
1693 float BestDiff = 0;
1694
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001695 const float blockFreq =
1696 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
Michael Gottesman5e985ee2013-12-14 02:37:38 +00001697 (1.0f / MBFI->getEntryFreq());
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001698 SmallVector<float, 8> GapWeight;
1699
1700 Order.rewind();
1701 while (unsigned PhysReg = Order.next()) {
1702 // Keep track of the largest spill weight that would need to be evicted in
1703 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1704 calcGapWeights(PhysReg, GapWeight);
1705
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001706 // Remove any gaps with regmask clobbers.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001707 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001708 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
Aaron Ballman04999042013-11-13 00:15:44 +00001709 GapWeight[RegMaskGaps[i]] = llvm::huge_valf;
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001710
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001711 // Try to find the best sequence of gaps to close.
1712 // The new spill weight must be larger than any gap interference.
1713
1714 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001715 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001716
1717 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1718 // It is the spill weight that needs to be evicted.
1719 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001720
1721 for (;;) {
1722 // Live before/after split?
1723 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1724 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1725
1726 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1727 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1728 << " i=" << MaxGap);
1729
1730 // Stop before the interval gets so big we wouldn't be making progress.
1731 if (!LiveBefore && !LiveAfter) {
1732 DEBUG(dbgs() << " all\n");
1733 break;
1734 }
1735 // Should the interval be extended or shrunk?
1736 bool Shrink = true;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001737
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001738 // How many gaps would the new range have?
1739 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1740
1741 // Legally, without causing looping?
1742 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1743
Aaron Ballman04999042013-11-13 00:15:44 +00001744 if (Legal && MaxGap < llvm::huge_valf) {
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001745 // Estimate the new spill weight. Each instruction reads or writes the
1746 // register. Conservatively assume there are no read-modify-write
1747 // instructions.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001748 //
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001749 // Try to guess the size of the new interval.
1750 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1751 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1752 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001753 // Would this split be possible to allocate?
1754 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00001755 DEBUG(dbgs() << " w=" << EstWeight);
1756 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001757 Shrink = false;
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00001758 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001759 if (Diff > BestDiff) {
1760 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00001761 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001762 BestBefore = SplitBefore;
1763 BestAfter = SplitAfter;
1764 }
1765 }
1766 }
1767
1768 // Try to shrink.
1769 if (Shrink) {
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001770 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001771 DEBUG(dbgs() << " shrink\n");
1772 // Recompute the max when necessary.
1773 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1774 MaxGap = GapWeight[SplitBefore];
1775 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1776 MaxGap = std::max(MaxGap, GapWeight[i]);
1777 }
1778 continue;
1779 }
1780 MaxGap = 0;
1781 }
1782
1783 // Try to extend the interval.
1784 if (SplitAfter >= NumGaps) {
1785 DEBUG(dbgs() << " end\n");
1786 break;
1787 }
1788
1789 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001790 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001791 }
1792 }
1793
1794 // Didn't find any candidates?
1795 if (BestBefore == NumGaps)
1796 return 0;
1797
1798 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1799 << '-' << Uses[BestAfter] << ", " << BestDiff
1800 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1801
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +00001802 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesenc9601982011-03-03 01:29:13 +00001803 SE->reset(LREdit);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001804
Jakob Stoklund Olesenc9601982011-03-03 01:29:13 +00001805 SE->openIntv();
1806 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1807 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1808 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001809 SmallVector<unsigned, 8> IntvMap;
1810 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001811 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001812
1813 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001814 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001815 // leave the new intervals as RS_New so they can compete.
1816 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1817 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1818 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1819 if (NewGaps >= NumGaps) {
1820 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1821 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001822 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1823 if (IntvMap[i] == 1) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001824 setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
1825 DEBUG(dbgs() << PrintReg(LREdit.get(i)));
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001826 }
1827 DEBUG(dbgs() << '\n');
1828 }
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +00001829 ++NumLocalSplits;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001830
1831 return 0;
1832}
1833
1834//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001835// Live Range Splitting
1836//===----------------------------------------------------------------------===//
1837
1838/// trySplit - Try to split VirtReg or one of its interferences, making it
1839/// assignable.
1840/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1841unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001842 SmallVectorImpl<unsigned>&NewVRegs) {
Jakob Stoklund Olesend4bb1d42011-08-05 23:50:33 +00001843 // Ranges must be Split2 or less.
1844 if (getStage(VirtReg) >= RS_Spill)
1845 return 0;
1846
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001847 // Local intervals are handled separately.
Jakob Stoklund Olesen609bc442011-02-19 00:38:40 +00001848 if (LIS->intervalIsInOneMBB(VirtReg)) {
1849 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00001850 SA->analyze(&VirtReg);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001851 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1852 if (PhysReg || !NewVRegs.empty())
1853 return PhysReg;
1854 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen609bc442011-02-19 00:38:40 +00001855 }
1856
1857 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001858
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00001859 SA->analyze(&VirtReg);
1860
Jakob Stoklund Oleseneaa6ed12011-05-03 20:42:13 +00001861 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1862 // coalescer. That may cause the range to become allocatable which means that
1863 // tryRegionSplit won't be making progress. This check should be replaced with
1864 // an assertion when the coalescer is fixed.
1865 if (SA->didRepairRange()) {
1866 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001867 Matrix->invalidateVirtRegs();
Jakob Stoklund Oleseneaa6ed12011-05-03 20:42:13 +00001868 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1869 return PhysReg;
1870 }
1871
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001872 // First try to split around a region spanning multiple blocks. RS_Split2
1873 // ranges already made dubious progress with region splitting, so they go
1874 // straight to single block splitting.
1875 if (getStage(VirtReg) < RS_Split2) {
1876 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1877 if (PhysReg || !NewVRegs.empty())
1878 return PhysReg;
1879 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001880
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001881 // Then isolate blocks.
1882 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001883}
1884
Quentin Colombet87769712014-02-05 22:13:59 +00001885//===----------------------------------------------------------------------===//
1886// Last Chance Recoloring
1887//===----------------------------------------------------------------------===//
1888
1889/// mayRecolorAllInterferences - Check if the virtual registers that
1890/// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be
1891/// recolored to free \p PhysReg.
1892/// When true is returned, \p RecoloringCandidates has been augmented with all
1893/// the live intervals that need to be recolored in order to free \p PhysReg
1894/// for \p VirtReg.
1895/// \p FixedRegisters contains all the virtual registers that cannot be
1896/// recolored.
1897bool
1898RAGreedy::mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
1899 SmallLISet &RecoloringCandidates,
1900 const SmallVirtRegSet &FixedRegisters) {
1901 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
1902
1903 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1904 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
1905 // If there is LastChanceRecoloringMaxInterference or more interferences,
1906 // chances are one would not be recolorable.
1907 if (Q.collectInterferingVRegs(LastChanceRecoloringMaxInterference) >=
1908 LastChanceRecoloringMaxInterference) {
1909 DEBUG(dbgs() << "Early abort: too many interferences.\n");
1910 return false;
1911 }
1912 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
1913 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
1914 // If Intf is done and sit on the same register class as VirtReg,
1915 // it would not be recolorable as it is in the same state as VirtReg.
1916 if ((getStage(*Intf) == RS_Done &&
1917 MRI->getRegClass(Intf->reg) == CurRC) ||
1918 FixedRegisters.count(Intf->reg)) {
1919 DEBUG(dbgs() << "Early abort: the inteference is not recolorable.\n");
1920 return false;
1921 }
1922 RecoloringCandidates.insert(Intf);
1923 }
1924 }
1925 return true;
1926}
1927
1928/// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
1929/// its interferences.
1930/// Last chance recoloring chooses a color for \p VirtReg and recolors every
1931/// virtual register that was using it. The recoloring process may recursively
1932/// use the last chance recoloring. Therefore, when a virtual register has been
1933/// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
1934/// be last-chance-recolored again during this recoloring "session".
1935/// E.g.,
1936/// Let
1937/// vA can use {R1, R2 }
1938/// vB can use { R2, R3}
1939/// vC can use {R1 }
1940/// Where vA, vB, and vC cannot be split anymore (they are reloads for
1941/// instance) and they all interfere.
1942///
1943/// vA is assigned R1
1944/// vB is assigned R2
1945/// vC tries to evict vA but vA is already done.
1946/// Regular register allocation fails.
1947///
1948/// Last chance recoloring kicks in:
1949/// vC does as if vA was evicted => vC uses R1.
1950/// vC is marked as fixed.
1951/// vA needs to find a color.
1952/// None are available.
1953/// vA cannot evict vC: vC is a fixed virtual register now.
1954/// vA does as if vB was evicted => vA uses R2.
1955/// vB needs to find a color.
1956/// R3 is available.
1957/// Recoloring => vC = R1, vA = R2, vB = R3
1958///
Alp Toker70b36992014-02-25 04:21:15 +00001959/// \p Order defines the preferred allocation order for \p VirtReg.
Quentin Colombet87769712014-02-05 22:13:59 +00001960/// \p NewRegs will contain any new virtual register that have been created
1961/// (split, spill) during the process and that must be assigned.
1962/// \p FixedRegisters contains all the virtual registers that cannot be
1963/// recolored.
1964/// \p Depth gives the current depth of the last chance recoloring.
1965/// \return a physical register that can be used for VirtReg or ~0u if none
1966/// exists.
1967unsigned RAGreedy::tryLastChanceRecoloring(LiveInterval &VirtReg,
1968 AllocationOrder &Order,
1969 SmallVectorImpl<unsigned> &NewVRegs,
1970 SmallVirtRegSet &FixedRegisters,
1971 unsigned Depth) {
1972 DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
1973 // Ranges must be Done.
Quentin Colombet0e3b5e02014-02-13 05:17:37 +00001974 assert((getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
Quentin Colombet87769712014-02-05 22:13:59 +00001975 "Last chance recoloring should really be last chance");
1976 // Set the max depth to LastChanceRecoloringMaxDepth.
1977 // We may want to reconsider that if we end up with a too large search space
1978 // for target with hundreds of registers.
1979 // Indeed, in that case we may want to cut the search space earlier.
1980 if (Depth >= LastChanceRecoloringMaxDepth) {
1981 DEBUG(dbgs() << "Abort because max depth has been reached.\n");
1982 return ~0u;
1983 }
1984
1985 // Set of Live intervals that will need to be recolored.
1986 SmallLISet RecoloringCandidates;
1987 // Record the original mapping virtual register to physical register in case
1988 // the recoloring fails.
1989 DenseMap<unsigned, unsigned> VirtRegToPhysReg;
1990 // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in
1991 // this recoloring "session".
1992 FixedRegisters.insert(VirtReg.reg);
1993
1994 Order.rewind();
1995 while (unsigned PhysReg = Order.next()) {
1996 DEBUG(dbgs() << "Try to assign: " << VirtReg << " to "
1997 << PrintReg(PhysReg, TRI) << '\n');
1998 RecoloringCandidates.clear();
1999 VirtRegToPhysReg.clear();
2000
2001 // It is only possible to recolor virtual register interference.
2002 if (Matrix->checkInterference(VirtReg, PhysReg) >
2003 LiveRegMatrix::IK_VirtReg) {
2004 DEBUG(dbgs() << "Some inteferences are not with virtual registers.\n");
2005
2006 continue;
2007 }
2008
2009 // Early give up on this PhysReg if it is obvious we cannot recolor all
2010 // the interferences.
2011 if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
2012 FixedRegisters)) {
2013 DEBUG(dbgs() << "Some inteferences cannot be recolored.\n");
2014 continue;
2015 }
2016
2017 // RecoloringCandidates contains all the virtual registers that interfer
2018 // with VirtReg on PhysReg (or one of its aliases).
2019 // Enqueue them for recoloring and perform the actual recoloring.
2020 PQueue RecoloringQueue;
2021 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2022 EndIt = RecoloringCandidates.end();
2023 It != EndIt; ++It) {
2024 unsigned ItVirtReg = (*It)->reg;
2025 enqueue(RecoloringQueue, *It);
2026 assert(VRM->hasPhys(ItVirtReg) &&
2027 "Interferences are supposed to be with allocated vairables");
2028
2029 // Record the current allocation.
2030 VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg);
2031 // unset the related struct.
2032 Matrix->unassign(**It);
2033 }
2034
2035 // Do as if VirtReg was assigned to PhysReg so that the underlying
2036 // recoloring has the right information about the interferes and
2037 // available colors.
2038 Matrix->assign(VirtReg, PhysReg);
2039
2040 // Save the current recoloring state.
2041 // If we cannot recolor all the interferences, we will have to start again
2042 // at this point for the next physical register.
2043 SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
2044 if (tryRecoloringCandidates(RecoloringQueue, NewVRegs, FixedRegisters,
2045 Depth)) {
2046 // Do not mess up with the global assignment process.
2047 // I.e., VirtReg must be unassigned.
2048 Matrix->unassign(VirtReg);
2049 return PhysReg;
2050 }
2051
2052 DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to "
2053 << PrintReg(PhysReg, TRI) << '\n');
2054
2055 // The recoloring attempt failed, undo the changes.
2056 FixedRegisters = SaveFixedRegisters;
2057 Matrix->unassign(VirtReg);
2058
2059 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2060 EndIt = RecoloringCandidates.end();
2061 It != EndIt; ++It) {
2062 unsigned ItVirtReg = (*It)->reg;
2063 if (VRM->hasPhys(ItVirtReg))
2064 Matrix->unassign(**It);
2065 Matrix->assign(**It, VirtRegToPhysReg[ItVirtReg]);
2066 }
2067 }
2068
2069 // Last chance recoloring did not worked either, give up.
2070 return ~0u;
2071}
2072
2073/// tryRecoloringCandidates - Try to assign a new color to every register
2074/// in \RecoloringQueue.
2075/// \p NewRegs will contain any new virtual register created during the
2076/// recoloring process.
2077/// \p FixedRegisters[in/out] contains all the registers that have been
2078/// recolored.
2079/// \return true if all virtual registers in RecoloringQueue were successfully
2080/// recolored, false otherwise.
2081bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
2082 SmallVectorImpl<unsigned> &NewVRegs,
2083 SmallVirtRegSet &FixedRegisters,
2084 unsigned Depth) {
2085 while (!RecoloringQueue.empty()) {
2086 LiveInterval *LI = dequeue(RecoloringQueue);
2087 DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
2088 unsigned PhysReg;
2089 PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters, Depth + 1);
2090 if (PhysReg == ~0u || !PhysReg)
2091 return false;
2092 DEBUG(dbgs() << "Recoloring of " << *LI
2093 << " succeeded with: " << PrintReg(PhysReg, TRI) << '\n');
2094 Matrix->assign(*LI, PhysReg);
2095 FixedRegisters.insert(LI->reg);
2096 }
2097 return true;
2098}
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002099
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00002100//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00002101// Main Entry Point
2102//===----------------------------------------------------------------------===//
2103
2104unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Mark Laceyf9ea8852013-08-14 23:50:04 +00002105 SmallVectorImpl<unsigned> &NewVRegs) {
Quentin Colombet87769712014-02-05 22:13:59 +00002106 SmallVirtRegSet FixedRegisters;
2107 return selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters);
2108}
2109
2110unsigned RAGreedy::selectOrSplitImpl(LiveInterval &VirtReg,
2111 SmallVectorImpl<unsigned> &NewVRegs,
2112 SmallVirtRegSet &FixedRegisters,
2113 unsigned Depth) {
Manman Ren78cf02a2014-03-25 00:16:25 +00002114 unsigned CostPerUseLimit = ~0u;
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00002115 // First try assigning a free register.
Jakob Stoklund Olesenb8bf3c02011-06-03 20:34:53 +00002116 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Manman Ren78cf02a2014-03-25 00:16:25 +00002117 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs)) {
2118 // We check other options if we are using a CSR for the first time.
2119 bool CSRFirstUse = false;
2120 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
2121 if (!MRI->isPhysRegUsed(CSR))
2122 CSRFirstUse = true;
2123
2124 BlockFrequency CSRCost(CSRFirstTimeCost);
Manman Ren14aa8912014-03-26 22:14:09 +00002125 // Using a CSR for the first time has a cost because it causes push|pop
2126 // to be added to prologue|epilogue. Splitting a cold section of the live
2127 // range can have lower cost than using the CSR for the first time;
2128 // Spilling a live range in the cold path can have lower cost than using
2129 // the CSR for the first time.
Manman Ren78cf02a2014-03-25 00:16:25 +00002130 if (getStage(VirtReg) == RS_Spill && CSRFirstUse && NewVRegs.empty() &&
2131 CSRFirstTimeCost > 0 && VirtReg.isSpillable()) {
2132 // We choose spill over using the CSR for the first time if the spill cost
2133 // is lower than CSRCost.
2134 SA->analyze(&VirtReg);
2135 if (calcSpillCost() >= CSRCost)
2136 return PhysReg;
2137
2138 // We are going to spill, set CostPerUseLimit to 1 to make sure that
2139 // we will not use a callee-saved register in tryEvict.
2140 CostPerUseLimit = 1;
2141 }
2142 else if (getStage(VirtReg) < RS_Split && CSRFirstUse &&
2143 NewVRegs.empty() && CSRFirstTimeCost > 0) {
2144 // We choose pre-splitting over using the CSR for the first time if
2145 // the cost of splitting is lower than CSRCost.
2146 SA->analyze(&VirtReg);
2147 unsigned NumCands = 0;
2148 unsigned BestCand =
2149 calculateRegionSplitCost(VirtReg, Order, CSRCost, NumCands,
2150 true/*IgnoreCSR*/);
2151 if (BestCand == NoCand)
2152 // Use the CSR if we can't find a region split below CSRCost.
2153 return PhysReg;
2154
2155 // Perform the actual pre-splitting.
2156 doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs);
2157 if (!NewVRegs.empty())
2158 return 0;
2159 } else
2160 return PhysReg;
2161 }
Andrew Trickccef0982010-12-09 18:15:21 +00002162
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +00002163 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00002164 DEBUG(dbgs() << StageName[Stage]
2165 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +00002166
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00002167 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002168 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00002169 // get a second chance until they have been split.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002170 if (Stage != RS_Split)
Manman Ren78cf02a2014-03-25 00:16:25 +00002171 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit))
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00002172 return PhysReg;
Andrew Trickccef0982010-12-09 18:15:21 +00002173
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002174 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
2175
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +00002176 // The first time we see a live range, don't try to split or spill.
2177 // Wait until the second time, when all smaller ranges have been allocated.
2178 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002179 if (Stage < RS_Split) {
2180 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesen86985072011-03-19 23:02:47 +00002181 DEBUG(dbgs() << "wait for second round\n");
Mark Laceyf9ea8852013-08-14 23:50:04 +00002182 NewVRegs.push_back(VirtReg.reg);
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +00002183 return 0;
2184 }
2185
Jakob Stoklund Olesena5c88992011-05-06 21:58:30 +00002186 // If we couldn't allocate a register from spilling, there is probably some
2187 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002188 if (Stage >= RS_Done || !VirtReg.isSpillable())
Quentin Colombet87769712014-02-05 22:13:59 +00002189 return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
2190 Depth);
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00002191
Jakob Stoklund Olesen903b6d32010-12-14 00:37:49 +00002192 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002193 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
2194 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +00002195 return PhysReg;
2196
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00002197 // Finally spill VirtReg itself.
Jakob Stoklund Olesen92da7052010-12-11 00:19:56 +00002198 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +00002199 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen4d6eafa2011-03-10 01:51:42 +00002200 spiller().spill(LRE);
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002201 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002202
Jakob Stoklund Olesen557a82c2011-03-16 22:56:08 +00002203 if (VerifyEnabled)
2204 MF->verify(this, "After spilling");
2205
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002206 // The live virtual register requesting allocation was spilled, so tell
2207 // the caller not to allocate anything during this round.
2208 return 0;
2209}
2210
2211bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
2212 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
David Blaikiec8c29202012-08-22 17:18:53 +00002213 << "********** Function: " << mf.getName() << '\n');
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002214
2215 MF = &mf;
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00002216 TRI = MF->getTarget().getRegisterInfo();
2217 TII = MF->getTarget().getInstrInfo();
2218 RCI.runOnMachineFunction(mf);
Jakob Stoklund Olesen2e98ee32010-12-17 23:16:35 +00002219 if (VerifyEnabled)
Jakob Stoklund Olesenbf4550e2010-12-18 00:06:56 +00002220 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesen2e98ee32010-12-17 23:16:35 +00002221
Jakob Stoklund Olesen2d2dec92012-06-20 22:52:29 +00002222 RegAllocBase::init(getAnalysis<VirtRegMap>(),
2223 getAnalysis<LiveIntervals>(),
2224 getAnalysis<LiveRegMatrix>());
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00002225 Indexes = &getAnalysis<SlotIndexes>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +00002226 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +00002227 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenadecb5e2010-12-10 22:54:44 +00002228 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +00002229 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00002230 Bundles = &getAnalysis<EdgeBundles>();
2231 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00002232 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00002233
Arnaud A. de Grandmaisonea3ac162013-11-11 19:04:45 +00002234 calculateSpillWeightsAndHints(*LIS, mf, *Loops, *MBFI);
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +00002235
Andrew Trick97064962013-07-25 07:26:26 +00002236 DEBUG(LIS->dump());
2237
Jakob Stoklund Olesenf1a60a62011-02-19 00:53:42 +00002238 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Benjamin Kramere2a1d892013-06-17 19:00:36 +00002239 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00002240 ExtraRegInfo.clear();
2241 ExtraRegInfo.resize(MRI->getNumVirtRegs());
2242 NextCascade = 1;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002243 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00002244 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +00002245
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002246 allocatePhysRegs();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002247 releaseMemory();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002248 return true;
2249}