blob: bdcef6ff12221ac3a85ea7f89109a5eefffafb0d [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
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000123 static const char *const StageName[];
124
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000125 // RegInfo - Keep additional information about each live range.
126 struct RegInfo {
127 LiveRangeStage Stage;
128
129 // Cascade - Eviction loop prevention. See canEvictInterference().
130 unsigned Cascade;
131
132 RegInfo() : Stage(RS_New), Cascade(0) {}
133 };
134
135 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000136
137 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000138 return ExtraRegInfo[VirtReg.reg].Stage;
139 }
140
141 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
142 ExtraRegInfo.resize(MRI->getNumVirtRegs());
143 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000144 }
145
146 template<typename Iterator>
147 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000148 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000149 for (;Begin != End; ++Begin) {
150 unsigned Reg = (*Begin)->reg;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000151 if (ExtraRegInfo[Reg].Stage == RS_New)
152 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000153 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000154 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000155
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000156 /// Cost of evicting interference.
157 struct EvictionCost {
158 unsigned BrokenHints; ///< Total number of broken hints.
159 float MaxWeight; ///< Maximum spill weight evicted.
160
161 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
162
163 bool operator<(const EvictionCost &O) const {
164 if (BrokenHints != O.BrokenHints)
165 return BrokenHints < O.BrokenHints;
166 return MaxWeight < O.MaxWeight;
167 }
168 };
169
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000170 // splitting state.
Andy Gibbs200241e2013-04-12 10:56:28 +0000171 OwningPtr<SplitAnalysis> SA;
172 OwningPtr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000173
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000174 /// Cached per-block interference maps
175 InterferenceCache IntfCache;
176
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000177 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000178 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000179
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000180 /// Global live range splitting candidate info.
181 struct GlobalSplitCandidate {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000182 // Register intended for assignment, or 0.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000183 unsigned PhysReg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000184
185 // SplitKit interval index for this candidate.
186 unsigned IntvIdx;
187
188 // Interference for PhysReg.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000189 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000190
191 // Bundles where this candidate should be live.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000192 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000193 SmallVector<unsigned, 8> ActiveBlocks;
194
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000195 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000196 PhysReg = Reg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000197 IntvIdx = 0;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000198 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000199 LiveBundles.clear();
200 ActiveBlocks.clear();
201 }
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000202
203 // Set B[i] = C for every live bundle where B[i] was NoCand.
204 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
205 unsigned Count = 0;
206 for (int i = LiveBundles.find_first(); i >= 0;
207 i = LiveBundles.find_next(i))
208 if (B[i] == NoCand) {
209 B[i] = C;
210 Count++;
211 }
212 return Count;
213 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000214 };
215
216 /// Candidate info for for each PhysReg in AllocationOrder.
217 /// This vector never shrinks, but grows to the size of the largest register
218 /// class.
219 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
220
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000221 enum { NoCand = ~0u };
222
223 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
224 /// NoCand which indicates the stack interval.
225 SmallVector<unsigned, 32> BundleCand;
226
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000227public:
228 RAGreedy();
229
230 /// Return the pass name.
231 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000232 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000233 }
234
235 /// RAGreedy analysis usage.
236 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000237 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000238 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000239 virtual void enqueue(LiveInterval *LI);
240 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000241 virtual unsigned selectOrSplit(LiveInterval&,
242 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000243
244 /// Perform register allocation.
245 virtual bool runOnMachineFunction(MachineFunction &mf);
246
247 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000248
249private:
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000250 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000251 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000252 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000253
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000254 float calcSpillCost();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000255 bool addSplitConstraints(InterferenceCache::Cursor, float&);
256 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000257 void growRegion(GlobalSplitCandidate &Cand);
258 float calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000259 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000260 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000261 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000262 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
263 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
264 void evictInterference(LiveInterval&, unsigned,
265 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000266
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000267 unsigned tryAssign(LiveInterval&, AllocationOrder&,
268 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000269 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000270 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000271 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
272 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +0000273 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
274 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +0000275 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
276 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000277 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
278 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000279 unsigned trySplit(LiveInterval&, AllocationOrder&,
280 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000281};
282} // end anonymous namespace
283
284char RAGreedy::ID = 0;
285
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000286#ifndef NDEBUG
287const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000288 "RS_New",
289 "RS_Assign",
290 "RS_Split",
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000291 "RS_Split2",
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000292 "RS_Spill",
293 "RS_Done"
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000294};
295#endif
296
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000297// Hysteresis to use when comparing floats.
298// This helps stabilize decisions based on float comparisons.
299const float Hysteresis = 0.98f;
300
301
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000302FunctionPass* llvm::createGreedyRegisterAllocator() {
303 return new RAGreedy();
304}
305
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000306RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000307 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000308 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000309 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
310 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000311 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Trick42b7a712012-01-17 06:55:03 +0000312 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000313 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
314 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
315 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
316 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
317 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000318 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000319 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
320 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000321}
322
323void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
324 AU.setPreservesCFG();
Benjamin Kramer4eed7562013-06-17 19:00:36 +0000325 AU.addRequired<MachineBlockFrequencyInfo>();
326 AU.addPreserved<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000327 AU.addRequired<AliasAnalysis>();
328 AU.addPreserved<AliasAnalysis>();
329 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000330 AU.addPreserved<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000331 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000332 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000333 AU.addRequired<LiveDebugVariables>();
334 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000335 AU.addRequired<LiveStacks>();
336 AU.addPreserved<LiveStacks>();
Evan Chengbb36a432012-09-21 20:04:28 +0000337 AU.addRequired<CalculateSpillWeights>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000338 AU.addRequired<MachineDominatorTree>();
339 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000340 AU.addRequired<MachineLoopInfo>();
341 AU.addPreserved<MachineLoopInfo>();
342 AU.addRequired<VirtRegMap>();
343 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000344 AU.addRequired<LiveRegMatrix>();
345 AU.addPreserved<LiveRegMatrix>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000346 AU.addRequired<EdgeBundles>();
347 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000348 MachineFunctionPass::getAnalysisUsage(AU);
349}
350
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000351
352//===----------------------------------------------------------------------===//
353// LiveRangeEdit delegate methods
354//===----------------------------------------------------------------------===//
355
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000356bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000357 if (VRM->hasPhys(VirtReg)) {
358 Matrix->unassign(LIS->getInterval(VirtReg));
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000359 return true;
360 }
361 // Unassigned virtreg is probably in the priority queue.
362 // RegAllocBase will erase it after dequeueing.
363 return false;
364}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000365
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000366void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000367 if (!VRM->hasPhys(VirtReg))
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000368 return;
369
370 // Register is assigned, put it back on the queue for reassignment.
371 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000372 Matrix->unassign(LI);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000373 enqueue(&LI);
374}
375
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000376void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen0d4fea72011-09-14 17:34:37 +0000377 // Cloning a register we haven't even heard about yet? Just ignore it.
378 if (!ExtraRegInfo.inBounds(Old))
379 return;
380
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000381 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000382 // be split into connected components. The new components are much smaller
383 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000384 // same stage as the parent.
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000385 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000386 ExtraRegInfo.grow(New);
387 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000388}
389
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000390void RAGreedy::releaseMemory() {
391 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000392 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000393 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000394}
395
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000396void RAGreedy::enqueue(LiveInterval *LI) {
397 // Prioritize live ranges by size, assigning larger ranges first.
398 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000399 const unsigned Size = LI->getSize();
400 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000401 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
402 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000403 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000404
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000405 ExtraRegInfo.grow(Reg);
406 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000407 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000408
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000409 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000410 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000411 // everything else has been allocated.
412 Prio = Size;
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000413 } else {
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000414 // Everything is allocated in long->short order. Long ranges that don't fit
415 // should be spilled (or split) ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000416 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000417
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000418 // Boost ranges that have a physical register hint.
Jakob Stoklund Olesenfc637442012-12-03 23:23:50 +0000419 if (VRM->hasKnownPreference(Reg))
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000420 Prio |= (1u << 30);
421 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000422
Jakob Stoklund Olesene3b23cd2012-04-02 22:30:39 +0000423 Queue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000424}
425
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000426LiveInterval *RAGreedy::dequeue() {
427 if (Queue.empty())
428 return 0;
Jakob Stoklund Olesene3b23cd2012-04-02 22:30:39 +0000429 LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000430 Queue.pop();
431 return LI;
432}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000433
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000434
435//===----------------------------------------------------------------------===//
436// Direct Assignment
437//===----------------------------------------------------------------------===//
438
439/// tryAssign - Try to assign VirtReg to an available register.
440unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
441 AllocationOrder &Order,
442 SmallVectorImpl<LiveInterval*> &NewVRegs) {
443 Order.rewind();
444 unsigned PhysReg;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000445 while ((PhysReg = Order.next()))
446 if (!Matrix->checkInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000447 break;
Jakob Stoklund Olesenf7999fe2012-12-04 22:25:16 +0000448 if (!PhysReg || Order.isHint())
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000449 return PhysReg;
450
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000451 // PhysReg is available, but there may be a better choice.
452
453 // If we missed a simple hint, try to cheaply evict interference from the
454 // preferred register.
455 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000456 if (Order.isHint(Hint)) {
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000457 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
458 EvictionCost MaxCost(1);
459 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
460 evictInterference(VirtReg, Hint, NewVRegs);
461 return Hint;
462 }
463 }
464
465 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000466 unsigned Cost = TRI->getCostPerUse(PhysReg);
467
468 // Most registers have 0 additional cost.
469 if (!Cost)
470 return PhysReg;
471
472 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
473 << '\n');
474 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
475 return CheapReg ? CheapReg : PhysReg;
476}
477
478
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000479//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000480// Interference eviction
481//===----------------------------------------------------------------------===//
482
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000483/// shouldEvict - determine if A should evict the assigned live range B. The
484/// eviction policy defined by this function together with the allocation order
485/// defined by enqueue() decides which registers ultimately end up being split
486/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000487///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000488/// Cascade numbers are used to prevent infinite loops if this function is a
489/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000490///
491/// @param A The live range to be assigned.
492/// @param IsHint True when A is about to be assigned to its preferred
493/// register.
494/// @param B The live range to be evicted.
495/// @param BreaksHint True when B is already assigned to its preferred register.
496bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
497 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000498 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000499
500 // Be fairly aggressive about following hints as long as the evictee can be
501 // split.
502 if (CanSplit && IsHint && !BreaksHint)
503 return true;
504
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000505 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000506}
507
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000508/// canEvictInterference - Return true if all interferences between VirtReg and
509/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
510///
511/// @param VirtReg Live range that is about to be assigned.
512/// @param PhysReg Desired register for assignment.
Dmitri Gribenko67c89782012-09-12 16:59:47 +0000513/// @param IsHint True when PhysReg is VirtReg's preferred register.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000514/// @param MaxCost Only look for cheaper candidates and update with new cost
515/// when returning true.
516/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000517bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000518 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000519 // It is only possible to evict virtual register interference.
520 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
521 return false;
522
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000523 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
524 // involved in an eviction before. If a cascade number was assigned, deny
525 // evicting anything with the same or a newer cascade number. This prevents
526 // infinite eviction loops.
527 //
528 // This works out so a register without a cascade number is allowed to evict
529 // anything, and it can be evicted by anything.
530 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
531 if (!Cascade)
532 Cascade = NextCascade;
533
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000534 EvictionCost Cost;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000535 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
536 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000537 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000538 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000539 return false;
540
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000541 // Check if any interfering live range is heavier than MaxWeight.
542 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
543 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000544 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
545 "Only expecting virtual register interference from query");
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000546 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000547 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000548 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000549 // Once a live range becomes small enough, it is urgent that we find a
550 // register for it. This is indicated by an infinite spill weight. These
551 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen9cda1be2012-05-30 21:46:58 +0000552 //
553 // Also allow urgent evictions of unspillable ranges from a strictly
554 // larger allocation order.
555 bool Urgent = !VirtReg.isSpillable() &&
556 (Intf->isSpillable() ||
557 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
558 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000559 // Only evict older cascades or live ranges without a cascade.
560 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
561 if (Cascade <= IntfCascade) {
562 if (!Urgent)
563 return false;
564 // We permit breaking cascades for urgent evictions. It should be the
565 // last resort, though, so make it really expensive.
566 Cost.BrokenHints += 10;
567 }
568 // Would this break a satisfied hint?
569 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
570 // Update eviction cost.
571 Cost.BrokenHints += BreaksHint;
572 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
573 // Abort if this would be too expensive.
574 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000575 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000576 // Finally, apply the eviction policy for non-urgent evictions.
577 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000578 return false;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000579 }
580 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000581 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000582 return true;
583}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000584
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000585/// evictInterference - Evict any interferring registers that prevent VirtReg
586/// from being assigned to Physreg. This assumes that canEvictInterference
587/// returned true.
588void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
589 SmallVectorImpl<LiveInterval*> &NewVRegs) {
590 // Make sure that VirtReg has a cascade number, and assign that cascade
591 // number to every evicted register. These live ranges than then only be
592 // evicted by a newer cascade, preventing infinite loops.
593 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
594 if (!Cascade)
595 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
596
597 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
598 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000599
600 // Collect all interfering virtregs first.
601 SmallVector<LiveInterval*, 8> Intfs;
602 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
603 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000604 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000605 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
606 Intfs.append(IVR.begin(), IVR.end());
607 }
608
609 // Evict them second. This will invalidate the queries.
610 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
611 LiveInterval *Intf = Intfs[i];
612 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
613 if (!VRM->hasPhys(Intf->reg))
614 continue;
615 Matrix->unassign(*Intf);
616 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
617 VirtReg.isSpillable() < Intf->isSpillable()) &&
618 "Cannot decrease cascade number, illegal eviction");
619 ExtraRegInfo[Intf->reg].Cascade = Cascade;
620 ++NumEvicted;
621 NewVRegs.push_back(Intf);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000622 }
623}
624
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000625/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000626/// @param VirtReg Currently unassigned virtual register.
627/// @param Order Physregs to try.
628/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000629unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
630 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000631 SmallVectorImpl<LiveInterval*> &NewVRegs,
632 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000633 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
634
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000635 // Keep track of the cheapest interference seen so far.
636 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000637 unsigned BestPhys = 0;
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000638 unsigned OrderLimit = Order.getOrder().size();
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000639
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000640 // When we are just looking for a reduced cost per use, don't break any
641 // hints, and only evict smaller spill weights.
642 if (CostPerUseLimit < ~0u) {
643 BestCost.BrokenHints = 0;
644 BestCost.MaxWeight = VirtReg.weight;
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000645
646 // Check of any registers in RC are below CostPerUseLimit.
647 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
648 unsigned MinCost = RegClassInfo.getMinCost(RC);
649 if (MinCost >= CostPerUseLimit) {
650 DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
651 << ", no cheaper registers to be found.\n");
652 return 0;
653 }
654
655 // It is normal for register classes to have a long tail of registers with
656 // the same cost. We don't need to look at them if they're too expensive.
657 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
658 OrderLimit = RegClassInfo.getLastCostChange(RC);
659 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
660 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000661 }
662
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000663 Order.rewind();
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000664 while (unsigned PhysReg = Order.nextWithDups(OrderLimit)) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000665 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
666 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000667 // The first use of a callee-saved register in a function has cost 1.
668 // Don't start using a CSR when the CostPerUseLimit is low.
669 if (CostPerUseLimit == 1)
670 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
671 if (!MRI->isPhysRegUsed(CSR)) {
672 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
673 << PrintReg(CSR, TRI) << '\n');
674 continue;
675 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000676
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000677 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000678 continue;
679
680 // Best so far.
681 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000682
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000683 // Stop if the hint can be used.
Jakob Stoklund Olesenf7999fe2012-12-04 22:25:16 +0000684 if (Order.isHint())
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000685 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000686 }
687
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000688 if (!BestPhys)
689 return 0;
690
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000691 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000692 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000693}
694
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000695
696//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000697// Region Splitting
698//===----------------------------------------------------------------------===//
699
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000700/// addSplitConstraints - Fill out the SplitConstraints vector based on the
701/// interference pattern in Physreg and its aliases. Add the constraints to
702/// SpillPlacement and return the static cost of this split in Cost, assuming
703/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000704/// Return false if there are no bundles with positive bias.
705bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
706 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000707 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000708
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000709 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000710 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000711 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000712 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
713 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000714 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000715
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000716 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000717 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000718 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
719 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
David Blaikie453f4f02013-05-15 07:36:59 +0000720 BC.ChangesValue = BI.FirstDef.isValid();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000721
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000722 if (!Intf.hasInterference())
723 continue;
724
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000725 // Number of spill code instructions to insert.
726 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000727
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000728 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000729 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000730 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000731 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000732 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000733 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000734 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000735 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000736 }
737
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000738 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000739 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000740 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000741 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000742 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000743 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000744 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000745 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000746 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000747
748 // Accumulate the total frequency of inserted spill code.
749 if (Ins)
750 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000751 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000752 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000753
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000754 // Add constraints for use-blocks. Note that these are the only constraints
755 // that may add a positive bias, it is downhill from here.
756 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000757 return SpillPlacer->scanActiveBundles();
758}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000759
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000760
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000761/// addThroughConstraints - Add constraints and links to SpillPlacer from the
762/// live-through blocks in Blocks.
763void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
764 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000765 const unsigned GroupSize = 8;
766 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000767 unsigned TBS[GroupSize];
768 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000769
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000770 for (unsigned i = 0; i != Blocks.size(); ++i) {
771 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000772 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000773
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000774 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000775 assert(T < GroupSize && "Array overflow");
776 TBS[T] = Number;
777 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000778 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000779 T = 0;
780 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000781 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000782 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000783
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000784 assert(B < GroupSize && "Array overflow");
785 BCS[B].Number = Number;
786
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000787 // Interference for the live-in value.
788 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
789 BCS[B].Entry = SpillPlacement::MustSpill;
790 else
791 BCS[B].Entry = SpillPlacement::PrefSpill;
792
793 // Interference for the live-out value.
794 if (Intf.last() >= SA->getLastSplitPoint(Number))
795 BCS[B].Exit = SpillPlacement::MustSpill;
796 else
797 BCS[B].Exit = SpillPlacement::PrefSpill;
798
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000799 if (++B == GroupSize) {
800 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
801 SpillPlacer->addConstraints(Array);
802 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000803 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000804 }
805
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000806 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
807 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000808 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000809}
810
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000811void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000812 // Keep track of through blocks that have not been added to SpillPlacer.
813 BitVector Todo = SA->getThroughBlocks();
814 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
815 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000816#ifndef NDEBUG
817 unsigned Visited = 0;
818#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000819
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000820 for (;;) {
821 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000822 // Find new through blocks in the periphery of PrefRegBundles.
823 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
824 unsigned Bundle = NewBundles[i];
825 // Look at all blocks connected to Bundle in the full graph.
826 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
827 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
828 I != E; ++I) {
829 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000830 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000831 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000832 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000833 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000834 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000835#ifndef NDEBUG
836 ++Visited;
837#endif
838 }
839 }
840 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000841 if (ActiveBlocks.size() == AddedTo)
842 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000843
844 // Compute through constraints from the interference, or assume that all
845 // through blocks prefer spilling when forming compact regions.
846 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
847 if (Cand.PhysReg)
848 addThroughConstraints(Cand.Intf, NewBlocks);
849 else
Jakob Stoklund Olesenb87f91b2011-08-03 23:09:38 +0000850 // Provide a strong negative bias on through blocks to prevent unwanted
851 // liveness on loop backedges.
852 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000853 AddedTo = ActiveBlocks.size();
854
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000855 // Perhaps iterating can enable more bundles?
856 SpillPlacer->iterate();
857 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000858 DEBUG(dbgs() << ", v=" << Visited);
859}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000860
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000861/// calcCompactRegion - Compute the set of edge bundles that should be live
862/// when splitting the current live range into compact regions. Compact
863/// regions can be computed without looking at interference. They are the
864/// regions formed by removing all the live-through blocks from the live range.
865///
866/// Returns false if the current live range is already compact, or if the
867/// compact regions would form single block regions anyway.
868bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
869 // Without any through blocks, the live range is already compact.
870 if (!SA->getNumThroughBlocks())
871 return false;
872
873 // Compact regions don't correspond to any physreg.
874 Cand.reset(IntfCache, 0);
875
876 DEBUG(dbgs() << "Compact region bundles");
877
878 // Use the spill placer to determine the live bundles. GrowRegion pretends
879 // that all the through blocks have interference when PhysReg is unset.
880 SpillPlacer->prepare(Cand.LiveBundles);
881
882 // The static split cost will be zero since Cand.Intf reports no interference.
883 float Cost;
884 if (!addSplitConstraints(Cand.Intf, Cost)) {
885 DEBUG(dbgs() << ", none.\n");
886 return false;
887 }
888
889 growRegion(Cand);
890 SpillPlacer->finish();
891
892 if (!Cand.LiveBundles.any()) {
893 DEBUG(dbgs() << ", none.\n");
894 return false;
895 }
896
897 DEBUG({
898 for (int i = Cand.LiveBundles.find_first(); i>=0;
899 i = Cand.LiveBundles.find_next(i))
900 dbgs() << " EB#" << i;
901 dbgs() << ".\n";
902 });
903 return true;
904}
905
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000906/// calcSpillCost - Compute how expensive it would be to split the live range in
907/// SA around all use blocks instead of forming bundle regions.
908float RAGreedy::calcSpillCost() {
909 float Cost = 0;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000910 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
911 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
912 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
913 unsigned Number = BI.MBB->getNumber();
914 // We normally only need one spill instruction - a load or a store.
915 Cost += SpillPlacer->getBlockFrequency(Number);
916
917 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3f5beed2011-08-02 23:04:08 +0000918 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
919 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000920 }
921 return Cost;
922}
923
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000924/// calcGlobalSplitCost - Return the global split cost of following the split
925/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000926/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000927///
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000928float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000929 float GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000930 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000931 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
932 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
933 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000934 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000935 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
936 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
937 unsigned Ins = 0;
938
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000939 if (BI.LiveIn)
940 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
941 if (BI.LiveOut)
942 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000943 if (Ins)
944 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000945 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000946
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000947 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
948 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000949 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
950 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000951 if (!RegIn && !RegOut)
952 continue;
953 if (RegIn && RegOut) {
954 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000955 Cand.Intf.moveToBlock(Number);
956 if (Cand.Intf.hasInterference())
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000957 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
958 continue;
959 }
960 // live-in / stack-out or stack-in live-out.
961 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000962 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000963 return GlobalCost;
964}
965
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000966/// splitAroundRegion - Split the current live range around the regions
967/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000968///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000969/// Before calling this function, GlobalCand and BundleCand must be initialized
970/// so each bundle is assigned to a valid candidate, or NoCand for the
971/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
972/// objects must be initialized for the current live range, and intervals
973/// created for the used candidates.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000974///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000975/// @param LREdit The LiveRangeEdit object handling the current split.
976/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
977/// must appear in this list.
978void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
979 ArrayRef<unsigned> UsedCands) {
980 // These are the intervals created for new global ranges. We may create more
981 // intervals for local ranges.
982 const unsigned NumGlobalIntvs = LREdit.size();
983 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
984 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000985
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000986 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen69145ba2011-08-06 18:20:24 +0000987 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000988 // is all copies.
989 unsigned Reg = SA->getParent().reg;
990 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
991
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000992 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000993 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
994 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
995 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000996 unsigned Number = BI.MBB->getNumber();
997 unsigned IntvIn = 0, IntvOut = 0;
998 SlotIndex IntfIn, IntfOut;
999 if (BI.LiveIn) {
1000 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1001 if (CandIn != NoCand) {
1002 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1003 IntvIn = Cand.IntvIdx;
1004 Cand.Intf.moveToBlock(Number);
1005 IntfIn = Cand.Intf.first();
1006 }
1007 }
1008 if (BI.LiveOut) {
1009 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1010 if (CandOut != NoCand) {
1011 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1012 IntvOut = Cand.IntvIdx;
1013 Cand.Intf.moveToBlock(Number);
1014 IntfOut = Cand.Intf.last();
1015 }
1016 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001017
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001018 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001019 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001020 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001021 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +00001022 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001023 continue;
1024 }
1025
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001026 if (IntvIn && IntvOut)
1027 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1028 else if (IntvIn)
1029 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +00001030 else
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001031 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001032 }
1033
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001034 // Handle live-through blocks. The relevant live-through blocks are stored in
1035 // the ActiveBlocks list with each candidate. We need to filter out
1036 // duplicates.
1037 BitVector Todo = SA->getThroughBlocks();
1038 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1039 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1040 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1041 unsigned Number = Blocks[i];
1042 if (!Todo.test(Number))
1043 continue;
1044 Todo.reset(Number);
1045
1046 unsigned IntvIn = 0, IntvOut = 0;
1047 SlotIndex IntfIn, IntfOut;
1048
1049 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1050 if (CandIn != NoCand) {
1051 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1052 IntvIn = Cand.IntvIdx;
1053 Cand.Intf.moveToBlock(Number);
1054 IntfIn = Cand.Intf.first();
1055 }
1056
1057 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1058 if (CandOut != NoCand) {
1059 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1060 IntvOut = Cand.IntvIdx;
1061 Cand.Intf.moveToBlock(Number);
1062 IntfOut = Cand.Intf.last();
1063 }
1064 if (!IntvIn && !IntvOut)
1065 continue;
1066 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1067 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001068 }
1069
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001070 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001071
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001072 SmallVector<unsigned, 8> IntvMap;
1073 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001074 DebugVars->splitRegister(Reg, LREdit.regs());
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001075
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001076 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +00001077 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001078
1079 // Sort out the new intervals created by splitting. We get four kinds:
1080 // - Remainder intervals should not be split again.
1081 // - Candidate intervals can be assigned to Cand.PhysReg.
1082 // - Block-local splits are candidates for local splitting.
1083 // - DCE leftovers should go back on the queue.
1084 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001085 LiveInterval &Reg = *LREdit.get(i);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001086
1087 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001088 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001089 continue;
1090
1091 // Remainder interval. Don't try splitting again, spill if it doesn't
1092 // allocate.
1093 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001094 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001095 continue;
1096 }
1097
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001098 // Global intervals. Allow repeated splitting as long as the number of live
1099 // blocks is strictly decreasing.
1100 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001101 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001102 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1103 << " blocks as original.\n");
1104 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001105 setStage(Reg, RS_Split2);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001106 }
1107 continue;
1108 }
1109
1110 // Other intervals are treated as new. This includes local intervals created
1111 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001112 }
1113
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001114 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001115 MF->verify(this, "After splitting live range around region");
1116}
1117
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001118unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1119 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001120 unsigned NumCands = 0;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001121 unsigned BestCand = NoCand;
1122 float BestCost;
1123 SmallVector<unsigned, 8> UsedCands;
1124
1125 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +00001126 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001127 if (HasCompact) {
1128 // Yes, keep GlobalCand[0] as the compact region candidate.
1129 NumCands = 1;
1130 BestCost = HUGE_VALF;
1131 } else {
1132 // No benefit from the compact region, our fallback will be per-block
1133 // splitting. Make sure we find a solution that is cheaper than spilling.
1134 BestCost = Hysteresis * calcSpillCost();
1135 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1136 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001137
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001138 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001139 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001140 // Discard bad candidates before we run out of interference cache cursors.
1141 // This will only affect register classes with a lot of registers (>32).
1142 if (NumCands == IntfCache.getMaxCursors()) {
1143 unsigned WorstCount = ~0u;
1144 unsigned Worst = 0;
1145 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001146 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001147 continue;
1148 unsigned Count = GlobalCand[i].LiveBundles.count();
1149 if (Count < WorstCount)
1150 Worst = i, WorstCount = Count;
1151 }
1152 --NumCands;
1153 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen7bdf0062011-11-01 00:02:31 +00001154 if (BestCand == NumCands)
1155 BestCand = Worst;
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001156 }
1157
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001158 if (GlobalCand.size() <= NumCands)
1159 GlobalCand.resize(NumCands+1);
1160 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1161 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001162
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001163 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001164 float Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001165 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001166 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001167 continue;
1168 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001169 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001170 if (Cost >= BestCost) {
1171 DEBUG({
1172 if (BestCand == NoCand)
1173 dbgs() << " worse than no bundles\n";
1174 else
1175 dbgs() << " worse than "
1176 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1177 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001178 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001179 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001180 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001181
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001182 SpillPlacer->finish();
1183
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001184 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001185 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001186 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001187 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001188 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001189
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001190 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001191 DEBUG({
1192 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001193 for (int i = Cand.LiveBundles.find_first(); i>=0;
1194 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001195 dbgs() << " EB#" << i;
1196 dbgs() << ".\n";
1197 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001198 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001199 BestCand = NumCands;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001200 BestCost = Hysteresis * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001201 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001202 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001203 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001204
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001205 // No solutions found, fall back to single block splitting.
1206 if (!HasCompact && BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001207 return 0;
1208
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001209 // Prepare split editor.
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001210 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001211 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001212
1213 // Assign all edge bundles to the preferred candidate, or NoCand.
1214 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1215
1216 // Assign bundles for the best candidate region.
1217 if (BestCand != NoCand) {
1218 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1219 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1220 UsedCands.push_back(BestCand);
1221 Cand.IntvIdx = SE->openIntv();
1222 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1223 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001224 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001225 }
1226 }
1227
1228 // Assign bundles for the compact region.
1229 if (HasCompact) {
1230 GlobalSplitCandidate &Cand = GlobalCand.front();
1231 assert(!Cand.PhysReg && "Compact region has no physreg");
1232 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1233 UsedCands.push_back(0);
1234 Cand.IntvIdx = SE->openIntv();
1235 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1236 << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001237 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001238 }
1239 }
1240
1241 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001242 return 0;
1243}
1244
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001245
1246//===----------------------------------------------------------------------===//
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001247// Per-Block Splitting
1248//===----------------------------------------------------------------------===//
1249
1250/// tryBlockSplit - Split a global live range around every block with uses. This
1251/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1252/// they don't allocate.
1253unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1254 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1255 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1256 unsigned Reg = VirtReg.reg;
1257 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001258 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001259 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001260 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1261 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1262 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1263 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1264 SE->splitSingleBlock(BI);
1265 }
1266 // No blocks were split.
1267 if (LREdit.empty())
1268 return 0;
1269
1270 // We did split for some blocks.
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001271 SmallVector<unsigned, 8> IntvMap;
1272 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001273
1274 // Tell LiveDebugVariables about the new ranges.
1275 DebugVars->splitRegister(Reg, LREdit.regs());
1276
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001277 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1278
1279 // Sort out the new intervals created by splitting. The remainder interval
1280 // goes straight to spilling, the new local ranges get to stay RS_New.
1281 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1282 LiveInterval &LI = *LREdit.get(i);
1283 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1284 setStage(LI, RS_Spill);
1285 }
1286
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001287 if (VerifyEnabled)
1288 MF->verify(this, "After splitting live range around basic blocks");
1289 return 0;
1290}
1291
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001292
1293//===----------------------------------------------------------------------===//
1294// Per-Instruction Splitting
1295//===----------------------------------------------------------------------===//
1296
1297/// tryInstructionSplit - Split a live range around individual instructions.
1298/// This is normally not worthwhile since the spiller is doing essentially the
1299/// same thing. However, when the live range is in a constrained register
1300/// class, it may help to insert copies such that parts of the live range can
1301/// be moved to a larger register class.
1302///
1303/// This is similar to spilling to a larger register class.
1304unsigned
1305RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1306 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1307 // There is no point to this if there are no larger sub-classes.
1308 if (!RegClassInfo.isProperSubClass(MRI->getRegClass(VirtReg.reg)))
1309 return 0;
1310
1311 // Always enable split spill mode, since we're effectively spilling to a
1312 // register.
1313 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1314 SE->reset(LREdit, SplitEditor::SM_Size);
1315
1316 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1317 if (Uses.size() <= 1)
1318 return 0;
1319
1320 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1321
1322 // Split around every non-copy instruction.
1323 for (unsigned i = 0; i != Uses.size(); ++i) {
1324 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1325 if (MI->isFullCopy()) {
1326 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1327 continue;
1328 }
1329 SE->openIntv();
1330 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1331 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1332 SE->useIntv(SegStart, SegStop);
1333 }
1334
1335 if (LREdit.empty()) {
1336 DEBUG(dbgs() << "All uses were copies.\n");
1337 return 0;
1338 }
1339
1340 SmallVector<unsigned, 8> IntvMap;
1341 SE->finish(&IntvMap);
1342 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1343 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1344
1345 // Assign all new registers to RS_Spill. This was the last chance.
1346 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1347 return 0;
1348}
1349
1350
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001351//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001352// Local Splitting
1353//===----------------------------------------------------------------------===//
1354
1355
1356/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1357/// in order to use PhysReg between two entries in SA->UseSlots.
1358///
1359/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1360///
1361void RAGreedy::calcGapWeights(unsigned PhysReg,
1362 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001363 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1364 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001365 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001366 const unsigned NumGaps = Uses.size()-1;
1367
1368 // Start and end points for the interference check.
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001369 SlotIndex StartIdx =
1370 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1371 SlotIndex StopIdx =
1372 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001373
1374 GapWeight.assign(NumGaps, 0.0f);
1375
1376 // Add interference from each overlapping register.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001377 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1378 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1379 .checkInterference())
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001380 continue;
1381
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001382 // We know that VirtReg is a continuous interval from FirstInstr to
1383 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001384 //
1385 // Interference that overlaps an instruction is counted in both gaps
1386 // surrounding the instruction. The exception is interference before
1387 // StartIdx and after StopIdx.
1388 //
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001389 LiveIntervalUnion::SegmentIter IntI =
1390 Matrix->getLiveUnions()[*Units] .find(StartIdx);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001391 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1392 // Skip the gaps before IntI.
1393 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1394 if (++Gap == NumGaps)
1395 break;
1396 if (Gap == NumGaps)
1397 break;
1398
1399 // Update the gaps covered by IntI.
1400 const float weight = IntI.value()->weight;
1401 for (; Gap != NumGaps; ++Gap) {
1402 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1403 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1404 break;
1405 }
1406 if (Gap == NumGaps)
1407 break;
1408 }
1409 }
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001410
1411 // Add fixed interference.
1412 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1413 const LiveInterval &LI = LIS->getRegUnit(*Units);
1414 LiveInterval::const_iterator I = LI.find(StartIdx);
1415 LiveInterval::const_iterator E = LI.end();
1416
1417 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1418 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1419 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1420 if (++Gap == NumGaps)
1421 break;
1422 if (Gap == NumGaps)
1423 break;
1424
1425 for (; Gap != NumGaps; ++Gap) {
1426 GapWeight[Gap] = HUGE_VALF;
1427 if (Uses[Gap+1].getBaseIndex() >= I->end)
1428 break;
1429 }
1430 if (Gap == NumGaps)
1431 break;
1432 }
1433 }
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001434}
1435
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001436/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1437/// basic block.
1438///
1439unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1440 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001441 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1442 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001443
1444 // Note that it is possible to have an interval that is live-in or live-out
1445 // while only covering a single block - A phi-def can use undef values from
1446 // predecessors, and the block could be a single-block loop.
1447 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001448 // that the interval is continuous from FirstInstr to LastInstr. We should
1449 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001450
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001451 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001452 if (Uses.size() <= 2)
1453 return 0;
1454 const unsigned NumGaps = Uses.size()-1;
1455
1456 DEBUG({
1457 dbgs() << "tryLocalSplit: ";
1458 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001459 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001460 dbgs() << '\n';
1461 });
1462
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001463 // If VirtReg is live across any register mask operands, compute a list of
1464 // gaps with register masks.
1465 SmallVector<unsigned, 8> RegMaskGaps;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001466 if (Matrix->checkRegMaskInterference(VirtReg)) {
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001467 // Get regmask slots for the whole block.
1468 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001469 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001470 // Constrain to VirtReg's live range.
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001471 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1472 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001473 unsigned re = RMS.size();
1474 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001475 // Look for Uses[i] <= RMS <= Uses[i+1].
1476 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1477 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001478 continue;
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001479 // Skip a regmask on the same instruction as the last use. It doesn't
1480 // overlap the live range.
1481 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1482 break;
1483 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001484 RegMaskGaps.push_back(i);
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001485 // Advance ri to the next gap. A regmask on one of the uses counts in
1486 // both gaps.
1487 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1488 ++ri;
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001489 }
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001490 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001491 }
1492
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001493 // Since we allow local split results to be split again, there is a risk of
1494 // creating infinite loops. It is tempting to require that the new live
1495 // ranges have less instructions than the original. That would guarantee
1496 // convergence, but it is too strict. A live range with 3 instructions can be
1497 // split 2+3 (including the COPY), and we want to allow that.
1498 //
1499 // Instead we use these rules:
1500 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001501 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001502 // noop split, of course).
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001503 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001504 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001505 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001506 // smaller ranges are marked RS_New.
1507 //
1508 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1509 // excessive splitting and infinite loops.
1510 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001511 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001512
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001513 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001514 unsigned BestBefore = NumGaps;
1515 unsigned BestAfter = 0;
1516 float BestDiff = 0;
1517
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001518 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001519 SmallVector<float, 8> GapWeight;
1520
1521 Order.rewind();
1522 while (unsigned PhysReg = Order.next()) {
1523 // Keep track of the largest spill weight that would need to be evicted in
1524 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1525 calcGapWeights(PhysReg, GapWeight);
1526
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001527 // Remove any gaps with regmask clobbers.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001528 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001529 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1530 GapWeight[RegMaskGaps[i]] = HUGE_VALF;
1531
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001532 // Try to find the best sequence of gaps to close.
1533 // The new spill weight must be larger than any gap interference.
1534
1535 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001536 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001537
1538 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1539 // It is the spill weight that needs to be evicted.
1540 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001541
1542 for (;;) {
1543 // Live before/after split?
1544 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1545 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1546
1547 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1548 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1549 << " i=" << MaxGap);
1550
1551 // Stop before the interval gets so big we wouldn't be making progress.
1552 if (!LiveBefore && !LiveAfter) {
1553 DEBUG(dbgs() << " all\n");
1554 break;
1555 }
1556 // Should the interval be extended or shrunk?
1557 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001558
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001559 // How many gaps would the new range have?
1560 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1561
1562 // Legally, without causing looping?
1563 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1564
1565 if (Legal && MaxGap < HUGE_VALF) {
1566 // Estimate the new spill weight. Each instruction reads or writes the
1567 // register. Conservatively assume there are no read-modify-write
1568 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001569 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001570 // Try to guess the size of the new interval.
1571 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1572 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1573 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001574 // Would this split be possible to allocate?
1575 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001576 DEBUG(dbgs() << " w=" << EstWeight);
1577 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001578 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001579 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001580 if (Diff > BestDiff) {
1581 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001582 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001583 BestBefore = SplitBefore;
1584 BestAfter = SplitAfter;
1585 }
1586 }
1587 }
1588
1589 // Try to shrink.
1590 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001591 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001592 DEBUG(dbgs() << " shrink\n");
1593 // Recompute the max when necessary.
1594 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1595 MaxGap = GapWeight[SplitBefore];
1596 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1597 MaxGap = std::max(MaxGap, GapWeight[i]);
1598 }
1599 continue;
1600 }
1601 MaxGap = 0;
1602 }
1603
1604 // Try to extend the interval.
1605 if (SplitAfter >= NumGaps) {
1606 DEBUG(dbgs() << " end\n");
1607 break;
1608 }
1609
1610 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001611 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001612 }
1613 }
1614
1615 // Didn't find any candidates?
1616 if (BestBefore == NumGaps)
1617 return 0;
1618
1619 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1620 << '-' << Uses[BestAfter] << ", " << BestDiff
1621 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1622
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001623 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001624 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001625
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001626 SE->openIntv();
1627 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1628 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1629 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001630 SmallVector<unsigned, 8> IntvMap;
1631 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001632 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001633
1634 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001635 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001636 // leave the new intervals as RS_New so they can compete.
1637 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1638 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1639 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1640 if (NewGaps >= NumGaps) {
1641 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1642 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001643 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1644 if (IntvMap[i] == 1) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001645 setStage(*LREdit.get(i), RS_Split2);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001646 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1647 }
1648 DEBUG(dbgs() << '\n');
1649 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001650 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001651
1652 return 0;
1653}
1654
1655//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001656// Live Range Splitting
1657//===----------------------------------------------------------------------===//
1658
1659/// trySplit - Try to split VirtReg or one of its interferences, making it
1660/// assignable.
1661/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1662unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1663 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesenccfa4462011-08-05 23:50:33 +00001664 // Ranges must be Split2 or less.
1665 if (getStage(VirtReg) >= RS_Spill)
1666 return 0;
1667
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001668 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001669 if (LIS->intervalIsInOneMBB(VirtReg)) {
1670 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001671 SA->analyze(&VirtReg);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001672 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1673 if (PhysReg || !NewVRegs.empty())
1674 return PhysReg;
1675 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001676 }
1677
1678 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001679
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001680 SA->analyze(&VirtReg);
1681
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001682 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1683 // coalescer. That may cause the range to become allocatable which means that
1684 // tryRegionSplit won't be making progress. This check should be replaced with
1685 // an assertion when the coalescer is fixed.
1686 if (SA->didRepairRange()) {
1687 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001688 Matrix->invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001689 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1690 return PhysReg;
1691 }
1692
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001693 // First try to split around a region spanning multiple blocks. RS_Split2
1694 // ranges already made dubious progress with region splitting, so they go
1695 // straight to single block splitting.
1696 if (getStage(VirtReg) < RS_Split2) {
1697 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1698 if (PhysReg || !NewVRegs.empty())
1699 return PhysReg;
1700 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001701
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001702 // Then isolate blocks.
1703 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001704}
1705
1706
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001707//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001708// Main Entry Point
1709//===----------------------------------------------------------------------===//
1710
1711unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001712 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001713 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001714 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001715 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1716 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001717
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001718 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001719 DEBUG(dbgs() << StageName[Stage]
1720 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001721
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001722 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001723 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001724 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001725 if (Stage != RS_Split)
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001726 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1727 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001728
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001729 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1730
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001731 // The first time we see a live range, don't try to split or spill.
1732 // Wait until the second time, when all smaller ranges have been allocated.
1733 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001734 if (Stage < RS_Split) {
1735 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001736 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001737 NewVRegs.push_back(&VirtReg);
1738 return 0;
1739 }
1740
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001741 // If we couldn't allocate a register from spilling, there is probably some
1742 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001743 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001744 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001745
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001746 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001747 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1748 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001749 return PhysReg;
1750
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001751 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001752 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001753 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001754 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001755 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001756
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001757 if (VerifyEnabled)
1758 MF->verify(this, "After spilling");
1759
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001760 // The live virtual register requesting allocation was spilled, so tell
1761 // the caller not to allocate anything during this round.
1762 return 0;
1763}
1764
1765bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1766 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
David Blaikie986d76d2012-08-22 17:18:53 +00001767 << "********** Function: " << mf.getName() << '\n');
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001768
1769 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001770 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001771 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001772
Jakob Stoklund Olesend4348a22012-06-20 22:52:29 +00001773 RegAllocBase::init(getAnalysis<VirtRegMap>(),
1774 getAnalysis<LiveIntervals>(),
1775 getAnalysis<LiveRegMatrix>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001776 Indexes = &getAnalysis<SlotIndexes>();
Benjamin Kramer4eed7562013-06-17 19:00:36 +00001777 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001778 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001779 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001780 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001781 Bundles = &getAnalysis<EdgeBundles>();
1782 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001783 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001784
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001785 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Benjamin Kramer4eed7562013-06-17 19:00:36 +00001786 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001787 ExtraRegInfo.clear();
1788 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1789 NextCascade = 1;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001790 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001791 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001792
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001793 allocatePhysRegs();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001794 releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001795 return true;
1796}