blob: aa7c1785035bff3206905e4e33e4cd4921fb6d98 [file] [log] [blame]
Jakob Stoklund Olesencba2e062010-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
Chandler Carruthd04a8d42012-12-03 16:50:05 +000015#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +000016#include "AllocationOrder.h"
Jakob Stoklund Olesen5907d862011-04-02 06:03:35 +000017#include "InterferenceCache.h"
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +000018#include "LiveDebugVariables.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000019#include "RegAllocBase.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000020#include "SpillPlacement.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000021#include "Spiller.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000022#include "SplitKit.h"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000023#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000024#include "llvm/Analysis/AliasAnalysis.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000025#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000026#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000027#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper789d5d82012-04-02 22:44:18 +000028#include "llvm/CodeGen/LiveRangeEdit.h"
Jakob Stoklund Olesen1ead68d2012-11-28 19:13:06 +000029#include "llvm/CodeGen/LiveRegMatrix.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000030#include "llvm/CodeGen/LiveStackAnalysis.h"
Benjamin Kramer4eed7562013-06-17 19:00:36 +000031#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000032#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000033#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000034#include "llvm/CodeGen/MachineLoopInfo.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000036#include "llvm/CodeGen/RegAllocRegistry.h"
Stephen Hines36b56882014-04-23 16:57:46 -070037#include "llvm/CodeGen/RegisterClassInfo.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000038#include "llvm/CodeGen/VirtRegMap.h"
Stephen Hinesdce4a402014-05-29 02:49:00 -070039#include "llvm/IR/LLVMContext.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000040#include "llvm/PassAnalysisSupport.h"
Stephen Hinesdce4a402014-05-29 02:49:00 -070041#include "llvm/Support/BranchProbability.h"
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +000042#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000043#include "llvm/Support/Debug.h"
44#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000045#include "llvm/Support/Timer.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000046#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000047#include <queue>
48
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000049using namespace llvm;
50
Stephen Hinesdce4a402014-05-29 02:49:00 -070051#define DEBUG_TYPE "regalloc"
52
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000053STATISTIC(NumGlobalSplits, "Number of split global live ranges");
54STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000055STATISTIC(NumEvicted, "Number of interferences evicted");
56
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +000057static cl::opt<SplitEditor::ComplementSpillMode>
58SplitSpillMode("split-spill-mode", cl::Hidden,
59 cl::desc("Spill mode for splitting live ranges"),
60 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
61 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
62 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
63 clEnumValEnd),
64 cl::init(SplitEditor::SM_Partition));
65
Stephen Hines36b56882014-04-23 16:57:46 -070066static cl::opt<unsigned>
67LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden,
68 cl::desc("Last chance recoloring max depth"),
69 cl::init(5));
70
71static cl::opt<unsigned> LastChanceRecoloringMaxInterference(
72 "lcr-max-interf", cl::Hidden,
73 cl::desc("Last chance recoloring maximum number of considered"
74 " interference at a time"),
75 cl::init(8));
76
Stephen Hinesdce4a402014-05-29 02:49:00 -070077static cl::opt<bool>
78ExhaustiveSearch("exhaustive-register-search", cl::NotHidden,
79 cl::desc("Exhaustive Search for registers bypassing the depth "
80 "and interference cutoffs of last chance recoloring"));
81
Stephen Hines36b56882014-04-23 16:57:46 -070082// FIXME: Find a good default for this flag and remove the flag.
83static cl::opt<unsigned>
84CSRFirstTimeCost("regalloc-csr-first-time-cost",
85 cl::desc("Cost for first time use of callee-saved register."),
86 cl::init(0), cl::Hidden);
87
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000088static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
89 createGreedyRegisterAllocator);
90
91namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000092class RAGreedy : public MachineFunctionPass,
93 public RegAllocBase,
94 private LiveRangeEdit::Delegate {
Stephen Hines36b56882014-04-23 16:57:46 -070095 // Convenient shortcuts.
96 typedef std::priority_queue<std::pair<unsigned, unsigned> > PQueue;
97 typedef SmallPtrSet<LiveInterval *, 4> SmallLISet;
98 typedef SmallSet<unsigned, 16> SmallVirtRegSet;
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000099
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000100 // context
101 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000102
Stephen Hines36b56882014-04-23 16:57:46 -0700103 // Shortcuts to some useful interface.
104 const TargetInstrInfo *TII;
105 const TargetRegisterInfo *TRI;
106 RegisterClassInfo RCI;
107
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000108 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000109 SlotIndexes *Indexes;
Benjamin Kramer4eed7562013-06-17 19:00:36 +0000110 MachineBlockFrequencyInfo *MBFI;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000111 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000112 MachineLoopInfo *Loops;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000113 EdgeBundles *Bundles;
114 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000115 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000116
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000117 // state
Stephen Hines36b56882014-04-23 16:57:46 -0700118 std::unique_ptr<Spiller> SpillerInstance;
119 PQueue Queue;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000120 unsigned NextCascade;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000121
122 // Live ranges pass through a number of stages as we try to allocate them.
123 // Some of the stages may also create new live ranges:
124 //
125 // - Region splitting.
126 // - Per-block splitting.
127 // - Local splitting.
128 // - Spilling.
129 //
130 // Ranges produced by one of the stages skip the previous stages when they are
131 // dequeued. This improves performance because we can skip interference checks
132 // that are unlikely to give any results. It also guarantees that the live
133 // range splitting algorithm terminates, something that is otherwise hard to
134 // ensure.
135 enum LiveRangeStage {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000136 /// Newly created live range that has never been queued.
137 RS_New,
138
139 /// Only attempt assignment and eviction. Then requeue as RS_Split.
140 RS_Assign,
141
142 /// Attempt live range splitting if assignment is impossible.
143 RS_Split,
144
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000145 /// Attempt more aggressive live range splitting that is guaranteed to make
146 /// progress. This is used for split products that may not be making
147 /// progress.
148 RS_Split2,
149
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000150 /// Live range will be spilled. No more splitting will be attempted.
151 RS_Spill,
152
153 /// There is nothing more we can do to this live range. Abort compilation
154 /// if it can't be assigned.
155 RS_Done
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000156 };
157
Stephen Hinesdce4a402014-05-29 02:49:00 -0700158 // Enum CutOffStage to keep a track whether the register allocation failed
159 // because of the cutoffs encountered in last chance recoloring.
160 // Note: This is used as bitmask. New value should be next power of 2.
161 enum CutOffStage {
162 // No cutoffs encountered
163 CO_None = 0,
164
165 // lcr-max-depth cutoff encountered
166 CO_Depth = 1,
167
168 // lcr-max-interf cutoff encountered
169 CO_Interf = 2
170 };
171
172 uint8_t CutOffInfo;
173
Eli Friedmanae43dac2013-09-10 23:18:14 +0000174#ifndef NDEBUG
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000175 static const char *const StageName[];
Eli Friedmanae43dac2013-09-10 23:18:14 +0000176#endif
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000177
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000178 // RegInfo - Keep additional information about each live range.
179 struct RegInfo {
180 LiveRangeStage Stage;
181
182 // Cascade - Eviction loop prevention. See canEvictInterference().
183 unsigned Cascade;
184
185 RegInfo() : Stage(RS_New), Cascade(0) {}
186 };
187
188 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000189
190 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000191 return ExtraRegInfo[VirtReg.reg].Stage;
192 }
193
194 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
195 ExtraRegInfo.resize(MRI->getNumVirtRegs());
196 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000197 }
198
199 template<typename Iterator>
200 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000201 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000202 for (;Begin != End; ++Begin) {
Mark Lacey1feb5852013-08-14 23:50:04 +0000203 unsigned Reg = *Begin;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000204 if (ExtraRegInfo[Reg].Stage == RS_New)
205 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000206 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000207 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000208
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000209 /// Cost of evicting interference.
210 struct EvictionCost {
211 unsigned BrokenHints; ///< Total number of broken hints.
212 float MaxWeight; ///< Maximum spill weight evicted.
213
Stephen Hines36b56882014-04-23 16:57:46 -0700214 EvictionCost(): BrokenHints(0), MaxWeight(0) {}
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000215
Andrew Trick6ea2b962013-07-25 18:35:14 +0000216 bool isMax() const { return BrokenHints == ~0u; }
217
Stephen Hines36b56882014-04-23 16:57:46 -0700218 void setMax() { BrokenHints = ~0u; }
219
220 void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
221
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000222 bool operator<(const EvictionCost &O) const {
Stephen Hines36b56882014-04-23 16:57:46 -0700223 return std::tie(BrokenHints, MaxWeight) <
224 std::tie(O.BrokenHints, O.MaxWeight);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000225 }
226 };
227
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000228 // splitting state.
Stephen Hines36b56882014-04-23 16:57:46 -0700229 std::unique_ptr<SplitAnalysis> SA;
230 std::unique_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000231
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000232 /// Cached per-block interference maps
233 InterferenceCache IntfCache;
234
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000235 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000236 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000237
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000238 /// Global live range splitting candidate info.
239 struct GlobalSplitCandidate {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000240 // Register intended for assignment, or 0.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000241 unsigned PhysReg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000242
243 // SplitKit interval index for this candidate.
244 unsigned IntvIdx;
245
246 // Interference for PhysReg.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000247 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000248
249 // Bundles where this candidate should be live.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000250 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000251 SmallVector<unsigned, 8> ActiveBlocks;
252
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000253 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000254 PhysReg = Reg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000255 IntvIdx = 0;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000256 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000257 LiveBundles.clear();
258 ActiveBlocks.clear();
259 }
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000260
261 // Set B[i] = C for every live bundle where B[i] was NoCand.
262 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
263 unsigned Count = 0;
264 for (int i = LiveBundles.find_first(); i >= 0;
265 i = LiveBundles.find_next(i))
266 if (B[i] == NoCand) {
267 B[i] = C;
268 Count++;
269 }
270 return Count;
271 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000272 };
273
Stephen Hines36b56882014-04-23 16:57:46 -0700274 /// Candidate info for each PhysReg in AllocationOrder.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000275 /// This vector never shrinks, but grows to the size of the largest register
276 /// class.
277 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
278
Stephen Hines36b56882014-04-23 16:57:46 -0700279 enum : unsigned { NoCand = ~0u };
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000280
281 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
282 /// NoCand which indicates the stack interval.
283 SmallVector<unsigned, 32> BundleCand;
284
Stephen Hinesdce4a402014-05-29 02:49:00 -0700285 /// Callee-save register cost, calculated once per machine function.
286 BlockFrequency CSRCost;
287
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000288public:
289 RAGreedy();
290
291 /// Return the pass name.
Stephen Hines36b56882014-04-23 16:57:46 -0700292 const char* getPassName() const override {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000293 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000294 }
295
296 /// RAGreedy analysis usage.
Stephen Hines36b56882014-04-23 16:57:46 -0700297 void getAnalysisUsage(AnalysisUsage &AU) const override;
298 void releaseMemory() override;
299 Spiller &spiller() override { return *SpillerInstance; }
300 void enqueue(LiveInterval *LI) override;
301 LiveInterval *dequeue() override;
302 unsigned selectOrSplit(LiveInterval&, SmallVectorImpl<unsigned>&) override;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000303
304 /// Perform register allocation.
Stephen Hines36b56882014-04-23 16:57:46 -0700305 bool runOnMachineFunction(MachineFunction &mf) override;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000306
307 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000308
309private:
Stephen Hines36b56882014-04-23 16:57:46 -0700310 unsigned selectOrSplitImpl(LiveInterval &, SmallVectorImpl<unsigned> &,
311 SmallVirtRegSet &, unsigned = 0);
312
313 bool LRE_CanEraseVirtReg(unsigned) override;
314 void LRE_WillShrinkVirtReg(unsigned) override;
315 void LRE_DidCloneVirtReg(unsigned, unsigned) override;
316 void enqueue(PQueue &CurQueue, LiveInterval *LI);
317 LiveInterval *dequeue(PQueue &CurQueue);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000318
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000319 BlockFrequency calcSpillCost();
320 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000321 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000322 void growRegion(GlobalSplitCandidate &Cand);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000323 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000324 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000325 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000326 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Andrew Trick8adae962013-07-25 18:35:19 +0000327 unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000328 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
329 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
330 void evictInterference(LiveInterval&, unsigned,
Mark Lacey1feb5852013-08-14 23:50:04 +0000331 SmallVectorImpl<unsigned>&);
Stephen Hines36b56882014-04-23 16:57:46 -0700332 bool mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
333 SmallLISet &RecoloringCandidates,
334 const SmallVirtRegSet &FixedRegisters);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000335
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000336 unsigned tryAssign(LiveInterval&, AllocationOrder&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000337 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000338 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000339 SmallVectorImpl<unsigned>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000340 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000341 SmallVectorImpl<unsigned>&);
Stephen Hines36b56882014-04-23 16:57:46 -0700342 /// Calculate cost of region splitting.
343 unsigned calculateRegionSplitCost(LiveInterval &VirtReg,
344 AllocationOrder &Order,
345 BlockFrequency &BestCost,
346 unsigned &NumCands, bool IgnoreCSR);
347 /// Perform region splitting.
348 unsigned doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
349 bool HasCompact,
350 SmallVectorImpl<unsigned> &NewVRegs);
351 /// Check other options before using a callee-saved register for the first
352 /// time.
353 unsigned tryAssignCSRFirstTime(LiveInterval &VirtReg, AllocationOrder &Order,
354 unsigned PhysReg, unsigned &CostPerUseLimit,
355 SmallVectorImpl<unsigned> &NewVRegs);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700356 void initializeCSRCost();
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +0000357 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000358 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +0000359 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000360 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000361 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000362 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000363 unsigned trySplit(LiveInterval&, AllocationOrder&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000364 SmallVectorImpl<unsigned>&);
Stephen Hines36b56882014-04-23 16:57:46 -0700365 unsigned tryLastChanceRecoloring(LiveInterval &, AllocationOrder &,
366 SmallVectorImpl<unsigned> &,
367 SmallVirtRegSet &, unsigned);
368 bool tryRecoloringCandidates(PQueue &, SmallVectorImpl<unsigned> &,
369 SmallVirtRegSet &, unsigned);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000370};
371} // end anonymous namespace
372
373char RAGreedy::ID = 0;
374
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000375#ifndef NDEBUG
376const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000377 "RS_New",
378 "RS_Assign",
379 "RS_Split",
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000380 "RS_Split2",
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000381 "RS_Spill",
382 "RS_Done"
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000383};
384#endif
385
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000386// Hysteresis to use when comparing floats.
387// This helps stabilize decisions based on float comparisons.
Stephen Hines36b56882014-04-23 16:57:46 -0700388const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000389
390
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000391FunctionPass* llvm::createGreedyRegisterAllocator() {
392 return new RAGreedy();
393}
394
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000395RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000396 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000397 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000398 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
399 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000400 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Trick42b7a712012-01-17 06:55:03 +0000401 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000402 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
403 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
404 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
405 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000406 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000407 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
408 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000409}
410
411void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
412 AU.setPreservesCFG();
Benjamin Kramer4eed7562013-06-17 19:00:36 +0000413 AU.addRequired<MachineBlockFrequencyInfo>();
414 AU.addPreserved<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000415 AU.addRequired<AliasAnalysis>();
416 AU.addPreserved<AliasAnalysis>();
417 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000418 AU.addPreserved<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000419 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000420 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000421 AU.addRequired<LiveDebugVariables>();
422 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000423 AU.addRequired<LiveStacks>();
424 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000425 AU.addRequired<MachineDominatorTree>();
426 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000427 AU.addRequired<MachineLoopInfo>();
428 AU.addPreserved<MachineLoopInfo>();
429 AU.addRequired<VirtRegMap>();
430 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000431 AU.addRequired<LiveRegMatrix>();
432 AU.addPreserved<LiveRegMatrix>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000433 AU.addRequired<EdgeBundles>();
434 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000435 MachineFunctionPass::getAnalysisUsage(AU);
436}
437
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000438
439//===----------------------------------------------------------------------===//
440// LiveRangeEdit delegate methods
441//===----------------------------------------------------------------------===//
442
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000443bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000444 if (VRM->hasPhys(VirtReg)) {
445 Matrix->unassign(LIS->getInterval(VirtReg));
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000446 return true;
447 }
448 // Unassigned virtreg is probably in the priority queue.
449 // RegAllocBase will erase it after dequeueing.
450 return false;
451}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000452
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000453void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000454 if (!VRM->hasPhys(VirtReg))
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000455 return;
456
457 // Register is assigned, put it back on the queue for reassignment.
458 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000459 Matrix->unassign(LI);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000460 enqueue(&LI);
461}
462
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000463void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen0d4fea72011-09-14 17:34:37 +0000464 // Cloning a register we haven't even heard about yet? Just ignore it.
465 if (!ExtraRegInfo.inBounds(Old))
466 return;
467
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000468 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000469 // be split into connected components. The new components are much smaller
470 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000471 // same stage as the parent.
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000472 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000473 ExtraRegInfo.grow(New);
474 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000475}
476
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000477void RAGreedy::releaseMemory() {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700478 SpillerInstance.reset(nullptr);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000479 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000480 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000481}
482
Stephen Hines36b56882014-04-23 16:57:46 -0700483void RAGreedy::enqueue(LiveInterval *LI) { enqueue(Queue, LI); }
484
485void RAGreedy::enqueue(PQueue &CurQueue, LiveInterval *LI) {
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000486 // Prioritize live ranges by size, assigning larger ranges first.
487 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000488 const unsigned Size = LI->getSize();
489 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000490 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
491 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000492 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000493
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000494 ExtraRegInfo.grow(Reg);
495 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000496 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000497
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000498 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000499 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000500 // everything else has been allocated.
501 Prio = Size;
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000502 } else {
Stephen Hines36b56882014-04-23 16:57:46 -0700503 // Giant live ranges fall back to the global assignment heuristic, which
504 // prevents excessive spilling in pathological cases.
505 bool ReverseLocal = TRI->reverseLocalAssignment();
506 bool ForceGlobal = !ReverseLocal && TRI->mayOverrideLocalAssignment() &&
507 (Size / SlotIndex::InstrDist) > (2 * MRI->getRegClass(Reg)->getNumRegs());
508
509 if (ExtraRegInfo[Reg].Stage == RS_Assign && !ForceGlobal && !LI->empty() &&
Andrew Trick6ea2b962013-07-25 18:35:14 +0000510 LIS->intervalIsInOneMBB(*LI)) {
511 // Allocate original local ranges in linear instruction order. Since they
512 // are singly defined, this produces optimal coloring in the absence of
513 // global interference and other constraints.
Stephen Hines36b56882014-04-23 16:57:46 -0700514 if (!ReverseLocal)
515 Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
516 else {
517 // Allocating bottom up may allow many short LRGs to be assigned first
518 // to one of the cheap registers. This could be much faster for very
519 // large blocks on targets with many physical registers.
520 Prio = Indexes->getZeroIndex().getInstrDistance(LI->beginIndex());
521 }
Andrew Trick6ea2b962013-07-25 18:35:14 +0000522 }
523 else {
524 // Allocate global and split ranges in long->short order. Long ranges that
525 // don't fit should be spilled (or split) ASAP so they don't create
526 // interference. Mark a bit to prioritize global above local ranges.
527 Prio = (1u << 29) + Size;
528 }
529 // Mark a higher bit to prioritize global and local above RS_Split.
530 Prio |= (1u << 31);
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000531
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000532 // Boost ranges that have a physical register hint.
Jakob Stoklund Olesenfc637442012-12-03 23:23:50 +0000533 if (VRM->hasKnownPreference(Reg))
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000534 Prio |= (1u << 30);
535 }
Andrew Trickbef4c3e2013-07-25 18:35:22 +0000536 // The virtual register number is a tie breaker for same-sized ranges.
537 // Give lower vreg numbers higher priority to assign them first.
Stephen Hines36b56882014-04-23 16:57:46 -0700538 CurQueue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000539}
540
Stephen Hines36b56882014-04-23 16:57:46 -0700541LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); }
542
543LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
544 if (CurQueue.empty())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700545 return nullptr;
Stephen Hines36b56882014-04-23 16:57:46 -0700546 LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
547 CurQueue.pop();
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000548 return LI;
549}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000550
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000551
552//===----------------------------------------------------------------------===//
553// Direct Assignment
554//===----------------------------------------------------------------------===//
555
556/// tryAssign - Try to assign VirtReg to an available register.
557unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
558 AllocationOrder &Order,
Mark Lacey1feb5852013-08-14 23:50:04 +0000559 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000560 Order.rewind();
561 unsigned PhysReg;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000562 while ((PhysReg = Order.next()))
563 if (!Matrix->checkInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000564 break;
Jakob Stoklund Olesenf7999fe2012-12-04 22:25:16 +0000565 if (!PhysReg || Order.isHint())
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000566 return PhysReg;
567
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000568 // PhysReg is available, but there may be a better choice.
569
570 // If we missed a simple hint, try to cheaply evict interference from the
571 // preferred register.
572 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000573 if (Order.isHint(Hint)) {
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000574 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
Stephen Hines36b56882014-04-23 16:57:46 -0700575 EvictionCost MaxCost;
576 MaxCost.setBrokenHints(1);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000577 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
578 evictInterference(VirtReg, Hint, NewVRegs);
579 return Hint;
580 }
581 }
582
583 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000584 unsigned Cost = TRI->getCostPerUse(PhysReg);
585
586 // Most registers have 0 additional cost.
587 if (!Cost)
588 return PhysReg;
589
590 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
591 << '\n');
592 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
593 return CheapReg ? CheapReg : PhysReg;
594}
595
596
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000597//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000598// Interference eviction
599//===----------------------------------------------------------------------===//
600
Andrew Trick8adae962013-07-25 18:35:19 +0000601unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
602 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
603 unsigned PhysReg;
604 while ((PhysReg = Order.next())) {
605 if (PhysReg == PrevReg)
606 continue;
607
608 MCRegUnitIterator Units(PhysReg, TRI);
609 for (; Units.isValid(); ++Units) {
610 // Instantiate a "subquery", not to be confused with the Queries array.
611 LiveIntervalUnion::Query subQ(&VirtReg, &Matrix->getLiveUnions()[*Units]);
612 if (subQ.checkInterference())
613 break;
614 }
615 // If no units have interference, break out with the current PhysReg.
616 if (!Units.isValid())
617 break;
618 }
619 if (PhysReg)
620 DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
621 << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
622 << '\n');
623 return PhysReg;
624}
625
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000626/// shouldEvict - determine if A should evict the assigned live range B. The
627/// eviction policy defined by this function together with the allocation order
628/// defined by enqueue() decides which registers ultimately end up being split
629/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000630///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000631/// Cascade numbers are used to prevent infinite loops if this function is a
632/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000633///
634/// @param A The live range to be assigned.
635/// @param IsHint True when A is about to be assigned to its preferred
636/// register.
637/// @param B The live range to be evicted.
638/// @param BreaksHint True when B is already assigned to its preferred register.
639bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
640 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000641 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000642
643 // Be fairly aggressive about following hints as long as the evictee can be
644 // split.
645 if (CanSplit && IsHint && !BreaksHint)
646 return true;
647
Stephen Hines36b56882014-04-23 16:57:46 -0700648 if (A.weight > B.weight) {
649 DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight << '\n');
650 return true;
651 }
652 return false;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000653}
654
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000655/// canEvictInterference - Return true if all interferences between VirtReg and
Stephen Hines36b56882014-04-23 16:57:46 -0700656/// PhysReg can be evicted.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000657///
658/// @param VirtReg Live range that is about to be assigned.
659/// @param PhysReg Desired register for assignment.
Dmitri Gribenko67c89782012-09-12 16:59:47 +0000660/// @param IsHint True when PhysReg is VirtReg's preferred register.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000661/// @param MaxCost Only look for cheaper candidates and update with new cost
662/// when returning true.
663/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000664bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000665 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000666 // It is only possible to evict virtual register interference.
667 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
668 return false;
669
Andrew Trick6ea2b962013-07-25 18:35:14 +0000670 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
671
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000672 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
673 // involved in an eviction before. If a cascade number was assigned, deny
674 // evicting anything with the same or a newer cascade number. This prevents
675 // infinite eviction loops.
676 //
677 // This works out so a register without a cascade number is allowed to evict
678 // anything, and it can be evicted by anything.
679 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
680 if (!Cascade)
681 Cascade = NextCascade;
682
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000683 EvictionCost Cost;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000684 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
685 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000686 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000687 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000688 return false;
689
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000690 // Check if any interfering live range is heavier than MaxWeight.
691 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
692 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000693 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
694 "Only expecting virtual register interference from query");
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000695 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000696 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000697 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000698 // Once a live range becomes small enough, it is urgent that we find a
699 // register for it. This is indicated by an infinite spill weight. These
700 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen9cda1be2012-05-30 21:46:58 +0000701 //
702 // Also allow urgent evictions of unspillable ranges from a strictly
703 // larger allocation order.
704 bool Urgent = !VirtReg.isSpillable() &&
705 (Intf->isSpillable() ||
706 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
707 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000708 // Only evict older cascades or live ranges without a cascade.
709 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
710 if (Cascade <= IntfCascade) {
711 if (!Urgent)
712 return false;
713 // We permit breaking cascades for urgent evictions. It should be the
714 // last resort, though, so make it really expensive.
715 Cost.BrokenHints += 10;
716 }
717 // Would this break a satisfied hint?
718 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
719 // Update eviction cost.
720 Cost.BrokenHints += BreaksHint;
721 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
722 // Abort if this would be too expensive.
723 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000724 return false;
Andrew Trick6ea2b962013-07-25 18:35:14 +0000725 if (Urgent)
726 continue;
Stephen Hines36b56882014-04-23 16:57:46 -0700727 // Apply the eviction policy for non-urgent evictions.
728 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
729 return false;
Andrew Trick6ea2b962013-07-25 18:35:14 +0000730 // If !MaxCost.isMax(), then we're just looking for a cheap register.
731 // Evicting another local live range in this case could lead to suboptimal
732 // coloring.
Andrew Trick8adae962013-07-25 18:35:19 +0000733 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
734 !canReassign(*Intf, PhysReg)) {
Andrew Trick6ea2b962013-07-25 18:35:14 +0000735 return false;
Andrew Trick8adae962013-07-25 18:35:19 +0000736 }
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000737 }
738 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000739 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000740 return true;
741}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000742
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000743/// evictInterference - Evict any interferring registers that prevent VirtReg
744/// from being assigned to Physreg. This assumes that canEvictInterference
745/// returned true.
746void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Mark Lacey1feb5852013-08-14 23:50:04 +0000747 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000748 // Make sure that VirtReg has a cascade number, and assign that cascade
749 // number to every evicted register. These live ranges than then only be
750 // evicted by a newer cascade, preventing infinite loops.
751 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
752 if (!Cascade)
753 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
754
755 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
756 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000757
758 // Collect all interfering virtregs first.
759 SmallVector<LiveInterval*, 8> Intfs;
760 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
761 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000762 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000763 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
764 Intfs.append(IVR.begin(), IVR.end());
765 }
766
767 // Evict them second. This will invalidate the queries.
768 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
769 LiveInterval *Intf = Intfs[i];
770 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
771 if (!VRM->hasPhys(Intf->reg))
772 continue;
773 Matrix->unassign(*Intf);
774 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
775 VirtReg.isSpillable() < Intf->isSpillable()) &&
776 "Cannot decrease cascade number, illegal eviction");
777 ExtraRegInfo[Intf->reg].Cascade = Cascade;
778 ++NumEvicted;
Mark Lacey1feb5852013-08-14 23:50:04 +0000779 NewVRegs.push_back(Intf->reg);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000780 }
781}
782
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000783/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000784/// @param VirtReg Currently unassigned virtual register.
785/// @param Order Physregs to try.
786/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000787unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
788 AllocationOrder &Order,
Mark Lacey1feb5852013-08-14 23:50:04 +0000789 SmallVectorImpl<unsigned> &NewVRegs,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000790 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000791 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
792
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000793 // Keep track of the cheapest interference seen so far.
Stephen Hines36b56882014-04-23 16:57:46 -0700794 EvictionCost BestCost;
795 BestCost.setMax();
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000796 unsigned BestPhys = 0;
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000797 unsigned OrderLimit = Order.getOrder().size();
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000798
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000799 // When we are just looking for a reduced cost per use, don't break any
800 // hints, and only evict smaller spill weights.
801 if (CostPerUseLimit < ~0u) {
802 BestCost.BrokenHints = 0;
803 BestCost.MaxWeight = VirtReg.weight;
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000804
805 // Check of any registers in RC are below CostPerUseLimit.
806 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
807 unsigned MinCost = RegClassInfo.getMinCost(RC);
808 if (MinCost >= CostPerUseLimit) {
809 DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
810 << ", no cheaper registers to be found.\n");
811 return 0;
812 }
813
814 // It is normal for register classes to have a long tail of registers with
815 // the same cost. We don't need to look at them if they're too expensive.
816 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
817 OrderLimit = RegClassInfo.getLastCostChange(RC);
818 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
819 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000820 }
821
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000822 Order.rewind();
Stephen Hines36b56882014-04-23 16:57:46 -0700823 while (unsigned PhysReg = Order.next(OrderLimit)) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000824 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
825 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000826 // The first use of a callee-saved register in a function has cost 1.
827 // Don't start using a CSR when the CostPerUseLimit is low.
828 if (CostPerUseLimit == 1)
829 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
830 if (!MRI->isPhysRegUsed(CSR)) {
831 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
832 << PrintReg(CSR, TRI) << '\n');
833 continue;
834 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000835
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000836 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000837 continue;
838
839 // Best so far.
840 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000841
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000842 // Stop if the hint can be used.
Jakob Stoklund Olesenf7999fe2012-12-04 22:25:16 +0000843 if (Order.isHint())
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000844 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000845 }
846
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000847 if (!BestPhys)
848 return 0;
849
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000850 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000851 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000852}
853
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000854
855//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000856// Region Splitting
857//===----------------------------------------------------------------------===//
858
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000859/// addSplitConstraints - Fill out the SplitConstraints vector based on the
860/// interference pattern in Physreg and its aliases. Add the constraints to
861/// SpillPlacement and return the static cost of this split in Cost, assuming
862/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000863/// Return false if there are no bundles with positive bias.
864bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000865 BlockFrequency &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000866 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000867
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000868 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000869 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000870 BlockFrequency StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000871 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
872 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000873 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000874
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000875 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000876 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000877 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
878 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
David Blaikie453f4f02013-05-15 07:36:59 +0000879 BC.ChangesValue = BI.FirstDef.isValid();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000880
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000881 if (!Intf.hasInterference())
882 continue;
883
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000884 // Number of spill code instructions to insert.
885 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000886
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000887 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000888 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000889 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000890 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000891 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000892 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000893 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000894 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000895 }
896
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000897 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000898 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000899 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000900 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000901 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000902 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000903 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000904 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000905 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000906
907 // Accumulate the total frequency of inserted spill code.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000908 while (Ins--)
909 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000910 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000911 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000912
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000913 // Add constraints for use-blocks. Note that these are the only constraints
914 // that may add a positive bias, it is downhill from here.
915 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000916 return SpillPlacer->scanActiveBundles();
917}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000918
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000919
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000920/// addThroughConstraints - Add constraints and links to SpillPlacer from the
921/// live-through blocks in Blocks.
922void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
923 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000924 const unsigned GroupSize = 8;
925 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000926 unsigned TBS[GroupSize];
927 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000928
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000929 for (unsigned i = 0; i != Blocks.size(); ++i) {
930 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000931 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000932
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000933 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000934 assert(T < GroupSize && "Array overflow");
935 TBS[T] = Number;
936 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000937 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000938 T = 0;
939 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000940 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000941 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000942
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000943 assert(B < GroupSize && "Array overflow");
944 BCS[B].Number = Number;
945
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000946 // Interference for the live-in value.
947 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
948 BCS[B].Entry = SpillPlacement::MustSpill;
949 else
950 BCS[B].Entry = SpillPlacement::PrefSpill;
951
952 // Interference for the live-out value.
953 if (Intf.last() >= SA->getLastSplitPoint(Number))
954 BCS[B].Exit = SpillPlacement::MustSpill;
955 else
956 BCS[B].Exit = SpillPlacement::PrefSpill;
957
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000958 if (++B == GroupSize) {
959 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
960 SpillPlacer->addConstraints(Array);
961 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000962 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000963 }
964
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000965 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
966 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000967 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000968}
969
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000970void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000971 // Keep track of through blocks that have not been added to SpillPlacer.
972 BitVector Todo = SA->getThroughBlocks();
973 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
974 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000975#ifndef NDEBUG
976 unsigned Visited = 0;
977#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000978
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000979 for (;;) {
980 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000981 // Find new through blocks in the periphery of PrefRegBundles.
982 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
983 unsigned Bundle = NewBundles[i];
984 // Look at all blocks connected to Bundle in the full graph.
985 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
986 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
987 I != E; ++I) {
988 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000989 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000990 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000991 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000992 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000993 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000994#ifndef NDEBUG
995 ++Visited;
996#endif
997 }
998 }
999 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +00001000 if (ActiveBlocks.size() == AddedTo)
1001 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +00001002
1003 // Compute through constraints from the interference, or assume that all
1004 // through blocks prefer spilling when forming compact regions.
1005 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
1006 if (Cand.PhysReg)
1007 addThroughConstraints(Cand.Intf, NewBlocks);
1008 else
Jakob Stoklund Olesenb87f91b2011-08-03 23:09:38 +00001009 // Provide a strong negative bias on through blocks to prevent unwanted
1010 // liveness on loop backedges.
1011 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +00001012 AddedTo = ActiveBlocks.size();
1013
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001014 // Perhaps iterating can enable more bundles?
1015 SpillPlacer->iterate();
1016 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001017 DEBUG(dbgs() << ", v=" << Visited);
1018}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001019
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +00001020/// calcCompactRegion - Compute the set of edge bundles that should be live
1021/// when splitting the current live range into compact regions. Compact
1022/// regions can be computed without looking at interference. They are the
1023/// regions formed by removing all the live-through blocks from the live range.
1024///
1025/// Returns false if the current live range is already compact, or if the
1026/// compact regions would form single block regions anyway.
1027bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
1028 // Without any through blocks, the live range is already compact.
1029 if (!SA->getNumThroughBlocks())
1030 return false;
1031
1032 // Compact regions don't correspond to any physreg.
1033 Cand.reset(IntfCache, 0);
1034
1035 DEBUG(dbgs() << "Compact region bundles");
1036
1037 // Use the spill placer to determine the live bundles. GrowRegion pretends
1038 // that all the through blocks have interference when PhysReg is unset.
1039 SpillPlacer->prepare(Cand.LiveBundles);
1040
1041 // The static split cost will be zero since Cand.Intf reports no interference.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001042 BlockFrequency Cost;
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +00001043 if (!addSplitConstraints(Cand.Intf, Cost)) {
1044 DEBUG(dbgs() << ", none.\n");
1045 return false;
1046 }
1047
1048 growRegion(Cand);
1049 SpillPlacer->finish();
1050
1051 if (!Cand.LiveBundles.any()) {
1052 DEBUG(dbgs() << ", none.\n");
1053 return false;
1054 }
1055
1056 DEBUG({
1057 for (int i = Cand.LiveBundles.find_first(); i>=0;
1058 i = Cand.LiveBundles.find_next(i))
1059 dbgs() << " EB#" << i;
1060 dbgs() << ".\n";
1061 });
1062 return true;
1063}
1064
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001065/// calcSpillCost - Compute how expensive it would be to split the live range in
1066/// SA around all use blocks instead of forming bundle regions.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001067BlockFrequency RAGreedy::calcSpillCost() {
1068 BlockFrequency Cost = 0;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001069 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1070 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1071 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1072 unsigned Number = BI.MBB->getNumber();
1073 // We normally only need one spill instruction - a load or a store.
1074 Cost += SpillPlacer->getBlockFrequency(Number);
1075
1076 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3f5beed2011-08-02 23:04:08 +00001077 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
1078 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001079 }
1080 return Cost;
1081}
1082
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001083/// calcGlobalSplitCost - Return the global split cost of following the split
1084/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001085/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001086///
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001087BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
1088 BlockFrequency GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001089 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001090 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1091 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1092 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001093 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001094 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
1095 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
1096 unsigned Ins = 0;
1097
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001098 if (BI.LiveIn)
1099 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
1100 if (BI.LiveOut)
1101 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001102 while (Ins--)
1103 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001104 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001105
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001106 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1107 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001108 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
1109 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +00001110 if (!RegIn && !RegOut)
1111 continue;
1112 if (RegIn && RegOut) {
1113 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001114 Cand.Intf.moveToBlock(Number);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001115 if (Cand.Intf.hasInterference()) {
1116 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1117 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1118 }
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +00001119 continue;
1120 }
1121 // live-in / stack-out or stack-in live-out.
1122 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001123 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001124 return GlobalCost;
1125}
1126
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001127/// splitAroundRegion - Split the current live range around the regions
1128/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001129///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001130/// Before calling this function, GlobalCand and BundleCand must be initialized
1131/// so each bundle is assigned to a valid candidate, or NoCand for the
1132/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1133/// objects must be initialized for the current live range, and intervals
1134/// created for the used candidates.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001135///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001136/// @param LREdit The LiveRangeEdit object handling the current split.
1137/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1138/// must appear in this list.
1139void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1140 ArrayRef<unsigned> UsedCands) {
1141 // These are the intervals created for new global ranges. We may create more
1142 // intervals for local ranges.
1143 const unsigned NumGlobalIntvs = LREdit.size();
1144 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1145 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001146
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001147 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen69145ba2011-08-06 18:20:24 +00001148 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001149 // is all copies.
1150 unsigned Reg = SA->getParent().reg;
1151 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1152
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +00001153 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001154 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1155 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1156 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001157 unsigned Number = BI.MBB->getNumber();
1158 unsigned IntvIn = 0, IntvOut = 0;
1159 SlotIndex IntfIn, IntfOut;
1160 if (BI.LiveIn) {
1161 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1162 if (CandIn != NoCand) {
1163 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1164 IntvIn = Cand.IntvIdx;
1165 Cand.Intf.moveToBlock(Number);
1166 IntfIn = Cand.Intf.first();
1167 }
1168 }
1169 if (BI.LiveOut) {
1170 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1171 if (CandOut != NoCand) {
1172 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1173 IntvOut = Cand.IntvIdx;
1174 Cand.Intf.moveToBlock(Number);
1175 IntfOut = Cand.Intf.last();
1176 }
1177 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001178
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001179 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001180 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001181 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001182 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +00001183 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001184 continue;
1185 }
1186
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001187 if (IntvIn && IntvOut)
1188 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1189 else if (IntvIn)
1190 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +00001191 else
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001192 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001193 }
1194
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001195 // Handle live-through blocks. The relevant live-through blocks are stored in
1196 // the ActiveBlocks list with each candidate. We need to filter out
1197 // duplicates.
1198 BitVector Todo = SA->getThroughBlocks();
1199 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1200 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1201 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1202 unsigned Number = Blocks[i];
1203 if (!Todo.test(Number))
1204 continue;
1205 Todo.reset(Number);
1206
1207 unsigned IntvIn = 0, IntvOut = 0;
1208 SlotIndex IntfIn, IntfOut;
1209
1210 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1211 if (CandIn != NoCand) {
1212 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1213 IntvIn = Cand.IntvIdx;
1214 Cand.Intf.moveToBlock(Number);
1215 IntfIn = Cand.Intf.first();
1216 }
1217
1218 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1219 if (CandOut != NoCand) {
1220 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1221 IntvOut = Cand.IntvIdx;
1222 Cand.Intf.moveToBlock(Number);
1223 IntfOut = Cand.Intf.last();
1224 }
1225 if (!IntvIn && !IntvOut)
1226 continue;
1227 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1228 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001229 }
1230
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001231 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001232
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001233 SmallVector<unsigned, 8> IntvMap;
1234 SE->finish(&IntvMap);
Mark Lacey1feb5852013-08-14 23:50:04 +00001235 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001236
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001237 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +00001238 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001239
1240 // Sort out the new intervals created by splitting. We get four kinds:
1241 // - Remainder intervals should not be split again.
1242 // - Candidate intervals can be assigned to Cand.PhysReg.
1243 // - Block-local splits are candidates for local splitting.
1244 // - DCE leftovers should go back on the queue.
1245 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Lacey1feb5852013-08-14 23:50:04 +00001246 LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001247
1248 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001249 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001250 continue;
1251
1252 // Remainder interval. Don't try splitting again, spill if it doesn't
1253 // allocate.
1254 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001255 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001256 continue;
1257 }
1258
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001259 // Global intervals. Allow repeated splitting as long as the number of live
1260 // blocks is strictly decreasing.
1261 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001262 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001263 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1264 << " blocks as original.\n");
1265 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001266 setStage(Reg, RS_Split2);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001267 }
1268 continue;
1269 }
1270
1271 // Other intervals are treated as new. This includes local intervals created
1272 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001273 }
1274
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001275 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001276 MF->verify(this, "After splitting live range around region");
1277}
1278
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001279unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Lacey1feb5852013-08-14 23:50:04 +00001280 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001281 unsigned NumCands = 0;
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001282 BlockFrequency BestCost;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001283
1284 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +00001285 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001286 if (HasCompact) {
1287 // Yes, keep GlobalCand[0] as the compact region candidate.
1288 NumCands = 1;
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001289 BestCost = BlockFrequency::getMaxFrequency();
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001290 } else {
1291 // No benefit from the compact region, our fallback will be per-block
1292 // splitting. Make sure we find a solution that is cheaper than spilling.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001293 BestCost = calcSpillCost();
Stephen Hines36b56882014-04-23 16:57:46 -07001294 DEBUG(dbgs() << "Cost of isolating all blocks = ";
1295 MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001296 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001297
Stephen Hines36b56882014-04-23 16:57:46 -07001298 unsigned BestCand =
1299 calculateRegionSplitCost(VirtReg, Order, BestCost, NumCands,
1300 false/*IgnoreCSR*/);
1301
1302 // No solutions found, fall back to single block splitting.
1303 if (!HasCompact && BestCand == NoCand)
1304 return 0;
1305
1306 return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
1307}
1308
1309unsigned RAGreedy::calculateRegionSplitCost(LiveInterval &VirtReg,
1310 AllocationOrder &Order,
1311 BlockFrequency &BestCost,
1312 unsigned &NumCands,
1313 bool IgnoreCSR) {
1314 unsigned BestCand = NoCand;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001315 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001316 while (unsigned PhysReg = Order.next()) {
Stephen Hines36b56882014-04-23 16:57:46 -07001317 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
1318 if (IgnoreCSR && !MRI->isPhysRegUsed(CSR))
1319 continue;
1320
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001321 // Discard bad candidates before we run out of interference cache cursors.
1322 // This will only affect register classes with a lot of registers (>32).
1323 if (NumCands == IntfCache.getMaxCursors()) {
1324 unsigned WorstCount = ~0u;
1325 unsigned Worst = 0;
1326 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001327 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001328 continue;
1329 unsigned Count = GlobalCand[i].LiveBundles.count();
1330 if (Count < WorstCount)
1331 Worst = i, WorstCount = Count;
1332 }
1333 --NumCands;
1334 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen7bdf0062011-11-01 00:02:31 +00001335 if (BestCand == NumCands)
1336 BestCand = Worst;
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001337 }
1338
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001339 if (GlobalCand.size() <= NumCands)
1340 GlobalCand.resize(NumCands+1);
1341 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1342 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001343
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001344 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001345 BlockFrequency Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001346 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001347 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001348 continue;
1349 }
Stephen Hines36b56882014-04-23 16:57:46 -07001350 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = ";
1351 MBFI->printBlockFreq(dbgs(), Cost));
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001352 if (Cost >= BestCost) {
1353 DEBUG({
1354 if (BestCand == NoCand)
1355 dbgs() << " worse than no bundles\n";
1356 else
1357 dbgs() << " worse than "
1358 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1359 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001360 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001361 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001362 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001363
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001364 SpillPlacer->finish();
1365
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001366 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001367 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001368 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001369 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001370 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001371
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001372 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001373 DEBUG({
Stephen Hines36b56882014-04-23 16:57:46 -07001374 dbgs() << ", total = "; MBFI->printBlockFreq(dbgs(), Cost)
1375 << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001376 for (int i = Cand.LiveBundles.find_first(); i>=0;
1377 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001378 dbgs() << " EB#" << i;
1379 dbgs() << ".\n";
1380 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001381 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001382 BestCand = NumCands;
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001383 BestCost = Cost;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001384 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001385 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001386 }
Stephen Hines36b56882014-04-23 16:57:46 -07001387 return BestCand;
1388}
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001389
Stephen Hines36b56882014-04-23 16:57:46 -07001390unsigned RAGreedy::doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
1391 bool HasCompact,
1392 SmallVectorImpl<unsigned> &NewVRegs) {
1393 SmallVector<unsigned, 8> UsedCands;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001394 // Prepare split editor.
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001395 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001396 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001397
1398 // Assign all edge bundles to the preferred candidate, or NoCand.
1399 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1400
1401 // Assign bundles for the best candidate region.
1402 if (BestCand != NoCand) {
1403 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1404 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1405 UsedCands.push_back(BestCand);
1406 Cand.IntvIdx = SE->openIntv();
1407 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1408 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001409 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001410 }
1411 }
1412
1413 // Assign bundles for the compact region.
1414 if (HasCompact) {
1415 GlobalSplitCandidate &Cand = GlobalCand.front();
1416 assert(!Cand.PhysReg && "Compact region has no physreg");
1417 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1418 UsedCands.push_back(0);
1419 Cand.IntvIdx = SE->openIntv();
1420 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1421 << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001422 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001423 }
1424 }
1425
1426 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001427 return 0;
1428}
1429
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001430
1431//===----------------------------------------------------------------------===//
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001432// Per-Block Splitting
1433//===----------------------------------------------------------------------===//
1434
1435/// tryBlockSplit - Split a global live range around every block with uses. This
1436/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1437/// they don't allocate.
1438unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Lacey1feb5852013-08-14 23:50:04 +00001439 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001440 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1441 unsigned Reg = VirtReg.reg;
1442 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001443 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001444 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001445 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1446 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1447 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1448 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1449 SE->splitSingleBlock(BI);
1450 }
1451 // No blocks were split.
1452 if (LREdit.empty())
1453 return 0;
1454
1455 // We did split for some blocks.
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001456 SmallVector<unsigned, 8> IntvMap;
1457 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001458
1459 // Tell LiveDebugVariables about the new ranges.
Mark Lacey1feb5852013-08-14 23:50:04 +00001460 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001461
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001462 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1463
1464 // Sort out the new intervals created by splitting. The remainder interval
1465 // goes straight to spilling, the new local ranges get to stay RS_New.
1466 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Lacey1feb5852013-08-14 23:50:04 +00001467 LiveInterval &LI = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001468 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1469 setStage(LI, RS_Spill);
1470 }
1471
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001472 if (VerifyEnabled)
1473 MF->verify(this, "After splitting live range around basic blocks");
1474 return 0;
1475}
1476
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001477
1478//===----------------------------------------------------------------------===//
1479// Per-Instruction Splitting
1480//===----------------------------------------------------------------------===//
1481
Stephen Hines36b56882014-04-23 16:57:46 -07001482/// Get the number of allocatable registers that match the constraints of \p Reg
1483/// on \p MI and that are also in \p SuperRC.
1484static unsigned getNumAllocatableRegsForConstraints(
1485 const MachineInstr *MI, unsigned Reg, const TargetRegisterClass *SuperRC,
1486 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1487 const RegisterClassInfo &RCI) {
1488 assert(SuperRC && "Invalid register class");
1489
1490 const TargetRegisterClass *ConstrainedRC =
1491 MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI,
1492 /* ExploreBundle */ true);
1493 if (!ConstrainedRC)
1494 return 0;
1495 return RCI.getNumAllocatableRegs(ConstrainedRC);
1496}
1497
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001498/// tryInstructionSplit - Split a live range around individual instructions.
1499/// This is normally not worthwhile since the spiller is doing essentially the
1500/// same thing. However, when the live range is in a constrained register
1501/// class, it may help to insert copies such that parts of the live range can
1502/// be moved to a larger register class.
1503///
1504/// This is similar to spilling to a larger register class.
1505unsigned
1506RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Lacey1feb5852013-08-14 23:50:04 +00001507 SmallVectorImpl<unsigned> &NewVRegs) {
Stephen Hines36b56882014-04-23 16:57:46 -07001508 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001509 // There is no point to this if there are no larger sub-classes.
Stephen Hines36b56882014-04-23 16:57:46 -07001510 if (!RegClassInfo.isProperSubClass(CurRC))
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001511 return 0;
1512
1513 // Always enable split spill mode, since we're effectively spilling to a
1514 // register.
1515 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1516 SE->reset(LREdit, SplitEditor::SM_Size);
1517
1518 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1519 if (Uses.size() <= 1)
1520 return 0;
1521
1522 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1523
Stephen Hines36b56882014-04-23 16:57:46 -07001524 const TargetRegisterClass *SuperRC = TRI->getLargestLegalSuperClass(CurRC);
1525 unsigned SuperRCNumAllocatableRegs = RCI.getNumAllocatableRegs(SuperRC);
1526 // Split around every non-copy instruction if this split will relax
1527 // the constraints on the virtual register.
1528 // Otherwise, splitting just inserts uncoalescable copies that do not help
1529 // the allocation.
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001530 for (unsigned i = 0; i != Uses.size(); ++i) {
1531 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
Stephen Hines36b56882014-04-23 16:57:46 -07001532 if (MI->isFullCopy() ||
1533 SuperRCNumAllocatableRegs ==
1534 getNumAllocatableRegsForConstraints(MI, VirtReg.reg, SuperRC, TII,
1535 TRI, RCI)) {
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001536 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1537 continue;
1538 }
1539 SE->openIntv();
1540 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1541 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1542 SE->useIntv(SegStart, SegStop);
1543 }
1544
1545 if (LREdit.empty()) {
1546 DEBUG(dbgs() << "All uses were copies.\n");
1547 return 0;
1548 }
1549
1550 SmallVector<unsigned, 8> IntvMap;
1551 SE->finish(&IntvMap);
Mark Lacey1feb5852013-08-14 23:50:04 +00001552 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001553 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1554
1555 // Assign all new registers to RS_Spill. This was the last chance.
1556 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1557 return 0;
1558}
1559
1560
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001561//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001562// Local Splitting
1563//===----------------------------------------------------------------------===//
1564
1565
1566/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1567/// in order to use PhysReg between two entries in SA->UseSlots.
1568///
1569/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1570///
1571void RAGreedy::calcGapWeights(unsigned PhysReg,
1572 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001573 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1574 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001575 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001576 const unsigned NumGaps = Uses.size()-1;
1577
1578 // Start and end points for the interference check.
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001579 SlotIndex StartIdx =
1580 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1581 SlotIndex StopIdx =
1582 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001583
1584 GapWeight.assign(NumGaps, 0.0f);
1585
1586 // Add interference from each overlapping register.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001587 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1588 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1589 .checkInterference())
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001590 continue;
1591
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001592 // We know that VirtReg is a continuous interval from FirstInstr to
1593 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001594 //
1595 // Interference that overlaps an instruction is counted in both gaps
1596 // surrounding the instruction. The exception is interference before
1597 // StartIdx and after StopIdx.
1598 //
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001599 LiveIntervalUnion::SegmentIter IntI =
1600 Matrix->getLiveUnions()[*Units] .find(StartIdx);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001601 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1602 // Skip the gaps before IntI.
1603 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1604 if (++Gap == NumGaps)
1605 break;
1606 if (Gap == NumGaps)
1607 break;
1608
1609 // Update the gaps covered by IntI.
1610 const float weight = IntI.value()->weight;
1611 for (; Gap != NumGaps; ++Gap) {
1612 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1613 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1614 break;
1615 }
1616 if (Gap == NumGaps)
1617 break;
1618 }
1619 }
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001620
1621 // Add fixed interference.
1622 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
Matthias Braun4f3b5e82013-10-10 21:29:02 +00001623 const LiveRange &LR = LIS->getRegUnit(*Units);
1624 LiveRange::const_iterator I = LR.find(StartIdx);
1625 LiveRange::const_iterator E = LR.end();
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001626
1627 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1628 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1629 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1630 if (++Gap == NumGaps)
1631 break;
1632 if (Gap == NumGaps)
1633 break;
1634
1635 for (; Gap != NumGaps; ++Gap) {
Aaron Ballmaneb360242013-11-13 00:15:44 +00001636 GapWeight[Gap] = llvm::huge_valf;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001637 if (Uses[Gap+1].getBaseIndex() >= I->end)
1638 break;
1639 }
1640 if (Gap == NumGaps)
1641 break;
1642 }
1643 }
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001644}
1645
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001646/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1647/// basic block.
1648///
1649unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Lacey1feb5852013-08-14 23:50:04 +00001650 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001651 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1652 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001653
1654 // Note that it is possible to have an interval that is live-in or live-out
1655 // while only covering a single block - A phi-def can use undef values from
1656 // predecessors, and the block could be a single-block loop.
1657 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001658 // that the interval is continuous from FirstInstr to LastInstr. We should
1659 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001660
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001661 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001662 if (Uses.size() <= 2)
1663 return 0;
1664 const unsigned NumGaps = Uses.size()-1;
1665
1666 DEBUG({
1667 dbgs() << "tryLocalSplit: ";
1668 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001669 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001670 dbgs() << '\n';
1671 });
1672
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001673 // If VirtReg is live across any register mask operands, compute a list of
1674 // gaps with register masks.
1675 SmallVector<unsigned, 8> RegMaskGaps;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001676 if (Matrix->checkRegMaskInterference(VirtReg)) {
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001677 // Get regmask slots for the whole block.
1678 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001679 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001680 // Constrain to VirtReg's live range.
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001681 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1682 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001683 unsigned re = RMS.size();
1684 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001685 // Look for Uses[i] <= RMS <= Uses[i+1].
1686 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1687 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001688 continue;
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001689 // Skip a regmask on the same instruction as the last use. It doesn't
1690 // overlap the live range.
1691 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1692 break;
1693 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001694 RegMaskGaps.push_back(i);
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001695 // Advance ri to the next gap. A regmask on one of the uses counts in
1696 // both gaps.
1697 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1698 ++ri;
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001699 }
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001700 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001701 }
1702
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001703 // Since we allow local split results to be split again, there is a risk of
1704 // creating infinite loops. It is tempting to require that the new live
1705 // ranges have less instructions than the original. That would guarantee
1706 // convergence, but it is too strict. A live range with 3 instructions can be
1707 // split 2+3 (including the COPY), and we want to allow that.
1708 //
1709 // Instead we use these rules:
1710 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001711 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001712 // noop split, of course).
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001713 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001714 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001715 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001716 // smaller ranges are marked RS_New.
1717 //
1718 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1719 // excessive splitting and infinite loops.
1720 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001721 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001722
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001723 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001724 unsigned BestBefore = NumGaps;
1725 unsigned BestAfter = 0;
1726 float BestDiff = 0;
1727
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001728 const float blockFreq =
1729 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
Stephen Hines36b56882014-04-23 16:57:46 -07001730 (1.0f / MBFI->getEntryFreq());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001731 SmallVector<float, 8> GapWeight;
1732
1733 Order.rewind();
1734 while (unsigned PhysReg = Order.next()) {
1735 // Keep track of the largest spill weight that would need to be evicted in
1736 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1737 calcGapWeights(PhysReg, GapWeight);
1738
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001739 // Remove any gaps with regmask clobbers.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001740 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001741 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
Aaron Ballmaneb360242013-11-13 00:15:44 +00001742 GapWeight[RegMaskGaps[i]] = llvm::huge_valf;
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001743
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001744 // Try to find the best sequence of gaps to close.
1745 // The new spill weight must be larger than any gap interference.
1746
1747 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001748 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001749
1750 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1751 // It is the spill weight that needs to be evicted.
1752 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001753
1754 for (;;) {
1755 // Live before/after split?
1756 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1757 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1758
1759 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1760 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1761 << " i=" << MaxGap);
1762
1763 // Stop before the interval gets so big we wouldn't be making progress.
1764 if (!LiveBefore && !LiveAfter) {
1765 DEBUG(dbgs() << " all\n");
1766 break;
1767 }
1768 // Should the interval be extended or shrunk?
1769 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001770
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001771 // How many gaps would the new range have?
1772 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1773
1774 // Legally, without causing looping?
1775 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1776
Aaron Ballmaneb360242013-11-13 00:15:44 +00001777 if (Legal && MaxGap < llvm::huge_valf) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001778 // Estimate the new spill weight. Each instruction reads or writes the
1779 // register. Conservatively assume there are no read-modify-write
1780 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001781 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001782 // Try to guess the size of the new interval.
1783 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1784 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1785 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001786 // Would this split be possible to allocate?
1787 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001788 DEBUG(dbgs() << " w=" << EstWeight);
1789 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001790 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001791 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001792 if (Diff > BestDiff) {
1793 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001794 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001795 BestBefore = SplitBefore;
1796 BestAfter = SplitAfter;
1797 }
1798 }
1799 }
1800
1801 // Try to shrink.
1802 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001803 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001804 DEBUG(dbgs() << " shrink\n");
1805 // Recompute the max when necessary.
1806 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1807 MaxGap = GapWeight[SplitBefore];
1808 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1809 MaxGap = std::max(MaxGap, GapWeight[i]);
1810 }
1811 continue;
1812 }
1813 MaxGap = 0;
1814 }
1815
1816 // Try to extend the interval.
1817 if (SplitAfter >= NumGaps) {
1818 DEBUG(dbgs() << " end\n");
1819 break;
1820 }
1821
1822 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001823 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001824 }
1825 }
1826
1827 // Didn't find any candidates?
1828 if (BestBefore == NumGaps)
1829 return 0;
1830
1831 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1832 << '-' << Uses[BestAfter] << ", " << BestDiff
1833 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1834
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001835 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001836 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001837
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001838 SE->openIntv();
1839 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1840 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1841 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001842 SmallVector<unsigned, 8> IntvMap;
1843 SE->finish(&IntvMap);
Mark Lacey1feb5852013-08-14 23:50:04 +00001844 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001845
1846 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001847 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001848 // leave the new intervals as RS_New so they can compete.
1849 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1850 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1851 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1852 if (NewGaps >= NumGaps) {
1853 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1854 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001855 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1856 if (IntvMap[i] == 1) {
Mark Lacey1feb5852013-08-14 23:50:04 +00001857 setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
1858 DEBUG(dbgs() << PrintReg(LREdit.get(i)));
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001859 }
1860 DEBUG(dbgs() << '\n');
1861 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001862 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001863
1864 return 0;
1865}
1866
1867//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001868// Live Range Splitting
1869//===----------------------------------------------------------------------===//
1870
1871/// trySplit - Try to split VirtReg or one of its interferences, making it
1872/// assignable.
1873/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1874unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Lacey1feb5852013-08-14 23:50:04 +00001875 SmallVectorImpl<unsigned>&NewVRegs) {
Jakob Stoklund Olesenccfa4462011-08-05 23:50:33 +00001876 // Ranges must be Split2 or less.
1877 if (getStage(VirtReg) >= RS_Spill)
1878 return 0;
1879
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001880 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001881 if (LIS->intervalIsInOneMBB(VirtReg)) {
1882 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001883 SA->analyze(&VirtReg);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001884 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1885 if (PhysReg || !NewVRegs.empty())
1886 return PhysReg;
1887 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001888 }
1889
1890 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001891
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001892 SA->analyze(&VirtReg);
1893
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001894 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1895 // coalescer. That may cause the range to become allocatable which means that
1896 // tryRegionSplit won't be making progress. This check should be replaced with
1897 // an assertion when the coalescer is fixed.
1898 if (SA->didRepairRange()) {
1899 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001900 Matrix->invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001901 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1902 return PhysReg;
1903 }
1904
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001905 // First try to split around a region spanning multiple blocks. RS_Split2
1906 // ranges already made dubious progress with region splitting, so they go
1907 // straight to single block splitting.
1908 if (getStage(VirtReg) < RS_Split2) {
1909 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1910 if (PhysReg || !NewVRegs.empty())
1911 return PhysReg;
1912 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001913
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001914 // Then isolate blocks.
1915 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001916}
1917
Stephen Hines36b56882014-04-23 16:57:46 -07001918//===----------------------------------------------------------------------===//
1919// Last Chance Recoloring
1920//===----------------------------------------------------------------------===//
1921
1922/// mayRecolorAllInterferences - Check if the virtual registers that
1923/// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be
1924/// recolored to free \p PhysReg.
1925/// When true is returned, \p RecoloringCandidates has been augmented with all
1926/// the live intervals that need to be recolored in order to free \p PhysReg
1927/// for \p VirtReg.
1928/// \p FixedRegisters contains all the virtual registers that cannot be
1929/// recolored.
1930bool
1931RAGreedy::mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
1932 SmallLISet &RecoloringCandidates,
1933 const SmallVirtRegSet &FixedRegisters) {
1934 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
1935
1936 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1937 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
1938 // If there is LastChanceRecoloringMaxInterference or more interferences,
1939 // chances are one would not be recolorable.
1940 if (Q.collectInterferingVRegs(LastChanceRecoloringMaxInterference) >=
Stephen Hinesdce4a402014-05-29 02:49:00 -07001941 LastChanceRecoloringMaxInterference && !ExhaustiveSearch) {
Stephen Hines36b56882014-04-23 16:57:46 -07001942 DEBUG(dbgs() << "Early abort: too many interferences.\n");
Stephen Hinesdce4a402014-05-29 02:49:00 -07001943 CutOffInfo |= CO_Interf;
Stephen Hines36b56882014-04-23 16:57:46 -07001944 return false;
1945 }
1946 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
1947 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
1948 // If Intf is done and sit on the same register class as VirtReg,
1949 // it would not be recolorable as it is in the same state as VirtReg.
1950 if ((getStage(*Intf) == RS_Done &&
1951 MRI->getRegClass(Intf->reg) == CurRC) ||
1952 FixedRegisters.count(Intf->reg)) {
1953 DEBUG(dbgs() << "Early abort: the inteference is not recolorable.\n");
1954 return false;
1955 }
1956 RecoloringCandidates.insert(Intf);
1957 }
1958 }
1959 return true;
1960}
1961
1962/// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
1963/// its interferences.
1964/// Last chance recoloring chooses a color for \p VirtReg and recolors every
1965/// virtual register that was using it. The recoloring process may recursively
1966/// use the last chance recoloring. Therefore, when a virtual register has been
1967/// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
1968/// be last-chance-recolored again during this recoloring "session".
1969/// E.g.,
1970/// Let
1971/// vA can use {R1, R2 }
1972/// vB can use { R2, R3}
1973/// vC can use {R1 }
1974/// Where vA, vB, and vC cannot be split anymore (they are reloads for
1975/// instance) and they all interfere.
1976///
1977/// vA is assigned R1
1978/// vB is assigned R2
1979/// vC tries to evict vA but vA is already done.
1980/// Regular register allocation fails.
1981///
1982/// Last chance recoloring kicks in:
1983/// vC does as if vA was evicted => vC uses R1.
1984/// vC is marked as fixed.
1985/// vA needs to find a color.
1986/// None are available.
1987/// vA cannot evict vC: vC is a fixed virtual register now.
1988/// vA does as if vB was evicted => vA uses R2.
1989/// vB needs to find a color.
1990/// R3 is available.
1991/// Recoloring => vC = R1, vA = R2, vB = R3
1992///
1993/// \p Order defines the preferred allocation order for \p VirtReg.
1994/// \p NewRegs will contain any new virtual register that have been created
1995/// (split, spill) during the process and that must be assigned.
1996/// \p FixedRegisters contains all the virtual registers that cannot be
1997/// recolored.
1998/// \p Depth gives the current depth of the last chance recoloring.
1999/// \return a physical register that can be used for VirtReg or ~0u if none
2000/// exists.
2001unsigned RAGreedy::tryLastChanceRecoloring(LiveInterval &VirtReg,
2002 AllocationOrder &Order,
2003 SmallVectorImpl<unsigned> &NewVRegs,
2004 SmallVirtRegSet &FixedRegisters,
2005 unsigned Depth) {
2006 DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
2007 // Ranges must be Done.
2008 assert((getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
2009 "Last chance recoloring should really be last chance");
2010 // Set the max depth to LastChanceRecoloringMaxDepth.
2011 // We may want to reconsider that if we end up with a too large search space
2012 // for target with hundreds of registers.
2013 // Indeed, in that case we may want to cut the search space earlier.
Stephen Hinesdce4a402014-05-29 02:49:00 -07002014 if (Depth >= LastChanceRecoloringMaxDepth && !ExhaustiveSearch) {
Stephen Hines36b56882014-04-23 16:57:46 -07002015 DEBUG(dbgs() << "Abort because max depth has been reached.\n");
Stephen Hinesdce4a402014-05-29 02:49:00 -07002016 CutOffInfo |= CO_Depth;
Stephen Hines36b56882014-04-23 16:57:46 -07002017 return ~0u;
2018 }
2019
2020 // Set of Live intervals that will need to be recolored.
2021 SmallLISet RecoloringCandidates;
2022 // Record the original mapping virtual register to physical register in case
2023 // the recoloring fails.
2024 DenseMap<unsigned, unsigned> VirtRegToPhysReg;
2025 // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in
2026 // this recoloring "session".
2027 FixedRegisters.insert(VirtReg.reg);
2028
2029 Order.rewind();
2030 while (unsigned PhysReg = Order.next()) {
2031 DEBUG(dbgs() << "Try to assign: " << VirtReg << " to "
2032 << PrintReg(PhysReg, TRI) << '\n');
2033 RecoloringCandidates.clear();
2034 VirtRegToPhysReg.clear();
2035
2036 // It is only possible to recolor virtual register interference.
2037 if (Matrix->checkInterference(VirtReg, PhysReg) >
2038 LiveRegMatrix::IK_VirtReg) {
2039 DEBUG(dbgs() << "Some inteferences are not with virtual registers.\n");
2040
2041 continue;
2042 }
2043
2044 // Early give up on this PhysReg if it is obvious we cannot recolor all
2045 // the interferences.
2046 if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
2047 FixedRegisters)) {
2048 DEBUG(dbgs() << "Some inteferences cannot be recolored.\n");
2049 continue;
2050 }
2051
2052 // RecoloringCandidates contains all the virtual registers that interfer
2053 // with VirtReg on PhysReg (or one of its aliases).
2054 // Enqueue them for recoloring and perform the actual recoloring.
2055 PQueue RecoloringQueue;
2056 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2057 EndIt = RecoloringCandidates.end();
2058 It != EndIt; ++It) {
2059 unsigned ItVirtReg = (*It)->reg;
2060 enqueue(RecoloringQueue, *It);
2061 assert(VRM->hasPhys(ItVirtReg) &&
2062 "Interferences are supposed to be with allocated vairables");
2063
2064 // Record the current allocation.
2065 VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg);
2066 // unset the related struct.
2067 Matrix->unassign(**It);
2068 }
2069
2070 // Do as if VirtReg was assigned to PhysReg so that the underlying
2071 // recoloring has the right information about the interferes and
2072 // available colors.
2073 Matrix->assign(VirtReg, PhysReg);
2074
2075 // Save the current recoloring state.
2076 // If we cannot recolor all the interferences, we will have to start again
2077 // at this point for the next physical register.
2078 SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
2079 if (tryRecoloringCandidates(RecoloringQueue, NewVRegs, FixedRegisters,
2080 Depth)) {
2081 // Do not mess up with the global assignment process.
2082 // I.e., VirtReg must be unassigned.
2083 Matrix->unassign(VirtReg);
2084 return PhysReg;
2085 }
2086
2087 DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to "
2088 << PrintReg(PhysReg, TRI) << '\n');
2089
2090 // The recoloring attempt failed, undo the changes.
2091 FixedRegisters = SaveFixedRegisters;
2092 Matrix->unassign(VirtReg);
2093
2094 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2095 EndIt = RecoloringCandidates.end();
2096 It != EndIt; ++It) {
2097 unsigned ItVirtReg = (*It)->reg;
2098 if (VRM->hasPhys(ItVirtReg))
2099 Matrix->unassign(**It);
2100 Matrix->assign(**It, VirtRegToPhysReg[ItVirtReg]);
2101 }
2102 }
2103
2104 // Last chance recoloring did not worked either, give up.
2105 return ~0u;
2106}
2107
2108/// tryRecoloringCandidates - Try to assign a new color to every register
2109/// in \RecoloringQueue.
2110/// \p NewRegs will contain any new virtual register created during the
2111/// recoloring process.
2112/// \p FixedRegisters[in/out] contains all the registers that have been
2113/// recolored.
2114/// \return true if all virtual registers in RecoloringQueue were successfully
2115/// recolored, false otherwise.
2116bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
2117 SmallVectorImpl<unsigned> &NewVRegs,
2118 SmallVirtRegSet &FixedRegisters,
2119 unsigned Depth) {
2120 while (!RecoloringQueue.empty()) {
2121 LiveInterval *LI = dequeue(RecoloringQueue);
2122 DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
2123 unsigned PhysReg;
2124 PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters, Depth + 1);
2125 if (PhysReg == ~0u || !PhysReg)
2126 return false;
2127 DEBUG(dbgs() << "Recoloring of " << *LI
2128 << " succeeded with: " << PrintReg(PhysReg, TRI) << '\n');
2129 Matrix->assign(*LI, PhysReg);
2130 FixedRegisters.insert(LI->reg);
2131 }
2132 return true;
2133}
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00002134
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00002135//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00002136// Main Entry Point
2137//===----------------------------------------------------------------------===//
2138
2139unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Mark Lacey1feb5852013-08-14 23:50:04 +00002140 SmallVectorImpl<unsigned> &NewVRegs) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07002141 CutOffInfo = CO_None;
2142 LLVMContext &Ctx = MF->getFunction()->getContext();
Stephen Hines36b56882014-04-23 16:57:46 -07002143 SmallVirtRegSet FixedRegisters;
Stephen Hinesdce4a402014-05-29 02:49:00 -07002144 unsigned Reg = selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters);
2145 if (Reg == ~0U && (CutOffInfo != CO_None)) {
2146 uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf);
2147 if (CutOffEncountered == CO_Depth)
2148 Ctx.emitError("register allocation failed: maximum depth for recoloring "
2149 "reached. Use -fexhaustive-register-search to skip "
2150 "cutoffs");
2151 else if (CutOffEncountered == CO_Interf)
2152 Ctx.emitError("register allocation failed: maximum interference for "
2153 "recoloring reached. Use -fexhaustive-register-search "
2154 "to skip cutoffs");
2155 else if (CutOffEncountered == (CO_Depth | CO_Interf))
2156 Ctx.emitError("register allocation failed: maximum interference and "
2157 "depth for recoloring reached. Use "
2158 "-fexhaustive-register-search to skip cutoffs");
2159 }
2160 return Reg;
Stephen Hines36b56882014-04-23 16:57:46 -07002161}
2162
2163/// Using a CSR for the first time has a cost because it causes push|pop
2164/// to be added to prologue|epilogue. Splitting a cold section of the live
2165/// range can have lower cost than using the CSR for the first time;
2166/// Spilling a live range in the cold path can have lower cost than using
2167/// the CSR for the first time. Returns the physical register if we decide
2168/// to use the CSR; otherwise return 0.
2169unsigned RAGreedy::tryAssignCSRFirstTime(LiveInterval &VirtReg,
2170 AllocationOrder &Order,
2171 unsigned PhysReg,
2172 unsigned &CostPerUseLimit,
2173 SmallVectorImpl<unsigned> &NewVRegs) {
Stephen Hines36b56882014-04-23 16:57:46 -07002174 if (getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) {
2175 // We choose spill over using the CSR for the first time if the spill cost
2176 // is lower than CSRCost.
2177 SA->analyze(&VirtReg);
2178 if (calcSpillCost() >= CSRCost)
2179 return PhysReg;
2180
2181 // We are going to spill, set CostPerUseLimit to 1 to make sure that
2182 // we will not use a callee-saved register in tryEvict.
2183 CostPerUseLimit = 1;
2184 return 0;
2185 }
2186 if (getStage(VirtReg) < RS_Split) {
2187 // We choose pre-splitting over using the CSR for the first time if
2188 // the cost of splitting is lower than CSRCost.
2189 SA->analyze(&VirtReg);
2190 unsigned NumCands = 0;
Stephen Hinesdce4a402014-05-29 02:49:00 -07002191 BlockFrequency BestCost = CSRCost; // Don't modify CSRCost.
2192 unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
2193 NumCands, true /*IgnoreCSR*/);
Stephen Hines36b56882014-04-23 16:57:46 -07002194 if (BestCand == NoCand)
2195 // Use the CSR if we can't find a region split below CSRCost.
2196 return PhysReg;
2197
2198 // Perform the actual pre-splitting.
2199 doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs);
2200 return 0;
2201 }
2202 return PhysReg;
2203}
2204
Stephen Hinesdce4a402014-05-29 02:49:00 -07002205void RAGreedy::initializeCSRCost() {
2206 // We use the larger one out of the command-line option and the value report
2207 // by TRI.
2208 CSRCost = BlockFrequency(
2209 std::max((unsigned)CSRFirstTimeCost, TRI->getCSRFirstUseCost()));
2210 if (!CSRCost.getFrequency())
2211 return;
2212
2213 // Raw cost is relative to Entry == 2^14; scale it appropriately.
2214 uint64_t ActualEntry = MBFI->getEntryFreq();
2215 if (!ActualEntry) {
2216 CSRCost = 0;
2217 return;
2218 }
2219 uint64_t FixedEntry = 1 << 14;
2220 if (ActualEntry < FixedEntry)
2221 CSRCost *= BranchProbability(ActualEntry, FixedEntry);
2222 else if (ActualEntry <= UINT32_MAX)
2223 // Invert the fraction and divide.
2224 CSRCost /= BranchProbability(FixedEntry, ActualEntry);
2225 else
2226 // Can't use BranchProbability in general, since it takes 32-bit numbers.
2227 CSRCost = CSRCost.getFrequency() * (ActualEntry / FixedEntry);
2228}
2229
Stephen Hines36b56882014-04-23 16:57:46 -07002230unsigned RAGreedy::selectOrSplitImpl(LiveInterval &VirtReg,
2231 SmallVectorImpl<unsigned> &NewVRegs,
2232 SmallVirtRegSet &FixedRegisters,
2233 unsigned Depth) {
2234 unsigned CostPerUseLimit = ~0u;
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00002235 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00002236 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Stephen Hines36b56882014-04-23 16:57:46 -07002237 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs)) {
2238 // We check other options if we are using a CSR for the first time.
2239 bool CSRFirstUse = false;
2240 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
2241 if (!MRI->isPhysRegUsed(CSR))
2242 CSRFirstUse = true;
2243
2244 // When NewVRegs is not empty, we may have made decisions such as evicting
2245 // a virtual register, go with the earlier decisions and use the physical
2246 // register.
Stephen Hinesdce4a402014-05-29 02:49:00 -07002247 if (CSRCost.getFrequency() && CSRFirstUse && NewVRegs.empty()) {
Stephen Hines36b56882014-04-23 16:57:46 -07002248 unsigned CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
2249 CostPerUseLimit, NewVRegs);
2250 if (CSRReg || !NewVRegs.empty())
2251 // Return now if we decide to use a CSR or create new vregs due to
2252 // pre-splitting.
2253 return CSRReg;
2254 } else
2255 return PhysReg;
2256 }
Andrew Trickb853e6c2010-12-09 18:15:21 +00002257
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00002258 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00002259 DEBUG(dbgs() << StageName[Stage]
2260 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00002261
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00002262 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00002263 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00002264 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00002265 if (Stage != RS_Split)
Stephen Hines36b56882014-04-23 16:57:46 -07002266 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit))
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00002267 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00002268
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00002269 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
2270
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00002271 // The first time we see a live range, don't try to split or spill.
2272 // Wait until the second time, when all smaller ranges have been allocated.
2273 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00002274 if (Stage < RS_Split) {
2275 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00002276 DEBUG(dbgs() << "wait for second round\n");
Mark Lacey1feb5852013-08-14 23:50:04 +00002277 NewVRegs.push_back(VirtReg.reg);
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00002278 return 0;
2279 }
2280
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00002281 // If we couldn't allocate a register from spilling, there is probably some
2282 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00002283 if (Stage >= RS_Done || !VirtReg.isSpillable())
Stephen Hines36b56882014-04-23 16:57:46 -07002284 return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
2285 Depth);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00002286
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00002287 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00002288 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
2289 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00002290 return PhysReg;
2291
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00002292 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00002293 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00002294 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00002295 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00002296 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00002297
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00002298 if (VerifyEnabled)
2299 MF->verify(this, "After spilling");
2300
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00002301 // The live virtual register requesting allocation was spilled, so tell
2302 // the caller not to allocate anything during this round.
2303 return 0;
2304}
2305
2306bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
2307 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
David Blaikie986d76d2012-08-22 17:18:53 +00002308 << "********** Function: " << mf.getName() << '\n');
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00002309
2310 MF = &mf;
Stephen Hines36b56882014-04-23 16:57:46 -07002311 TRI = MF->getTarget().getRegisterInfo();
2312 TII = MF->getTarget().getInstrInfo();
2313 RCI.runOnMachineFunction(mf);
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00002314 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00002315 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00002316
Jakob Stoklund Olesend4348a22012-06-20 22:52:29 +00002317 RegAllocBase::init(getAnalysis<VirtRegMap>(),
2318 getAnalysis<LiveIntervals>(),
2319 getAnalysis<LiveRegMatrix>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00002320 Indexes = &getAnalysis<SlotIndexes>();
Benjamin Kramer4eed7562013-06-17 19:00:36 +00002321 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00002322 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00002323 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00002324 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00002325 Bundles = &getAnalysis<EdgeBundles>();
2326 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00002327 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00002328
Stephen Hinesdce4a402014-05-29 02:49:00 -07002329 initializeCSRCost();
2330
Arnaud A. de Grandmaison095f9942013-11-11 19:04:45 +00002331 calculateSpillWeightsAndHints(*LIS, mf, *Loops, *MBFI);
Arnaud A. de Grandmaisona77da052013-11-10 17:46:31 +00002332
Andrew Trick5dca6132013-07-25 07:26:26 +00002333 DEBUG(LIS->dump());
2334
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00002335 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Benjamin Kramer4eed7562013-06-17 19:00:36 +00002336 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00002337 ExtraRegInfo.clear();
2338 ExtraRegInfo.resize(MRI->getNumVirtRegs());
2339 NextCascade = 1;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00002340 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00002341 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00002342
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00002343 allocatePhysRegs();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00002344 releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00002345 return true;
2346}