blob: 3fa52432209f7b5c3f19f6ca84749413f5c4bf37 [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
15#define DEBUG_TYPE "regalloc"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +000017#include "AllocationOrder.h"
Jakob Stoklund Olesen5907d862011-04-02 06:03:35 +000018#include "InterferenceCache.h"
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +000019#include "LiveDebugVariables.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000020#include "RegAllocBase.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000021#include "SpillPlacement.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000022#include "Spiller.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000023#include "SplitKit.h"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000024#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000025#include "llvm/Analysis/AliasAnalysis.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000026#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000027#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000028#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper789d5d82012-04-02 22:44:18 +000029#include "llvm/CodeGen/LiveRangeEdit.h"
Jakob Stoklund Olesen1ead68d2012-11-28 19:13:06 +000030#include "llvm/CodeGen/LiveRegMatrix.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000031#include "llvm/CodeGen/LiveStackAnalysis.h"
Benjamin Kramer4eed7562013-06-17 19:00:36 +000032#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000033#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000034#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000035#include "llvm/CodeGen/MachineLoopInfo.h"
36#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000037#include "llvm/CodeGen/RegAllocRegistry.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000038#include "llvm/CodeGen/VirtRegMap.h"
39#include "llvm/PassAnalysisSupport.h"
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +000040#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000041#include "llvm/Support/Debug.h"
42#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000043#include "llvm/Support/Timer.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000044#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000045#include <queue>
46
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000047using namespace llvm;
48
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000049STATISTIC(NumGlobalSplits, "Number of split global live ranges");
50STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000051STATISTIC(NumEvicted, "Number of interferences evicted");
52
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +000053static cl::opt<SplitEditor::ComplementSpillMode>
54SplitSpillMode("split-spill-mode", cl::Hidden,
55 cl::desc("Spill mode for splitting live ranges"),
56 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
57 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
58 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
59 clEnumValEnd),
60 cl::init(SplitEditor::SM_Partition));
61
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000062static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
63 createGreedyRegisterAllocator);
64
65namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000066class RAGreedy : public MachineFunctionPass,
67 public RegAllocBase,
68 private LiveRangeEdit::Delegate {
69
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000070 // context
71 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000072
73 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000074 SlotIndexes *Indexes;
Benjamin Kramer4eed7562013-06-17 19:00:36 +000075 MachineBlockFrequencyInfo *MBFI;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000076 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000077 MachineLoopInfo *Loops;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000078 EdgeBundles *Bundles;
79 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +000080 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000081
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000082 // state
Andy Gibbs200241e2013-04-12 10:56:28 +000083 OwningPtr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000084 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +000085 unsigned NextCascade;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000086
87 // Live ranges pass through a number of stages as we try to allocate them.
88 // Some of the stages may also create new live ranges:
89 //
90 // - Region splitting.
91 // - Per-block splitting.
92 // - Local splitting.
93 // - Spilling.
94 //
95 // Ranges produced by one of the stages skip the previous stages when they are
96 // dequeued. This improves performance because we can skip interference checks
97 // that are unlikely to give any results. It also guarantees that the live
98 // range splitting algorithm terminates, something that is otherwise hard to
99 // ensure.
100 enum LiveRangeStage {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000101 /// Newly created live range that has never been queued.
102 RS_New,
103
104 /// Only attempt assignment and eviction. Then requeue as RS_Split.
105 RS_Assign,
106
107 /// Attempt live range splitting if assignment is impossible.
108 RS_Split,
109
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000110 /// Attempt more aggressive live range splitting that is guaranteed to make
111 /// progress. This is used for split products that may not be making
112 /// progress.
113 RS_Split2,
114
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000115 /// Live range will be spilled. No more splitting will be attempted.
116 RS_Spill,
117
118 /// There is nothing more we can do to this live range. Abort compilation
119 /// if it can't be assigned.
120 RS_Done
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000121 };
122
Eli Friedmanae43dac2013-09-10 23:18:14 +0000123#ifndef NDEBUG
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000124 static const char *const StageName[];
Eli Friedmanae43dac2013-09-10 23:18:14 +0000125#endif
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000126
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000127 // RegInfo - Keep additional information about each live range.
128 struct RegInfo {
129 LiveRangeStage Stage;
130
131 // Cascade - Eviction loop prevention. See canEvictInterference().
132 unsigned Cascade;
133
134 RegInfo() : Stage(RS_New), Cascade(0) {}
135 };
136
137 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000138
139 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000140 return ExtraRegInfo[VirtReg.reg].Stage;
141 }
142
143 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
144 ExtraRegInfo.resize(MRI->getNumVirtRegs());
145 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000146 }
147
148 template<typename Iterator>
149 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000150 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000151 for (;Begin != End; ++Begin) {
Mark Lacey1feb5852013-08-14 23:50:04 +0000152 unsigned Reg = *Begin;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000153 if (ExtraRegInfo[Reg].Stage == RS_New)
154 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000155 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000156 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000157
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000158 /// Cost of evicting interference.
159 struct EvictionCost {
160 unsigned BrokenHints; ///< Total number of broken hints.
161 float MaxWeight; ///< Maximum spill weight evicted.
162
163 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
164
Andrew Trick6ea2b962013-07-25 18:35:14 +0000165 bool isMax() const { return BrokenHints == ~0u; }
166
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000167 bool operator<(const EvictionCost &O) const {
168 if (BrokenHints != O.BrokenHints)
169 return BrokenHints < O.BrokenHints;
170 return MaxWeight < O.MaxWeight;
171 }
172 };
173
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000174 // splitting state.
Andy Gibbs200241e2013-04-12 10:56:28 +0000175 OwningPtr<SplitAnalysis> SA;
176 OwningPtr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000177
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000178 /// Cached per-block interference maps
179 InterferenceCache IntfCache;
180
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000181 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000182 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000183
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000184 /// Global live range splitting candidate info.
185 struct GlobalSplitCandidate {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000186 // Register intended for assignment, or 0.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000187 unsigned PhysReg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000188
189 // SplitKit interval index for this candidate.
190 unsigned IntvIdx;
191
192 // Interference for PhysReg.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000193 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000194
195 // Bundles where this candidate should be live.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000196 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000197 SmallVector<unsigned, 8> ActiveBlocks;
198
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000199 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000200 PhysReg = Reg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000201 IntvIdx = 0;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000202 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000203 LiveBundles.clear();
204 ActiveBlocks.clear();
205 }
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000206
207 // Set B[i] = C for every live bundle where B[i] was NoCand.
208 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
209 unsigned Count = 0;
210 for (int i = LiveBundles.find_first(); i >= 0;
211 i = LiveBundles.find_next(i))
212 if (B[i] == NoCand) {
213 B[i] = C;
214 Count++;
215 }
216 return Count;
217 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000218 };
219
220 /// Candidate info for for each PhysReg in AllocationOrder.
221 /// This vector never shrinks, but grows to the size of the largest register
222 /// class.
223 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
224
Reid Kleckner73f615b2013-10-08 20:15:11 +0000225 enum LLVM_ENUM_INT_TYPE(unsigned) { NoCand = ~0u };
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000226
227 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
228 /// NoCand which indicates the stack interval.
229 SmallVector<unsigned, 32> BundleCand;
230
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000231public:
232 RAGreedy();
233
234 /// Return the pass name.
235 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000236 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000237 }
238
239 /// RAGreedy analysis usage.
240 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000241 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000242 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000243 virtual void enqueue(LiveInterval *LI);
244 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000245 virtual unsigned selectOrSplit(LiveInterval&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000246 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000247
248 /// Perform register allocation.
249 virtual bool runOnMachineFunction(MachineFunction &mf);
250
251 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000252
253private:
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000254 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000255 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000256 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000257
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000258 BlockFrequency calcSpillCost();
259 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000260 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000261 void growRegion(GlobalSplitCandidate &Cand);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000262 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000263 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000264 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000265 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Andrew Trick8adae962013-07-25 18:35:19 +0000266 unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000267 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
268 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
269 void evictInterference(LiveInterval&, unsigned,
Mark Lacey1feb5852013-08-14 23:50:04 +0000270 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000271
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000272 unsigned tryAssign(LiveInterval&, AllocationOrder&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000273 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000274 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000275 SmallVectorImpl<unsigned>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000276 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000277 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +0000278 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000279 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +0000280 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000281 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000282 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000283 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000284 unsigned trySplit(LiveInterval&, AllocationOrder&,
Mark Lacey1feb5852013-08-14 23:50:04 +0000285 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000286};
287} // end anonymous namespace
288
289char RAGreedy::ID = 0;
290
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000291#ifndef NDEBUG
292const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000293 "RS_New",
294 "RS_Assign",
295 "RS_Split",
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000296 "RS_Split2",
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000297 "RS_Spill",
298 "RS_Done"
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000299};
300#endif
301
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000302// Hysteresis to use when comparing floats.
303// This helps stabilize decisions based on float comparisons.
304const float Hysteresis = 0.98f;
305
306
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000307FunctionPass* llvm::createGreedyRegisterAllocator() {
308 return new RAGreedy();
309}
310
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000311RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000312 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000313 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000314 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
315 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000316 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Trick42b7a712012-01-17 06:55:03 +0000317 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000318 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
319 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
320 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
321 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
322 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000323 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000324 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
325 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000326}
327
328void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
329 AU.setPreservesCFG();
Benjamin Kramer4eed7562013-06-17 19:00:36 +0000330 AU.addRequired<MachineBlockFrequencyInfo>();
331 AU.addPreserved<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000332 AU.addRequired<AliasAnalysis>();
333 AU.addPreserved<AliasAnalysis>();
334 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000335 AU.addPreserved<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000336 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000337 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000338 AU.addRequired<LiveDebugVariables>();
339 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000340 AU.addRequired<LiveStacks>();
341 AU.addPreserved<LiveStacks>();
Evan Chengbb36a432012-09-21 20:04:28 +0000342 AU.addRequired<CalculateSpillWeights>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000343 AU.addRequired<MachineDominatorTree>();
344 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000345 AU.addRequired<MachineLoopInfo>();
346 AU.addPreserved<MachineLoopInfo>();
347 AU.addRequired<VirtRegMap>();
348 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000349 AU.addRequired<LiveRegMatrix>();
350 AU.addPreserved<LiveRegMatrix>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000351 AU.addRequired<EdgeBundles>();
352 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000353 MachineFunctionPass::getAnalysisUsage(AU);
354}
355
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000356
357//===----------------------------------------------------------------------===//
358// LiveRangeEdit delegate methods
359//===----------------------------------------------------------------------===//
360
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000361bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000362 if (VRM->hasPhys(VirtReg)) {
363 Matrix->unassign(LIS->getInterval(VirtReg));
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000364 return true;
365 }
366 // Unassigned virtreg is probably in the priority queue.
367 // RegAllocBase will erase it after dequeueing.
368 return false;
369}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000370
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000371void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000372 if (!VRM->hasPhys(VirtReg))
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000373 return;
374
375 // Register is assigned, put it back on the queue for reassignment.
376 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000377 Matrix->unassign(LI);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000378 enqueue(&LI);
379}
380
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000381void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen0d4fea72011-09-14 17:34:37 +0000382 // Cloning a register we haven't even heard about yet? Just ignore it.
383 if (!ExtraRegInfo.inBounds(Old))
384 return;
385
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000386 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000387 // be split into connected components. The new components are much smaller
388 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000389 // same stage as the parent.
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000390 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000391 ExtraRegInfo.grow(New);
392 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000393}
394
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000395void RAGreedy::releaseMemory() {
396 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000397 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000398 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000399}
400
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000401void RAGreedy::enqueue(LiveInterval *LI) {
402 // Prioritize live ranges by size, assigning larger ranges first.
403 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000404 const unsigned Size = LI->getSize();
405 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000406 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
407 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000408 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000409
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000410 ExtraRegInfo.grow(Reg);
411 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000412 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000413
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000414 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000415 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000416 // everything else has been allocated.
417 Prio = Size;
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000418 } else {
Andrew Trick6ea2b962013-07-25 18:35:14 +0000419 if (ExtraRegInfo[Reg].Stage == RS_Assign && !LI->empty() &&
420 LIS->intervalIsInOneMBB(*LI)) {
421 // Allocate original local ranges in linear instruction order. Since they
422 // are singly defined, this produces optimal coloring in the absence of
423 // global interference and other constraints.
Andrew Trickc0173e62013-07-30 19:59:19 +0000424 Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
Andrew Trick6ea2b962013-07-25 18:35:14 +0000425 }
426 else {
427 // Allocate global and split ranges in long->short order. Long ranges that
428 // don't fit should be spilled (or split) ASAP so they don't create
429 // interference. Mark a bit to prioritize global above local ranges.
430 Prio = (1u << 29) + Size;
431 }
432 // Mark a higher bit to prioritize global and local above RS_Split.
433 Prio |= (1u << 31);
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000434
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000435 // Boost ranges that have a physical register hint.
Jakob Stoklund Olesenfc637442012-12-03 23:23:50 +0000436 if (VRM->hasKnownPreference(Reg))
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000437 Prio |= (1u << 30);
438 }
Andrew Trickbef4c3e2013-07-25 18:35:22 +0000439 // The virtual register number is a tie breaker for same-sized ranges.
440 // Give lower vreg numbers higher priority to assign them first.
Jakob Stoklund Olesene3b23cd2012-04-02 22:30:39 +0000441 Queue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000442}
443
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000444LiveInterval *RAGreedy::dequeue() {
445 if (Queue.empty())
446 return 0;
Jakob Stoklund Olesene3b23cd2012-04-02 22:30:39 +0000447 LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000448 Queue.pop();
449 return LI;
450}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000451
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000452
453//===----------------------------------------------------------------------===//
454// Direct Assignment
455//===----------------------------------------------------------------------===//
456
457/// tryAssign - Try to assign VirtReg to an available register.
458unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
459 AllocationOrder &Order,
Mark Lacey1feb5852013-08-14 23:50:04 +0000460 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000461 Order.rewind();
462 unsigned PhysReg;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000463 while ((PhysReg = Order.next()))
464 if (!Matrix->checkInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000465 break;
Jakob Stoklund Olesenf7999fe2012-12-04 22:25:16 +0000466 if (!PhysReg || Order.isHint())
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000467 return PhysReg;
468
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000469 // PhysReg is available, but there may be a better choice.
470
471 // If we missed a simple hint, try to cheaply evict interference from the
472 // preferred register.
473 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000474 if (Order.isHint(Hint)) {
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000475 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
476 EvictionCost MaxCost(1);
477 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
478 evictInterference(VirtReg, Hint, NewVRegs);
479 return Hint;
480 }
481 }
482
483 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000484 unsigned Cost = TRI->getCostPerUse(PhysReg);
485
486 // Most registers have 0 additional cost.
487 if (!Cost)
488 return PhysReg;
489
490 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
491 << '\n');
492 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
493 return CheapReg ? CheapReg : PhysReg;
494}
495
496
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000497//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000498// Interference eviction
499//===----------------------------------------------------------------------===//
500
Andrew Trick8adae962013-07-25 18:35:19 +0000501unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
502 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
503 unsigned PhysReg;
504 while ((PhysReg = Order.next())) {
505 if (PhysReg == PrevReg)
506 continue;
507
508 MCRegUnitIterator Units(PhysReg, TRI);
509 for (; Units.isValid(); ++Units) {
510 // Instantiate a "subquery", not to be confused with the Queries array.
511 LiveIntervalUnion::Query subQ(&VirtReg, &Matrix->getLiveUnions()[*Units]);
512 if (subQ.checkInterference())
513 break;
514 }
515 // If no units have interference, break out with the current PhysReg.
516 if (!Units.isValid())
517 break;
518 }
519 if (PhysReg)
520 DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
521 << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
522 << '\n');
523 return PhysReg;
524}
525
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000526/// shouldEvict - determine if A should evict the assigned live range B. The
527/// eviction policy defined by this function together with the allocation order
528/// defined by enqueue() decides which registers ultimately end up being split
529/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000530///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000531/// Cascade numbers are used to prevent infinite loops if this function is a
532/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000533///
534/// @param A The live range to be assigned.
535/// @param IsHint True when A is about to be assigned to its preferred
536/// register.
537/// @param B The live range to be evicted.
538/// @param BreaksHint True when B is already assigned to its preferred register.
539bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
540 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000541 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000542
543 // Be fairly aggressive about following hints as long as the evictee can be
544 // split.
545 if (CanSplit && IsHint && !BreaksHint)
546 return true;
547
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000548 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000549}
550
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000551/// canEvictInterference - Return true if all interferences between VirtReg and
552/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
553///
554/// @param VirtReg Live range that is about to be assigned.
555/// @param PhysReg Desired register for assignment.
Dmitri Gribenko67c89782012-09-12 16:59:47 +0000556/// @param IsHint True when PhysReg is VirtReg's preferred register.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000557/// @param MaxCost Only look for cheaper candidates and update with new cost
558/// when returning true.
559/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000560bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000561 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000562 // It is only possible to evict virtual register interference.
563 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
564 return false;
565
Andrew Trick6ea2b962013-07-25 18:35:14 +0000566 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
567
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000568 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
569 // involved in an eviction before. If a cascade number was assigned, deny
570 // evicting anything with the same or a newer cascade number. This prevents
571 // infinite eviction loops.
572 //
573 // This works out so a register without a cascade number is allowed to evict
574 // anything, and it can be evicted by anything.
575 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
576 if (!Cascade)
577 Cascade = NextCascade;
578
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000579 EvictionCost Cost;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000580 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
581 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000582 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000583 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000584 return false;
585
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000586 // Check if any interfering live range is heavier than MaxWeight.
587 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
588 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000589 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
590 "Only expecting virtual register interference from query");
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000591 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000592 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000593 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000594 // Once a live range becomes small enough, it is urgent that we find a
595 // register for it. This is indicated by an infinite spill weight. These
596 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen9cda1be2012-05-30 21:46:58 +0000597 //
598 // Also allow urgent evictions of unspillable ranges from a strictly
599 // larger allocation order.
600 bool Urgent = !VirtReg.isSpillable() &&
601 (Intf->isSpillable() ||
602 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
603 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000604 // Only evict older cascades or live ranges without a cascade.
605 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
606 if (Cascade <= IntfCascade) {
607 if (!Urgent)
608 return false;
609 // We permit breaking cascades for urgent evictions. It should be the
610 // last resort, though, so make it really expensive.
611 Cost.BrokenHints += 10;
612 }
613 // Would this break a satisfied hint?
614 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
615 // Update eviction cost.
616 Cost.BrokenHints += BreaksHint;
617 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
618 // Abort if this would be too expensive.
619 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000620 return false;
Andrew Trick6ea2b962013-07-25 18:35:14 +0000621 if (Urgent)
622 continue;
623 // If !MaxCost.isMax(), then we're just looking for a cheap register.
624 // Evicting another local live range in this case could lead to suboptimal
625 // coloring.
Andrew Trick8adae962013-07-25 18:35:19 +0000626 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
627 !canReassign(*Intf, PhysReg)) {
Andrew Trick6ea2b962013-07-25 18:35:14 +0000628 return false;
Andrew Trick8adae962013-07-25 18:35:19 +0000629 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000630 // Finally, apply the eviction policy for non-urgent evictions.
Andrew Trick6ea2b962013-07-25 18:35:14 +0000631 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000632 return false;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000633 }
634 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000635 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000636 return true;
637}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000638
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000639/// evictInterference - Evict any interferring registers that prevent VirtReg
640/// from being assigned to Physreg. This assumes that canEvictInterference
641/// returned true.
642void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Mark Lacey1feb5852013-08-14 23:50:04 +0000643 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000644 // Make sure that VirtReg has a cascade number, and assign that cascade
645 // number to every evicted register. These live ranges than then only be
646 // evicted by a newer cascade, preventing infinite loops.
647 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
648 if (!Cascade)
649 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
650
651 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
652 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000653
654 // Collect all interfering virtregs first.
655 SmallVector<LiveInterval*, 8> Intfs;
656 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
657 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000658 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000659 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
660 Intfs.append(IVR.begin(), IVR.end());
661 }
662
663 // Evict them second. This will invalidate the queries.
664 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
665 LiveInterval *Intf = Intfs[i];
666 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
667 if (!VRM->hasPhys(Intf->reg))
668 continue;
669 Matrix->unassign(*Intf);
670 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
671 VirtReg.isSpillable() < Intf->isSpillable()) &&
672 "Cannot decrease cascade number, illegal eviction");
673 ExtraRegInfo[Intf->reg].Cascade = Cascade;
674 ++NumEvicted;
Mark Lacey1feb5852013-08-14 23:50:04 +0000675 NewVRegs.push_back(Intf->reg);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000676 }
677}
678
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000679/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000680/// @param VirtReg Currently unassigned virtual register.
681/// @param Order Physregs to try.
682/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000683unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
684 AllocationOrder &Order,
Mark Lacey1feb5852013-08-14 23:50:04 +0000685 SmallVectorImpl<unsigned> &NewVRegs,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000686 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000687 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
688
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000689 // Keep track of the cheapest interference seen so far.
690 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000691 unsigned BestPhys = 0;
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000692 unsigned OrderLimit = Order.getOrder().size();
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000693
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000694 // When we are just looking for a reduced cost per use, don't break any
695 // hints, and only evict smaller spill weights.
696 if (CostPerUseLimit < ~0u) {
697 BestCost.BrokenHints = 0;
698 BestCost.MaxWeight = VirtReg.weight;
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000699
700 // Check of any registers in RC are below CostPerUseLimit.
701 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
702 unsigned MinCost = RegClassInfo.getMinCost(RC);
703 if (MinCost >= CostPerUseLimit) {
704 DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
705 << ", no cheaper registers to be found.\n");
706 return 0;
707 }
708
709 // It is normal for register classes to have a long tail of registers with
710 // the same cost. We don't need to look at them if they're too expensive.
711 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
712 OrderLimit = RegClassInfo.getLastCostChange(RC);
713 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
714 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000715 }
716
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000717 Order.rewind();
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000718 while (unsigned PhysReg = Order.nextWithDups(OrderLimit)) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000719 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
720 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000721 // The first use of a callee-saved register in a function has cost 1.
722 // Don't start using a CSR when the CostPerUseLimit is low.
723 if (CostPerUseLimit == 1)
724 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
725 if (!MRI->isPhysRegUsed(CSR)) {
726 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
727 << PrintReg(CSR, TRI) << '\n');
728 continue;
729 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000730
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000731 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000732 continue;
733
734 // Best so far.
735 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000736
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000737 // Stop if the hint can be used.
Jakob Stoklund Olesenf7999fe2012-12-04 22:25:16 +0000738 if (Order.isHint())
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000739 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000740 }
741
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000742 if (!BestPhys)
743 return 0;
744
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000745 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000746 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000747}
748
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000749
750//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000751// Region Splitting
752//===----------------------------------------------------------------------===//
753
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000754/// addSplitConstraints - Fill out the SplitConstraints vector based on the
755/// interference pattern in Physreg and its aliases. Add the constraints to
756/// SpillPlacement and return the static cost of this split in Cost, assuming
757/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000758/// Return false if there are no bundles with positive bias.
759bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000760 BlockFrequency &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000761 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000762
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000763 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000764 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000765 BlockFrequency StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000766 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
767 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000768 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000769
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000770 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000771 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000772 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
773 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
David Blaikie453f4f02013-05-15 07:36:59 +0000774 BC.ChangesValue = BI.FirstDef.isValid();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000775
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000776 if (!Intf.hasInterference())
777 continue;
778
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000779 // Number of spill code instructions to insert.
780 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000781
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000782 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000783 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000784 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000785 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000786 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000787 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000788 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000789 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000790 }
791
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000792 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000793 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000794 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000795 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000796 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000797 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000798 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000799 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000800 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000801
802 // Accumulate the total frequency of inserted spill code.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000803 while (Ins--)
804 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000805 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000806 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000807
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000808 // Add constraints for use-blocks. Note that these are the only constraints
809 // that may add a positive bias, it is downhill from here.
810 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000811 return SpillPlacer->scanActiveBundles();
812}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000813
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000814
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000815/// addThroughConstraints - Add constraints and links to SpillPlacer from the
816/// live-through blocks in Blocks.
817void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
818 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000819 const unsigned GroupSize = 8;
820 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000821 unsigned TBS[GroupSize];
822 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000823
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000824 for (unsigned i = 0; i != Blocks.size(); ++i) {
825 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000826 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000827
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000828 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000829 assert(T < GroupSize && "Array overflow");
830 TBS[T] = Number;
831 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000832 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000833 T = 0;
834 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000835 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000836 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000837
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000838 assert(B < GroupSize && "Array overflow");
839 BCS[B].Number = Number;
840
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000841 // Interference for the live-in value.
842 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
843 BCS[B].Entry = SpillPlacement::MustSpill;
844 else
845 BCS[B].Entry = SpillPlacement::PrefSpill;
846
847 // Interference for the live-out value.
848 if (Intf.last() >= SA->getLastSplitPoint(Number))
849 BCS[B].Exit = SpillPlacement::MustSpill;
850 else
851 BCS[B].Exit = SpillPlacement::PrefSpill;
852
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000853 if (++B == GroupSize) {
854 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
855 SpillPlacer->addConstraints(Array);
856 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000857 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000858 }
859
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000860 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
861 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000862 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000863}
864
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000865void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000866 // Keep track of through blocks that have not been added to SpillPlacer.
867 BitVector Todo = SA->getThroughBlocks();
868 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
869 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000870#ifndef NDEBUG
871 unsigned Visited = 0;
872#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000873
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000874 for (;;) {
875 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000876 // Find new through blocks in the periphery of PrefRegBundles.
877 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
878 unsigned Bundle = NewBundles[i];
879 // Look at all blocks connected to Bundle in the full graph.
880 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
881 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
882 I != E; ++I) {
883 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000884 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000885 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000886 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000887 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000888 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000889#ifndef NDEBUG
890 ++Visited;
891#endif
892 }
893 }
894 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000895 if (ActiveBlocks.size() == AddedTo)
896 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000897
898 // Compute through constraints from the interference, or assume that all
899 // through blocks prefer spilling when forming compact regions.
900 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
901 if (Cand.PhysReg)
902 addThroughConstraints(Cand.Intf, NewBlocks);
903 else
Jakob Stoklund Olesenb87f91b2011-08-03 23:09:38 +0000904 // Provide a strong negative bias on through blocks to prevent unwanted
905 // liveness on loop backedges.
906 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000907 AddedTo = ActiveBlocks.size();
908
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000909 // Perhaps iterating can enable more bundles?
910 SpillPlacer->iterate();
911 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000912 DEBUG(dbgs() << ", v=" << Visited);
913}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000914
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000915/// calcCompactRegion - Compute the set of edge bundles that should be live
916/// when splitting the current live range into compact regions. Compact
917/// regions can be computed without looking at interference. They are the
918/// regions formed by removing all the live-through blocks from the live range.
919///
920/// Returns false if the current live range is already compact, or if the
921/// compact regions would form single block regions anyway.
922bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
923 // Without any through blocks, the live range is already compact.
924 if (!SA->getNumThroughBlocks())
925 return false;
926
927 // Compact regions don't correspond to any physreg.
928 Cand.reset(IntfCache, 0);
929
930 DEBUG(dbgs() << "Compact region bundles");
931
932 // Use the spill placer to determine the live bundles. GrowRegion pretends
933 // that all the through blocks have interference when PhysReg is unset.
934 SpillPlacer->prepare(Cand.LiveBundles);
935
936 // The static split cost will be zero since Cand.Intf reports no interference.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000937 BlockFrequency Cost;
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000938 if (!addSplitConstraints(Cand.Intf, Cost)) {
939 DEBUG(dbgs() << ", none.\n");
940 return false;
941 }
942
943 growRegion(Cand);
944 SpillPlacer->finish();
945
946 if (!Cand.LiveBundles.any()) {
947 DEBUG(dbgs() << ", none.\n");
948 return false;
949 }
950
951 DEBUG({
952 for (int i = Cand.LiveBundles.find_first(); i>=0;
953 i = Cand.LiveBundles.find_next(i))
954 dbgs() << " EB#" << i;
955 dbgs() << ".\n";
956 });
957 return true;
958}
959
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000960/// calcSpillCost - Compute how expensive it would be to split the live range in
961/// SA around all use blocks instead of forming bundle regions.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000962BlockFrequency RAGreedy::calcSpillCost() {
963 BlockFrequency Cost = 0;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000964 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
965 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
966 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
967 unsigned Number = BI.MBB->getNumber();
968 // We normally only need one spill instruction - a load or a store.
969 Cost += SpillPlacer->getBlockFrequency(Number);
970
971 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3f5beed2011-08-02 23:04:08 +0000972 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
973 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000974 }
975 return Cost;
976}
977
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000978/// calcGlobalSplitCost - Return the global split cost of following the split
979/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000980/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000981///
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000982BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
983 BlockFrequency GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000984 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000985 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
986 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
987 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000988 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000989 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
990 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
991 unsigned Ins = 0;
992
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000993 if (BI.LiveIn)
994 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
995 if (BI.LiveOut)
996 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +0000997 while (Ins--)
998 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000999 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001000
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001001 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1002 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001003 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
1004 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +00001005 if (!RegIn && !RegOut)
1006 continue;
1007 if (RegIn && RegOut) {
1008 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001009 Cand.Intf.moveToBlock(Number);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001010 if (Cand.Intf.hasInterference()) {
1011 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1012 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1013 }
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +00001014 continue;
1015 }
1016 // live-in / stack-out or stack-in live-out.
1017 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001018 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001019 return GlobalCost;
1020}
1021
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001022/// splitAroundRegion - Split the current live range around the regions
1023/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001024///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001025/// Before calling this function, GlobalCand and BundleCand must be initialized
1026/// so each bundle is assigned to a valid candidate, or NoCand for the
1027/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1028/// objects must be initialized for the current live range, and intervals
1029/// created for the used candidates.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001030///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001031/// @param LREdit The LiveRangeEdit object handling the current split.
1032/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1033/// must appear in this list.
1034void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1035 ArrayRef<unsigned> UsedCands) {
1036 // These are the intervals created for new global ranges. We may create more
1037 // intervals for local ranges.
1038 const unsigned NumGlobalIntvs = LREdit.size();
1039 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1040 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001041
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001042 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen69145ba2011-08-06 18:20:24 +00001043 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001044 // is all copies.
1045 unsigned Reg = SA->getParent().reg;
1046 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1047
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +00001048 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001049 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1050 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1051 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001052 unsigned Number = BI.MBB->getNumber();
1053 unsigned IntvIn = 0, IntvOut = 0;
1054 SlotIndex IntfIn, IntfOut;
1055 if (BI.LiveIn) {
1056 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1057 if (CandIn != NoCand) {
1058 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1059 IntvIn = Cand.IntvIdx;
1060 Cand.Intf.moveToBlock(Number);
1061 IntfIn = Cand.Intf.first();
1062 }
1063 }
1064 if (BI.LiveOut) {
1065 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1066 if (CandOut != NoCand) {
1067 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1068 IntvOut = Cand.IntvIdx;
1069 Cand.Intf.moveToBlock(Number);
1070 IntfOut = Cand.Intf.last();
1071 }
1072 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001073
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001074 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001075 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001076 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001077 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +00001078 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001079 continue;
1080 }
1081
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001082 if (IntvIn && IntvOut)
1083 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1084 else if (IntvIn)
1085 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +00001086 else
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001087 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001088 }
1089
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001090 // Handle live-through blocks. The relevant live-through blocks are stored in
1091 // the ActiveBlocks list with each candidate. We need to filter out
1092 // duplicates.
1093 BitVector Todo = SA->getThroughBlocks();
1094 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1095 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1096 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1097 unsigned Number = Blocks[i];
1098 if (!Todo.test(Number))
1099 continue;
1100 Todo.reset(Number);
1101
1102 unsigned IntvIn = 0, IntvOut = 0;
1103 SlotIndex IntfIn, IntfOut;
1104
1105 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1106 if (CandIn != NoCand) {
1107 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1108 IntvIn = Cand.IntvIdx;
1109 Cand.Intf.moveToBlock(Number);
1110 IntfIn = Cand.Intf.first();
1111 }
1112
1113 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1114 if (CandOut != NoCand) {
1115 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1116 IntvOut = Cand.IntvIdx;
1117 Cand.Intf.moveToBlock(Number);
1118 IntfOut = Cand.Intf.last();
1119 }
1120 if (!IntvIn && !IntvOut)
1121 continue;
1122 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1123 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001124 }
1125
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001126 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001127
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001128 SmallVector<unsigned, 8> IntvMap;
1129 SE->finish(&IntvMap);
Mark Lacey1feb5852013-08-14 23:50:04 +00001130 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001131
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001132 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +00001133 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001134
1135 // Sort out the new intervals created by splitting. We get four kinds:
1136 // - Remainder intervals should not be split again.
1137 // - Candidate intervals can be assigned to Cand.PhysReg.
1138 // - Block-local splits are candidates for local splitting.
1139 // - DCE leftovers should go back on the queue.
1140 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Lacey1feb5852013-08-14 23:50:04 +00001141 LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001142
1143 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001144 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001145 continue;
1146
1147 // Remainder interval. Don't try splitting again, spill if it doesn't
1148 // allocate.
1149 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001150 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001151 continue;
1152 }
1153
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001154 // Global intervals. Allow repeated splitting as long as the number of live
1155 // blocks is strictly decreasing.
1156 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001157 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001158 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1159 << " blocks as original.\n");
1160 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001161 setStage(Reg, RS_Split2);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001162 }
1163 continue;
1164 }
1165
1166 // Other intervals are treated as new. This includes local intervals created
1167 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001168 }
1169
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001170 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001171 MF->verify(this, "After splitting live range around region");
1172}
1173
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001174unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Lacey1feb5852013-08-14 23:50:04 +00001175 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001176 unsigned NumCands = 0;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001177 unsigned BestCand = NoCand;
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001178 BlockFrequency BestCost;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001179 SmallVector<unsigned, 8> UsedCands;
1180
1181 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +00001182 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001183 if (HasCompact) {
1184 // Yes, keep GlobalCand[0] as the compact region candidate.
1185 NumCands = 1;
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001186 BestCost = BlockFrequency::getMaxFrequency();
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001187 } else {
1188 // No benefit from the compact region, our fallback will be per-block
1189 // splitting. Make sure we find a solution that is cheaper than spilling.
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001190 BestCost = calcSpillCost();
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001191 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1192 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001193
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001194 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001195 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001196 // Discard bad candidates before we run out of interference cache cursors.
1197 // This will only affect register classes with a lot of registers (>32).
1198 if (NumCands == IntfCache.getMaxCursors()) {
1199 unsigned WorstCount = ~0u;
1200 unsigned Worst = 0;
1201 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001202 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001203 continue;
1204 unsigned Count = GlobalCand[i].LiveBundles.count();
1205 if (Count < WorstCount)
1206 Worst = i, WorstCount = Count;
1207 }
1208 --NumCands;
1209 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen7bdf0062011-11-01 00:02:31 +00001210 if (BestCand == NumCands)
1211 BestCand = Worst;
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001212 }
1213
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001214 if (GlobalCand.size() <= NumCands)
1215 GlobalCand.resize(NumCands+1);
1216 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1217 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001218
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001219 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001220 BlockFrequency Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001221 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001222 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001223 continue;
1224 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001225 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001226 if (Cost >= BestCost) {
1227 DEBUG({
1228 if (BestCand == NoCand)
1229 dbgs() << " worse than no bundles\n";
1230 else
1231 dbgs() << " worse than "
1232 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1233 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001234 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001235 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001236 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001237
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001238 SpillPlacer->finish();
1239
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001240 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001241 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001242 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001243 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001244 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001245
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001246 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001247 DEBUG({
1248 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001249 for (int i = Cand.LiveBundles.find_first(); i>=0;
1250 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001251 dbgs() << " EB#" << i;
1252 dbgs() << ".\n";
1253 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001254 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001255 BestCand = NumCands;
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001256 BestCost = Cost;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001257 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001258 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001259 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001260
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001261 // No solutions found, fall back to single block splitting.
1262 if (!HasCompact && BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001263 return 0;
1264
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001265 // Prepare split editor.
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001266 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001267 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001268
1269 // Assign all edge bundles to the preferred candidate, or NoCand.
1270 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1271
1272 // Assign bundles for the best candidate region.
1273 if (BestCand != NoCand) {
1274 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1275 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1276 UsedCands.push_back(BestCand);
1277 Cand.IntvIdx = SE->openIntv();
1278 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1279 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001280 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001281 }
1282 }
1283
1284 // Assign bundles for the compact region.
1285 if (HasCompact) {
1286 GlobalSplitCandidate &Cand = GlobalCand.front();
1287 assert(!Cand.PhysReg && "Compact region has no physreg");
1288 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1289 UsedCands.push_back(0);
1290 Cand.IntvIdx = SE->openIntv();
1291 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1292 << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001293 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001294 }
1295 }
1296
1297 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001298 return 0;
1299}
1300
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001301
1302//===----------------------------------------------------------------------===//
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001303// Per-Block Splitting
1304//===----------------------------------------------------------------------===//
1305
1306/// tryBlockSplit - Split a global live range around every block with uses. This
1307/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1308/// they don't allocate.
1309unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Lacey1feb5852013-08-14 23:50:04 +00001310 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001311 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1312 unsigned Reg = VirtReg.reg;
1313 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001314 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001315 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001316 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1317 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1318 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1319 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1320 SE->splitSingleBlock(BI);
1321 }
1322 // No blocks were split.
1323 if (LREdit.empty())
1324 return 0;
1325
1326 // We did split for some blocks.
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001327 SmallVector<unsigned, 8> IntvMap;
1328 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001329
1330 // Tell LiveDebugVariables about the new ranges.
Mark Lacey1feb5852013-08-14 23:50:04 +00001331 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001332
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001333 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1334
1335 // Sort out the new intervals created by splitting. The remainder interval
1336 // goes straight to spilling, the new local ranges get to stay RS_New.
1337 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Lacey1feb5852013-08-14 23:50:04 +00001338 LiveInterval &LI = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001339 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1340 setStage(LI, RS_Spill);
1341 }
1342
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001343 if (VerifyEnabled)
1344 MF->verify(this, "After splitting live range around basic blocks");
1345 return 0;
1346}
1347
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001348
1349//===----------------------------------------------------------------------===//
1350// Per-Instruction Splitting
1351//===----------------------------------------------------------------------===//
1352
1353/// tryInstructionSplit - Split a live range around individual instructions.
1354/// This is normally not worthwhile since the spiller is doing essentially the
1355/// same thing. However, when the live range is in a constrained register
1356/// class, it may help to insert copies such that parts of the live range can
1357/// be moved to a larger register class.
1358///
1359/// This is similar to spilling to a larger register class.
1360unsigned
1361RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Lacey1feb5852013-08-14 23:50:04 +00001362 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001363 // There is no point to this if there are no larger sub-classes.
1364 if (!RegClassInfo.isProperSubClass(MRI->getRegClass(VirtReg.reg)))
1365 return 0;
1366
1367 // Always enable split spill mode, since we're effectively spilling to a
1368 // register.
1369 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1370 SE->reset(LREdit, SplitEditor::SM_Size);
1371
1372 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1373 if (Uses.size() <= 1)
1374 return 0;
1375
1376 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1377
1378 // Split around every non-copy instruction.
1379 for (unsigned i = 0; i != Uses.size(); ++i) {
1380 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1381 if (MI->isFullCopy()) {
1382 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1383 continue;
1384 }
1385 SE->openIntv();
1386 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1387 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1388 SE->useIntv(SegStart, SegStop);
1389 }
1390
1391 if (LREdit.empty()) {
1392 DEBUG(dbgs() << "All uses were copies.\n");
1393 return 0;
1394 }
1395
1396 SmallVector<unsigned, 8> IntvMap;
1397 SE->finish(&IntvMap);
Mark Lacey1feb5852013-08-14 23:50:04 +00001398 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001399 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1400
1401 // Assign all new registers to RS_Spill. This was the last chance.
1402 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1403 return 0;
1404}
1405
1406
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001407//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001408// Local Splitting
1409//===----------------------------------------------------------------------===//
1410
1411
1412/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1413/// in order to use PhysReg between two entries in SA->UseSlots.
1414///
1415/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1416///
1417void RAGreedy::calcGapWeights(unsigned PhysReg,
1418 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001419 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1420 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001421 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001422 const unsigned NumGaps = Uses.size()-1;
1423
1424 // Start and end points for the interference check.
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001425 SlotIndex StartIdx =
1426 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1427 SlotIndex StopIdx =
1428 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001429
1430 GapWeight.assign(NumGaps, 0.0f);
1431
1432 // Add interference from each overlapping register.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001433 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1434 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1435 .checkInterference())
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001436 continue;
1437
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001438 // We know that VirtReg is a continuous interval from FirstInstr to
1439 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001440 //
1441 // Interference that overlaps an instruction is counted in both gaps
1442 // surrounding the instruction. The exception is interference before
1443 // StartIdx and after StopIdx.
1444 //
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001445 LiveIntervalUnion::SegmentIter IntI =
1446 Matrix->getLiveUnions()[*Units] .find(StartIdx);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001447 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1448 // Skip the gaps before IntI.
1449 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1450 if (++Gap == NumGaps)
1451 break;
1452 if (Gap == NumGaps)
1453 break;
1454
1455 // Update the gaps covered by IntI.
1456 const float weight = IntI.value()->weight;
1457 for (; Gap != NumGaps; ++Gap) {
1458 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1459 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1460 break;
1461 }
1462 if (Gap == NumGaps)
1463 break;
1464 }
1465 }
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001466
1467 // Add fixed interference.
1468 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1469 const LiveInterval &LI = LIS->getRegUnit(*Units);
1470 LiveInterval::const_iterator I = LI.find(StartIdx);
1471 LiveInterval::const_iterator E = LI.end();
1472
1473 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1474 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1475 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1476 if (++Gap == NumGaps)
1477 break;
1478 if (Gap == NumGaps)
1479 break;
1480
1481 for (; Gap != NumGaps; ++Gap) {
1482 GapWeight[Gap] = HUGE_VALF;
1483 if (Uses[Gap+1].getBaseIndex() >= I->end)
1484 break;
1485 }
1486 if (Gap == NumGaps)
1487 break;
1488 }
1489 }
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001490}
1491
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001492/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1493/// basic block.
1494///
1495unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Lacey1feb5852013-08-14 23:50:04 +00001496 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001497 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1498 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001499
1500 // Note that it is possible to have an interval that is live-in or live-out
1501 // while only covering a single block - A phi-def can use undef values from
1502 // predecessors, and the block could be a single-block loop.
1503 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001504 // that the interval is continuous from FirstInstr to LastInstr. We should
1505 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001506
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001507 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001508 if (Uses.size() <= 2)
1509 return 0;
1510 const unsigned NumGaps = Uses.size()-1;
1511
1512 DEBUG({
1513 dbgs() << "tryLocalSplit: ";
1514 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001515 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001516 dbgs() << '\n';
1517 });
1518
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001519 // If VirtReg is live across any register mask operands, compute a list of
1520 // gaps with register masks.
1521 SmallVector<unsigned, 8> RegMaskGaps;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001522 if (Matrix->checkRegMaskInterference(VirtReg)) {
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001523 // Get regmask slots for the whole block.
1524 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001525 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001526 // Constrain to VirtReg's live range.
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001527 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1528 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001529 unsigned re = RMS.size();
1530 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001531 // Look for Uses[i] <= RMS <= Uses[i+1].
1532 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1533 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001534 continue;
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001535 // Skip a regmask on the same instruction as the last use. It doesn't
1536 // overlap the live range.
1537 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1538 break;
1539 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001540 RegMaskGaps.push_back(i);
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001541 // Advance ri to the next gap. A regmask on one of the uses counts in
1542 // both gaps.
1543 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1544 ++ri;
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001545 }
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001546 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001547 }
1548
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001549 // Since we allow local split results to be split again, there is a risk of
1550 // creating infinite loops. It is tempting to require that the new live
1551 // ranges have less instructions than the original. That would guarantee
1552 // convergence, but it is too strict. A live range with 3 instructions can be
1553 // split 2+3 (including the COPY), and we want to allow that.
1554 //
1555 // Instead we use these rules:
1556 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001557 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001558 // noop split, of course).
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001559 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001560 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001561 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001562 // smaller ranges are marked RS_New.
1563 //
1564 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1565 // excessive splitting and infinite loops.
1566 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001567 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001568
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001569 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001570 unsigned BestBefore = NumGaps;
1571 unsigned BestAfter = 0;
1572 float BestDiff = 0;
1573
Jakob Stoklund Olesen03ef6002013-07-16 18:26:18 +00001574 const float blockFreq =
1575 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
1576 (1.0f / BlockFrequency::getEntryFrequency());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001577 SmallVector<float, 8> GapWeight;
1578
1579 Order.rewind();
1580 while (unsigned PhysReg = Order.next()) {
1581 // Keep track of the largest spill weight that would need to be evicted in
1582 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1583 calcGapWeights(PhysReg, GapWeight);
1584
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001585 // Remove any gaps with regmask clobbers.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001586 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001587 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1588 GapWeight[RegMaskGaps[i]] = HUGE_VALF;
1589
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001590 // Try to find the best sequence of gaps to close.
1591 // The new spill weight must be larger than any gap interference.
1592
1593 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001594 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001595
1596 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1597 // It is the spill weight that needs to be evicted.
1598 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001599
1600 for (;;) {
1601 // Live before/after split?
1602 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1603 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1604
1605 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1606 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1607 << " i=" << MaxGap);
1608
1609 // Stop before the interval gets so big we wouldn't be making progress.
1610 if (!LiveBefore && !LiveAfter) {
1611 DEBUG(dbgs() << " all\n");
1612 break;
1613 }
1614 // Should the interval be extended or shrunk?
1615 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001616
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001617 // How many gaps would the new range have?
1618 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1619
1620 // Legally, without causing looping?
1621 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1622
1623 if (Legal && MaxGap < HUGE_VALF) {
1624 // Estimate the new spill weight. Each instruction reads or writes the
1625 // register. Conservatively assume there are no read-modify-write
1626 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001627 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001628 // Try to guess the size of the new interval.
1629 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1630 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1631 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001632 // Would this split be possible to allocate?
1633 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001634 DEBUG(dbgs() << " w=" << EstWeight);
1635 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001636 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001637 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001638 if (Diff > BestDiff) {
1639 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001640 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001641 BestBefore = SplitBefore;
1642 BestAfter = SplitAfter;
1643 }
1644 }
1645 }
1646
1647 // Try to shrink.
1648 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001649 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001650 DEBUG(dbgs() << " shrink\n");
1651 // Recompute the max when necessary.
1652 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1653 MaxGap = GapWeight[SplitBefore];
1654 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1655 MaxGap = std::max(MaxGap, GapWeight[i]);
1656 }
1657 continue;
1658 }
1659 MaxGap = 0;
1660 }
1661
1662 // Try to extend the interval.
1663 if (SplitAfter >= NumGaps) {
1664 DEBUG(dbgs() << " end\n");
1665 break;
1666 }
1667
1668 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001669 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001670 }
1671 }
1672
1673 // Didn't find any candidates?
1674 if (BestBefore == NumGaps)
1675 return 0;
1676
1677 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1678 << '-' << Uses[BestAfter] << ", " << BestDiff
1679 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1680
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001681 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001682 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001683
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001684 SE->openIntv();
1685 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1686 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1687 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001688 SmallVector<unsigned, 8> IntvMap;
1689 SE->finish(&IntvMap);
Mark Lacey1feb5852013-08-14 23:50:04 +00001690 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001691
1692 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001693 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001694 // leave the new intervals as RS_New so they can compete.
1695 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1696 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1697 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1698 if (NewGaps >= NumGaps) {
1699 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1700 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001701 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1702 if (IntvMap[i] == 1) {
Mark Lacey1feb5852013-08-14 23:50:04 +00001703 setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
1704 DEBUG(dbgs() << PrintReg(LREdit.get(i)));
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001705 }
1706 DEBUG(dbgs() << '\n');
1707 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001708 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001709
1710 return 0;
1711}
1712
1713//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001714// Live Range Splitting
1715//===----------------------------------------------------------------------===//
1716
1717/// trySplit - Try to split VirtReg or one of its interferences, making it
1718/// assignable.
1719/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1720unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Lacey1feb5852013-08-14 23:50:04 +00001721 SmallVectorImpl<unsigned>&NewVRegs) {
Jakob Stoklund Olesenccfa4462011-08-05 23:50:33 +00001722 // Ranges must be Split2 or less.
1723 if (getStage(VirtReg) >= RS_Spill)
1724 return 0;
1725
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001726 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001727 if (LIS->intervalIsInOneMBB(VirtReg)) {
1728 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001729 SA->analyze(&VirtReg);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001730 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1731 if (PhysReg || !NewVRegs.empty())
1732 return PhysReg;
1733 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001734 }
1735
1736 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001737
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001738 SA->analyze(&VirtReg);
1739
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001740 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1741 // coalescer. That may cause the range to become allocatable which means that
1742 // tryRegionSplit won't be making progress. This check should be replaced with
1743 // an assertion when the coalescer is fixed.
1744 if (SA->didRepairRange()) {
1745 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001746 Matrix->invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001747 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1748 return PhysReg;
1749 }
1750
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001751 // First try to split around a region spanning multiple blocks. RS_Split2
1752 // ranges already made dubious progress with region splitting, so they go
1753 // straight to single block splitting.
1754 if (getStage(VirtReg) < RS_Split2) {
1755 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1756 if (PhysReg || !NewVRegs.empty())
1757 return PhysReg;
1758 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001759
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001760 // Then isolate blocks.
1761 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001762}
1763
1764
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001765//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001766// Main Entry Point
1767//===----------------------------------------------------------------------===//
1768
1769unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Mark Lacey1feb5852013-08-14 23:50:04 +00001770 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001771 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001772 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001773 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1774 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001775
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001776 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001777 DEBUG(dbgs() << StageName[Stage]
1778 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001779
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001780 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001781 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001782 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001783 if (Stage != RS_Split)
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001784 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1785 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001786
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001787 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1788
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001789 // The first time we see a live range, don't try to split or spill.
1790 // Wait until the second time, when all smaller ranges have been allocated.
1791 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001792 if (Stage < RS_Split) {
1793 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001794 DEBUG(dbgs() << "wait for second round\n");
Mark Lacey1feb5852013-08-14 23:50:04 +00001795 NewVRegs.push_back(VirtReg.reg);
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001796 return 0;
1797 }
1798
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001799 // If we couldn't allocate a register from spilling, there is probably some
1800 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001801 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001802 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001803
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001804 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001805 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1806 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001807 return PhysReg;
1808
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001809 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001810 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001811 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001812 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001813 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001814
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001815 if (VerifyEnabled)
1816 MF->verify(this, "After spilling");
1817
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001818 // The live virtual register requesting allocation was spilled, so tell
1819 // the caller not to allocate anything during this round.
1820 return 0;
1821}
1822
1823bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1824 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
David Blaikie986d76d2012-08-22 17:18:53 +00001825 << "********** Function: " << mf.getName() << '\n');
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001826
1827 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001828 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001829 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001830
Jakob Stoklund Olesend4348a22012-06-20 22:52:29 +00001831 RegAllocBase::init(getAnalysis<VirtRegMap>(),
1832 getAnalysis<LiveIntervals>(),
1833 getAnalysis<LiveRegMatrix>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001834 Indexes = &getAnalysis<SlotIndexes>();
Benjamin Kramer4eed7562013-06-17 19:00:36 +00001835 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001836 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001837 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001838 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001839 Bundles = &getAnalysis<EdgeBundles>();
1840 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001841 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001842
Andrew Trick5dca6132013-07-25 07:26:26 +00001843 DEBUG(LIS->dump());
1844
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001845 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Benjamin Kramer4eed7562013-06-17 19:00:36 +00001846 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001847 ExtraRegInfo.clear();
1848 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1849 NextCascade = 1;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001850 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001851 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001852
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001853 allocatePhysRegs();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001854 releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001855 return true;
1856}