blob: 06f69c1e0d16fc6199ad961765807d19556321b0 [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"
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +000016#include "AllocationOrder.h"
Jakob Stoklund Olesen5907d862011-04-02 06:03:35 +000017#include "InterferenceCache.h"
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +000018#include "LiveDebugVariables.h"
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +000019#include "LiveRegMatrix.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000020#include "RegAllocBase.h"
21#include "Spiller.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000022#include "SpillPlacement.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000023#include "SplitKit.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000024#include "VirtRegMap.h"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000025#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000026#include "llvm/Analysis/AliasAnalysis.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000027#include "llvm/PassAnalysisSupport.h"
28#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000029#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000030#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper789d5d82012-04-02 22:44:18 +000031#include "llvm/CodeGen/LiveRangeEdit.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000032#include "llvm/CodeGen/LiveStackAnalysis.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"
37#include "llvm/CodeGen/Passes.h"
38#include "llvm/CodeGen/RegAllocRegistry.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000039#include "llvm/Target/TargetOptions.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"
43#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000044#include "llvm/Support/Timer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000045
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000046#include <queue>
47
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000048using namespace llvm;
49
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000050STATISTIC(NumGlobalSplits, "Number of split global live ranges");
51STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000052STATISTIC(NumEvicted, "Number of interferences evicted");
53
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +000054static cl::opt<SplitEditor::ComplementSpillMode>
55SplitSpillMode("split-spill-mode", cl::Hidden,
56 cl::desc("Spill mode for splitting live ranges"),
57 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
58 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
59 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
60 clEnumValEnd),
61 cl::init(SplitEditor::SM_Partition));
62
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000063static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
64 createGreedyRegisterAllocator);
65
66namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000067class RAGreedy : public MachineFunctionPass,
68 public RegAllocBase,
69 private LiveRangeEdit::Delegate {
70
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000071 // context
72 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000073
74 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000075 SlotIndexes *Indexes;
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
83 std::auto_ptr<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.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000171 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000172 std::auto_ptr<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();
325 AU.addRequired<AliasAnalysis>();
326 AU.addPreserved<AliasAnalysis>();
327 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000328 AU.addPreserved<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000329 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000330 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000331 AU.addRequired<LiveDebugVariables>();
332 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000333 AU.addRequired<LiveStacks>();
334 AU.addPreserved<LiveStacks>();
Evan Chengbb36a432012-09-21 20:04:28 +0000335 AU.addRequired<CalculateSpillWeights>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000336 AU.addRequired<MachineDominatorTree>();
337 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000338 AU.addRequired<MachineLoopInfo>();
339 AU.addPreserved<MachineLoopInfo>();
340 AU.addRequired<VirtRegMap>();
341 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000342 AU.addRequired<LiveRegMatrix>();
343 AU.addPreserved<LiveRegMatrix>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000344 AU.addRequired<EdgeBundles>();
345 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000346 MachineFunctionPass::getAnalysisUsage(AU);
347}
348
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000349
350//===----------------------------------------------------------------------===//
351// LiveRangeEdit delegate methods
352//===----------------------------------------------------------------------===//
353
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000354bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000355 if (VRM->hasPhys(VirtReg)) {
356 Matrix->unassign(LIS->getInterval(VirtReg));
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000357 return true;
358 }
359 // Unassigned virtreg is probably in the priority queue.
360 // RegAllocBase will erase it after dequeueing.
361 return false;
362}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000363
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000364void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000365 if (!VRM->hasPhys(VirtReg))
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000366 return;
367
368 // Register is assigned, put it back on the queue for reassignment.
369 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000370 Matrix->unassign(LI);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000371 enqueue(&LI);
372}
373
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000374void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen0d4fea72011-09-14 17:34:37 +0000375 // Cloning a register we haven't even heard about yet? Just ignore it.
376 if (!ExtraRegInfo.inBounds(Old))
377 return;
378
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000379 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000380 // be split into connected components. The new components are much smaller
381 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000382 // same stage as the parent.
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000383 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000384 ExtraRegInfo.grow(New);
385 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000386}
387
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000388void RAGreedy::releaseMemory() {
389 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000390 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000391 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000392}
393
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000394void RAGreedy::enqueue(LiveInterval *LI) {
395 // Prioritize live ranges by size, assigning larger ranges first.
396 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000397 const unsigned Size = LI->getSize();
398 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000399 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
400 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000401 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000402
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000403 ExtraRegInfo.grow(Reg);
404 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000405 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000406
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000407 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000408 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000409 // everything else has been allocated.
410 Prio = Size;
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000411 } else {
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000412 // Everything is allocated in long->short order. Long ranges that don't fit
413 // should be spilled (or split) ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000414 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000415
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000416 // Boost ranges that have a physical register hint.
417 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
418 Prio |= (1u << 30);
419 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000420
Jakob Stoklund Olesene3b23cd2012-04-02 22:30:39 +0000421 Queue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000422}
423
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000424LiveInterval *RAGreedy::dequeue() {
425 if (Queue.empty())
426 return 0;
Jakob Stoklund Olesene3b23cd2012-04-02 22:30:39 +0000427 LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000428 Queue.pop();
429 return LI;
430}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000431
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000432
433//===----------------------------------------------------------------------===//
434// Direct Assignment
435//===----------------------------------------------------------------------===//
436
437/// tryAssign - Try to assign VirtReg to an available register.
438unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
439 AllocationOrder &Order,
440 SmallVectorImpl<LiveInterval*> &NewVRegs) {
441 Order.rewind();
442 unsigned PhysReg;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000443 while ((PhysReg = Order.next()))
444 if (!Matrix->checkInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000445 break;
446 if (!PhysReg || Order.isHint(PhysReg))
447 return PhysReg;
448
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000449 // PhysReg is available, but there may be a better choice.
450
451 // If we missed a simple hint, try to cheaply evict interference from the
452 // preferred register.
453 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000454 if (Order.isHint(Hint)) {
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000455 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
456 EvictionCost MaxCost(1);
457 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
458 evictInterference(VirtReg, Hint, NewVRegs);
459 return Hint;
460 }
461 }
462
463 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000464 unsigned Cost = TRI->getCostPerUse(PhysReg);
465
466 // Most registers have 0 additional cost.
467 if (!Cost)
468 return PhysReg;
469
470 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
471 << '\n');
472 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
473 return CheapReg ? CheapReg : PhysReg;
474}
475
476
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000477//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000478// Interference eviction
479//===----------------------------------------------------------------------===//
480
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000481/// shouldEvict - determine if A should evict the assigned live range B. The
482/// eviction policy defined by this function together with the allocation order
483/// defined by enqueue() decides which registers ultimately end up being split
484/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000485///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000486/// Cascade numbers are used to prevent infinite loops if this function is a
487/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000488///
489/// @param A The live range to be assigned.
490/// @param IsHint True when A is about to be assigned to its preferred
491/// register.
492/// @param B The live range to be evicted.
493/// @param BreaksHint True when B is already assigned to its preferred register.
494bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
495 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000496 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000497
498 // Be fairly aggressive about following hints as long as the evictee can be
499 // split.
500 if (CanSplit && IsHint && !BreaksHint)
501 return true;
502
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000503 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000504}
505
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000506/// canEvictInterference - Return true if all interferences between VirtReg and
507/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
508///
509/// @param VirtReg Live range that is about to be assigned.
510/// @param PhysReg Desired register for assignment.
Dmitri Gribenko67c89782012-09-12 16:59:47 +0000511/// @param IsHint True when PhysReg is VirtReg's preferred register.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000512/// @param MaxCost Only look for cheaper candidates and update with new cost
513/// when returning true.
514/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000515bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000516 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000517 // It is only possible to evict virtual register interference.
518 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
519 return false;
520
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000521 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
522 // involved in an eviction before. If a cascade number was assigned, deny
523 // evicting anything with the same or a newer cascade number. This prevents
524 // infinite eviction loops.
525 //
526 // This works out so a register without a cascade number is allowed to evict
527 // anything, and it can be evicted by anything.
528 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
529 if (!Cascade)
530 Cascade = NextCascade;
531
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000532 EvictionCost Cost;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000533 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
534 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000535 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000536 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000537 return false;
538
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000539 // Check if any interfering live range is heavier than MaxWeight.
540 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
541 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000542 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
543 "Only expecting virtual register interference from query");
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000544 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000545 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000546 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000547 // Once a live range becomes small enough, it is urgent that we find a
548 // register for it. This is indicated by an infinite spill weight. These
549 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen9cda1be2012-05-30 21:46:58 +0000550 //
551 // Also allow urgent evictions of unspillable ranges from a strictly
552 // larger allocation order.
553 bool Urgent = !VirtReg.isSpillable() &&
554 (Intf->isSpillable() ||
555 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
556 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000557 // Only evict older cascades or live ranges without a cascade.
558 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
559 if (Cascade <= IntfCascade) {
560 if (!Urgent)
561 return false;
562 // We permit breaking cascades for urgent evictions. It should be the
563 // last resort, though, so make it really expensive.
564 Cost.BrokenHints += 10;
565 }
566 // Would this break a satisfied hint?
567 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
568 // Update eviction cost.
569 Cost.BrokenHints += BreaksHint;
570 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
571 // Abort if this would be too expensive.
572 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000573 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000574 // Finally, apply the eviction policy for non-urgent evictions.
575 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000576 return false;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000577 }
578 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000579 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000580 return true;
581}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000582
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000583/// evictInterference - Evict any interferring registers that prevent VirtReg
584/// from being assigned to Physreg. This assumes that canEvictInterference
585/// returned true.
586void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
587 SmallVectorImpl<LiveInterval*> &NewVRegs) {
588 // Make sure that VirtReg has a cascade number, and assign that cascade
589 // number to every evicted register. These live ranges than then only be
590 // evicted by a newer cascade, preventing infinite loops.
591 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
592 if (!Cascade)
593 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
594
595 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
596 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000597
598 // Collect all interfering virtregs first.
599 SmallVector<LiveInterval*, 8> Intfs;
600 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
601 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000602 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000603 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
604 Intfs.append(IVR.begin(), IVR.end());
605 }
606
607 // Evict them second. This will invalidate the queries.
608 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
609 LiveInterval *Intf = Intfs[i];
610 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
611 if (!VRM->hasPhys(Intf->reg))
612 continue;
613 Matrix->unassign(*Intf);
614 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
615 VirtReg.isSpillable() < Intf->isSpillable()) &&
616 "Cannot decrease cascade number, illegal eviction");
617 ExtraRegInfo[Intf->reg].Cascade = Cascade;
618 ++NumEvicted;
619 NewVRegs.push_back(Intf);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000620 }
621}
622
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000623/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000624/// @param VirtReg Currently unassigned virtual register.
625/// @param Order Physregs to try.
626/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000627unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
628 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000629 SmallVectorImpl<LiveInterval*> &NewVRegs,
630 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000631 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
632
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000633 // Keep track of the cheapest interference seen so far.
634 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000635 unsigned BestPhys = 0;
636
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000637 // When we are just looking for a reduced cost per use, don't break any
638 // hints, and only evict smaller spill weights.
639 if (CostPerUseLimit < ~0u) {
640 BestCost.BrokenHints = 0;
641 BestCost.MaxWeight = VirtReg.weight;
642 }
643
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000644 Order.rewind();
645 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000646 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
647 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000648 // The first use of a callee-saved register in a function has cost 1.
649 // Don't start using a CSR when the CostPerUseLimit is low.
650 if (CostPerUseLimit == 1)
651 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
652 if (!MRI->isPhysRegUsed(CSR)) {
653 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
654 << PrintReg(CSR, TRI) << '\n');
655 continue;
656 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000657
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000658 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000659 continue;
660
661 // Best so far.
662 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000663
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000664 // Stop if the hint can be used.
665 if (Order.isHint(PhysReg))
666 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000667 }
668
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000669 if (!BestPhys)
670 return 0;
671
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000672 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000673 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000674}
675
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000676
677//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000678// Region Splitting
679//===----------------------------------------------------------------------===//
680
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000681/// addSplitConstraints - Fill out the SplitConstraints vector based on the
682/// interference pattern in Physreg and its aliases. Add the constraints to
683/// SpillPlacement and return the static cost of this split in Cost, assuming
684/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000685/// Return false if there are no bundles with positive bias.
686bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
687 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000688 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000689
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000690 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000691 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000692 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000693 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
694 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000695 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000696
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000697 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000698 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000699 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
700 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesen5ebca792011-08-02 23:04:06 +0000701 BC.ChangesValue = BI.FirstDef;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000702
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000703 if (!Intf.hasInterference())
704 continue;
705
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000706 // Number of spill code instructions to insert.
707 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000708
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000709 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000710 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000711 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000712 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000713 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000714 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000715 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000716 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000717 }
718
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000719 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000720 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000721 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000722 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000723 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000724 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000725 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000726 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000727 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000728
729 // Accumulate the total frequency of inserted spill code.
730 if (Ins)
731 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000732 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000733 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000734
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000735 // Add constraints for use-blocks. Note that these are the only constraints
736 // that may add a positive bias, it is downhill from here.
737 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000738 return SpillPlacer->scanActiveBundles();
739}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000740
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000741
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000742/// addThroughConstraints - Add constraints and links to SpillPlacer from the
743/// live-through blocks in Blocks.
744void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
745 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000746 const unsigned GroupSize = 8;
747 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000748 unsigned TBS[GroupSize];
749 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000750
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000751 for (unsigned i = 0; i != Blocks.size(); ++i) {
752 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000753 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000754
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000755 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000756 assert(T < GroupSize && "Array overflow");
757 TBS[T] = Number;
758 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000759 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000760 T = 0;
761 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000762 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000763 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000764
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000765 assert(B < GroupSize && "Array overflow");
766 BCS[B].Number = Number;
767
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000768 // Interference for the live-in value.
769 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
770 BCS[B].Entry = SpillPlacement::MustSpill;
771 else
772 BCS[B].Entry = SpillPlacement::PrefSpill;
773
774 // Interference for the live-out value.
775 if (Intf.last() >= SA->getLastSplitPoint(Number))
776 BCS[B].Exit = SpillPlacement::MustSpill;
777 else
778 BCS[B].Exit = SpillPlacement::PrefSpill;
779
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000780 if (++B == GroupSize) {
781 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
782 SpillPlacer->addConstraints(Array);
783 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000784 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000785 }
786
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000787 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
788 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000789 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000790}
791
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000792void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000793 // Keep track of through blocks that have not been added to SpillPlacer.
794 BitVector Todo = SA->getThroughBlocks();
795 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
796 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000797#ifndef NDEBUG
798 unsigned Visited = 0;
799#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000800
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000801 for (;;) {
802 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000803 // Find new through blocks in the periphery of PrefRegBundles.
804 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
805 unsigned Bundle = NewBundles[i];
806 // Look at all blocks connected to Bundle in the full graph.
807 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
808 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
809 I != E; ++I) {
810 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000811 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000812 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000813 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000814 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000815 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000816#ifndef NDEBUG
817 ++Visited;
818#endif
819 }
820 }
821 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000822 if (ActiveBlocks.size() == AddedTo)
823 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000824
825 // Compute through constraints from the interference, or assume that all
826 // through blocks prefer spilling when forming compact regions.
827 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
828 if (Cand.PhysReg)
829 addThroughConstraints(Cand.Intf, NewBlocks);
830 else
Jakob Stoklund Olesenb87f91b2011-08-03 23:09:38 +0000831 // Provide a strong negative bias on through blocks to prevent unwanted
832 // liveness on loop backedges.
833 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000834 AddedTo = ActiveBlocks.size();
835
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000836 // Perhaps iterating can enable more bundles?
837 SpillPlacer->iterate();
838 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000839 DEBUG(dbgs() << ", v=" << Visited);
840}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000841
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000842/// calcCompactRegion - Compute the set of edge bundles that should be live
843/// when splitting the current live range into compact regions. Compact
844/// regions can be computed without looking at interference. They are the
845/// regions formed by removing all the live-through blocks from the live range.
846///
847/// Returns false if the current live range is already compact, or if the
848/// compact regions would form single block regions anyway.
849bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
850 // Without any through blocks, the live range is already compact.
851 if (!SA->getNumThroughBlocks())
852 return false;
853
854 // Compact regions don't correspond to any physreg.
855 Cand.reset(IntfCache, 0);
856
857 DEBUG(dbgs() << "Compact region bundles");
858
859 // Use the spill placer to determine the live bundles. GrowRegion pretends
860 // that all the through blocks have interference when PhysReg is unset.
861 SpillPlacer->prepare(Cand.LiveBundles);
862
863 // The static split cost will be zero since Cand.Intf reports no interference.
864 float Cost;
865 if (!addSplitConstraints(Cand.Intf, Cost)) {
866 DEBUG(dbgs() << ", none.\n");
867 return false;
868 }
869
870 growRegion(Cand);
871 SpillPlacer->finish();
872
873 if (!Cand.LiveBundles.any()) {
874 DEBUG(dbgs() << ", none.\n");
875 return false;
876 }
877
878 DEBUG({
879 for (int i = Cand.LiveBundles.find_first(); i>=0;
880 i = Cand.LiveBundles.find_next(i))
881 dbgs() << " EB#" << i;
882 dbgs() << ".\n";
883 });
884 return true;
885}
886
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000887/// calcSpillCost - Compute how expensive it would be to split the live range in
888/// SA around all use blocks instead of forming bundle regions.
889float RAGreedy::calcSpillCost() {
890 float Cost = 0;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000891 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
892 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
893 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
894 unsigned Number = BI.MBB->getNumber();
895 // We normally only need one spill instruction - a load or a store.
896 Cost += SpillPlacer->getBlockFrequency(Number);
897
898 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3f5beed2011-08-02 23:04:08 +0000899 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
900 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000901 }
902 return Cost;
903}
904
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000905/// calcGlobalSplitCost - Return the global split cost of following the split
906/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000907/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000908///
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000909float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000910 float GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000911 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000912 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
913 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
914 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000915 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000916 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
917 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
918 unsigned Ins = 0;
919
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000920 if (BI.LiveIn)
921 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
922 if (BI.LiveOut)
923 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000924 if (Ins)
925 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000926 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000927
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000928 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
929 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000930 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
931 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000932 if (!RegIn && !RegOut)
933 continue;
934 if (RegIn && RegOut) {
935 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000936 Cand.Intf.moveToBlock(Number);
937 if (Cand.Intf.hasInterference())
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000938 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
939 continue;
940 }
941 // live-in / stack-out or stack-in live-out.
942 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000943 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000944 return GlobalCost;
945}
946
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000947/// splitAroundRegion - Split the current live range around the regions
948/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000949///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000950/// Before calling this function, GlobalCand and BundleCand must be initialized
951/// so each bundle is assigned to a valid candidate, or NoCand for the
952/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
953/// objects must be initialized for the current live range, and intervals
954/// created for the used candidates.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000955///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000956/// @param LREdit The LiveRangeEdit object handling the current split.
957/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
958/// must appear in this list.
959void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
960 ArrayRef<unsigned> UsedCands) {
961 // These are the intervals created for new global ranges. We may create more
962 // intervals for local ranges.
963 const unsigned NumGlobalIntvs = LREdit.size();
964 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
965 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000966
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000967 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen69145ba2011-08-06 18:20:24 +0000968 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000969 // is all copies.
970 unsigned Reg = SA->getParent().reg;
971 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
972
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000973 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000974 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
975 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
976 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000977 unsigned Number = BI.MBB->getNumber();
978 unsigned IntvIn = 0, IntvOut = 0;
979 SlotIndex IntfIn, IntfOut;
980 if (BI.LiveIn) {
981 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
982 if (CandIn != NoCand) {
983 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
984 IntvIn = Cand.IntvIdx;
985 Cand.Intf.moveToBlock(Number);
986 IntfIn = Cand.Intf.first();
987 }
988 }
989 if (BI.LiveOut) {
990 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
991 if (CandOut != NoCand) {
992 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
993 IntvOut = Cand.IntvIdx;
994 Cand.Intf.moveToBlock(Number);
995 IntfOut = Cand.Intf.last();
996 }
997 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000998
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000999 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001000 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001001 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001002 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +00001003 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001004 continue;
1005 }
1006
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001007 if (IntvIn && IntvOut)
1008 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1009 else if (IntvIn)
1010 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +00001011 else
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001012 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001013 }
1014
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001015 // Handle live-through blocks. The relevant live-through blocks are stored in
1016 // the ActiveBlocks list with each candidate. We need to filter out
1017 // duplicates.
1018 BitVector Todo = SA->getThroughBlocks();
1019 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1020 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1021 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1022 unsigned Number = Blocks[i];
1023 if (!Todo.test(Number))
1024 continue;
1025 Todo.reset(Number);
1026
1027 unsigned IntvIn = 0, IntvOut = 0;
1028 SlotIndex IntfIn, IntfOut;
1029
1030 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1031 if (CandIn != NoCand) {
1032 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1033 IntvIn = Cand.IntvIdx;
1034 Cand.Intf.moveToBlock(Number);
1035 IntfIn = Cand.Intf.first();
1036 }
1037
1038 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1039 if (CandOut != NoCand) {
1040 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1041 IntvOut = Cand.IntvIdx;
1042 Cand.Intf.moveToBlock(Number);
1043 IntfOut = Cand.Intf.last();
1044 }
1045 if (!IntvIn && !IntvOut)
1046 continue;
1047 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1048 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001049 }
1050
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001051 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001052
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001053 SmallVector<unsigned, 8> IntvMap;
1054 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001055 DebugVars->splitRegister(Reg, LREdit.regs());
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001056
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001057 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +00001058 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001059
1060 // Sort out the new intervals created by splitting. We get four kinds:
1061 // - Remainder intervals should not be split again.
1062 // - Candidate intervals can be assigned to Cand.PhysReg.
1063 // - Block-local splits are candidates for local splitting.
1064 // - DCE leftovers should go back on the queue.
1065 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001066 LiveInterval &Reg = *LREdit.get(i);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001067
1068 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001069 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001070 continue;
1071
1072 // Remainder interval. Don't try splitting again, spill if it doesn't
1073 // allocate.
1074 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001075 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001076 continue;
1077 }
1078
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001079 // Global intervals. Allow repeated splitting as long as the number of live
1080 // blocks is strictly decreasing.
1081 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001082 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001083 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1084 << " blocks as original.\n");
1085 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001086 setStage(Reg, RS_Split2);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001087 }
1088 continue;
1089 }
1090
1091 // Other intervals are treated as new. This includes local intervals created
1092 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001093 }
1094
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001095 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001096 MF->verify(this, "After splitting live range around region");
1097}
1098
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001099unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1100 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001101 unsigned NumCands = 0;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001102 unsigned BestCand = NoCand;
1103 float BestCost;
1104 SmallVector<unsigned, 8> UsedCands;
1105
1106 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +00001107 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001108 if (HasCompact) {
1109 // Yes, keep GlobalCand[0] as the compact region candidate.
1110 NumCands = 1;
1111 BestCost = HUGE_VALF;
1112 } else {
1113 // No benefit from the compact region, our fallback will be per-block
1114 // splitting. Make sure we find a solution that is cheaper than spilling.
1115 BestCost = Hysteresis * calcSpillCost();
1116 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1117 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001118
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001119 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001120 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001121 // Discard bad candidates before we run out of interference cache cursors.
1122 // This will only affect register classes with a lot of registers (>32).
1123 if (NumCands == IntfCache.getMaxCursors()) {
1124 unsigned WorstCount = ~0u;
1125 unsigned Worst = 0;
1126 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001127 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001128 continue;
1129 unsigned Count = GlobalCand[i].LiveBundles.count();
1130 if (Count < WorstCount)
1131 Worst = i, WorstCount = Count;
1132 }
1133 --NumCands;
1134 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen7bdf0062011-11-01 00:02:31 +00001135 if (BestCand == NumCands)
1136 BestCand = Worst;
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001137 }
1138
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001139 if (GlobalCand.size() <= NumCands)
1140 GlobalCand.resize(NumCands+1);
1141 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1142 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001143
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001144 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001145 float Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001146 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001147 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001148 continue;
1149 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001150 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001151 if (Cost >= BestCost) {
1152 DEBUG({
1153 if (BestCand == NoCand)
1154 dbgs() << " worse than no bundles\n";
1155 else
1156 dbgs() << " worse than "
1157 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1158 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001159 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001160 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001161 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001162
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001163 SpillPlacer->finish();
1164
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001165 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001166 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001167 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001168 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001169 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001170
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001171 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001172 DEBUG({
1173 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001174 for (int i = Cand.LiveBundles.find_first(); i>=0;
1175 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001176 dbgs() << " EB#" << i;
1177 dbgs() << ".\n";
1178 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001179 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001180 BestCand = NumCands;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001181 BestCost = Hysteresis * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001182 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001183 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001184 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001185
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001186 // No solutions found, fall back to single block splitting.
1187 if (!HasCompact && BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001188 return 0;
1189
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001190 // Prepare split editor.
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001191 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001192 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001193
1194 // Assign all edge bundles to the preferred candidate, or NoCand.
1195 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1196
1197 // Assign bundles for the best candidate region.
1198 if (BestCand != NoCand) {
1199 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1200 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1201 UsedCands.push_back(BestCand);
1202 Cand.IntvIdx = SE->openIntv();
1203 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1204 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001205 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001206 }
1207 }
1208
1209 // Assign bundles for the compact region.
1210 if (HasCompact) {
1211 GlobalSplitCandidate &Cand = GlobalCand.front();
1212 assert(!Cand.PhysReg && "Compact region has no physreg");
1213 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1214 UsedCands.push_back(0);
1215 Cand.IntvIdx = SE->openIntv();
1216 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1217 << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001218 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001219 }
1220 }
1221
1222 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001223 return 0;
1224}
1225
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001226
1227//===----------------------------------------------------------------------===//
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001228// Per-Block Splitting
1229//===----------------------------------------------------------------------===//
1230
1231/// tryBlockSplit - Split a global live range around every block with uses. This
1232/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1233/// they don't allocate.
1234unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1235 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1236 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1237 unsigned Reg = VirtReg.reg;
1238 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001239 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001240 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001241 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1242 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1243 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1244 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1245 SE->splitSingleBlock(BI);
1246 }
1247 // No blocks were split.
1248 if (LREdit.empty())
1249 return 0;
1250
1251 // We did split for some blocks.
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001252 SmallVector<unsigned, 8> IntvMap;
1253 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001254
1255 // Tell LiveDebugVariables about the new ranges.
1256 DebugVars->splitRegister(Reg, LREdit.regs());
1257
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001258 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1259
1260 // Sort out the new intervals created by splitting. The remainder interval
1261 // goes straight to spilling, the new local ranges get to stay RS_New.
1262 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1263 LiveInterval &LI = *LREdit.get(i);
1264 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1265 setStage(LI, RS_Spill);
1266 }
1267
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001268 if (VerifyEnabled)
1269 MF->verify(this, "After splitting live range around basic blocks");
1270 return 0;
1271}
1272
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001273
1274//===----------------------------------------------------------------------===//
1275// Per-Instruction Splitting
1276//===----------------------------------------------------------------------===//
1277
1278/// tryInstructionSplit - Split a live range around individual instructions.
1279/// This is normally not worthwhile since the spiller is doing essentially the
1280/// same thing. However, when the live range is in a constrained register
1281/// class, it may help to insert copies such that parts of the live range can
1282/// be moved to a larger register class.
1283///
1284/// This is similar to spilling to a larger register class.
1285unsigned
1286RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1287 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1288 // There is no point to this if there are no larger sub-classes.
1289 if (!RegClassInfo.isProperSubClass(MRI->getRegClass(VirtReg.reg)))
1290 return 0;
1291
1292 // Always enable split spill mode, since we're effectively spilling to a
1293 // register.
1294 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1295 SE->reset(LREdit, SplitEditor::SM_Size);
1296
1297 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1298 if (Uses.size() <= 1)
1299 return 0;
1300
1301 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1302
1303 // Split around every non-copy instruction.
1304 for (unsigned i = 0; i != Uses.size(); ++i) {
1305 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1306 if (MI->isFullCopy()) {
1307 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1308 continue;
1309 }
1310 SE->openIntv();
1311 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1312 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1313 SE->useIntv(SegStart, SegStop);
1314 }
1315
1316 if (LREdit.empty()) {
1317 DEBUG(dbgs() << "All uses were copies.\n");
1318 return 0;
1319 }
1320
1321 SmallVector<unsigned, 8> IntvMap;
1322 SE->finish(&IntvMap);
1323 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1324 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1325
1326 // Assign all new registers to RS_Spill. This was the last chance.
1327 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1328 return 0;
1329}
1330
1331
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001332//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001333// Local Splitting
1334//===----------------------------------------------------------------------===//
1335
1336
1337/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1338/// in order to use PhysReg between two entries in SA->UseSlots.
1339///
1340/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1341///
1342void RAGreedy::calcGapWeights(unsigned PhysReg,
1343 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001344 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1345 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001346 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001347 const unsigned NumGaps = Uses.size()-1;
1348
1349 // Start and end points for the interference check.
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001350 SlotIndex StartIdx =
1351 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1352 SlotIndex StopIdx =
1353 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001354
1355 GapWeight.assign(NumGaps, 0.0f);
1356
1357 // Add interference from each overlapping register.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001358 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1359 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1360 .checkInterference())
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001361 continue;
1362
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001363 // We know that VirtReg is a continuous interval from FirstInstr to
1364 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001365 //
1366 // Interference that overlaps an instruction is counted in both gaps
1367 // surrounding the instruction. The exception is interference before
1368 // StartIdx and after StopIdx.
1369 //
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001370 LiveIntervalUnion::SegmentIter IntI =
1371 Matrix->getLiveUnions()[*Units] .find(StartIdx);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001372 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1373 // Skip the gaps before IntI.
1374 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1375 if (++Gap == NumGaps)
1376 break;
1377 if (Gap == NumGaps)
1378 break;
1379
1380 // Update the gaps covered by IntI.
1381 const float weight = IntI.value()->weight;
1382 for (; Gap != NumGaps; ++Gap) {
1383 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1384 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1385 break;
1386 }
1387 if (Gap == NumGaps)
1388 break;
1389 }
1390 }
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001391
1392 // Add fixed interference.
1393 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1394 const LiveInterval &LI = LIS->getRegUnit(*Units);
1395 LiveInterval::const_iterator I = LI.find(StartIdx);
1396 LiveInterval::const_iterator E = LI.end();
1397
1398 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1399 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1400 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1401 if (++Gap == NumGaps)
1402 break;
1403 if (Gap == NumGaps)
1404 break;
1405
1406 for (; Gap != NumGaps; ++Gap) {
1407 GapWeight[Gap] = HUGE_VALF;
1408 if (Uses[Gap+1].getBaseIndex() >= I->end)
1409 break;
1410 }
1411 if (Gap == NumGaps)
1412 break;
1413 }
1414 }
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001415}
1416
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001417/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1418/// basic block.
1419///
1420unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1421 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001422 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1423 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001424
1425 // Note that it is possible to have an interval that is live-in or live-out
1426 // while only covering a single block - A phi-def can use undef values from
1427 // predecessors, and the block could be a single-block loop.
1428 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001429 // that the interval is continuous from FirstInstr to LastInstr. We should
1430 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001431
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001432 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001433 if (Uses.size() <= 2)
1434 return 0;
1435 const unsigned NumGaps = Uses.size()-1;
1436
1437 DEBUG({
1438 dbgs() << "tryLocalSplit: ";
1439 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001440 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001441 dbgs() << '\n';
1442 });
1443
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001444 // If VirtReg is live across any register mask operands, compute a list of
1445 // gaps with register masks.
1446 SmallVector<unsigned, 8> RegMaskGaps;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001447 if (Matrix->checkRegMaskInterference(VirtReg)) {
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001448 // Get regmask slots for the whole block.
1449 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001450 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001451 // Constrain to VirtReg's live range.
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001452 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1453 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001454 unsigned re = RMS.size();
1455 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001456 // Look for Uses[i] <= RMS <= Uses[i+1].
1457 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1458 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001459 continue;
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001460 // Skip a regmask on the same instruction as the last use. It doesn't
1461 // overlap the live range.
1462 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1463 break;
1464 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001465 RegMaskGaps.push_back(i);
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001466 // Advance ri to the next gap. A regmask on one of the uses counts in
1467 // both gaps.
1468 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1469 ++ri;
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001470 }
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001471 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001472 }
1473
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001474 // Since we allow local split results to be split again, there is a risk of
1475 // creating infinite loops. It is tempting to require that the new live
1476 // ranges have less instructions than the original. That would guarantee
1477 // convergence, but it is too strict. A live range with 3 instructions can be
1478 // split 2+3 (including the COPY), and we want to allow that.
1479 //
1480 // Instead we use these rules:
1481 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001482 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001483 // noop split, of course).
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001484 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001485 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001486 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001487 // smaller ranges are marked RS_New.
1488 //
1489 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1490 // excessive splitting and infinite loops.
1491 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001492 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001493
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001494 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001495 unsigned BestBefore = NumGaps;
1496 unsigned BestAfter = 0;
1497 float BestDiff = 0;
1498
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001499 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001500 SmallVector<float, 8> GapWeight;
1501
1502 Order.rewind();
1503 while (unsigned PhysReg = Order.next()) {
1504 // Keep track of the largest spill weight that would need to be evicted in
1505 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1506 calcGapWeights(PhysReg, GapWeight);
1507
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001508 // Remove any gaps with regmask clobbers.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001509 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001510 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1511 GapWeight[RegMaskGaps[i]] = HUGE_VALF;
1512
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001513 // Try to find the best sequence of gaps to close.
1514 // The new spill weight must be larger than any gap interference.
1515
1516 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001517 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001518
1519 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1520 // It is the spill weight that needs to be evicted.
1521 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001522
1523 for (;;) {
1524 // Live before/after split?
1525 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1526 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1527
1528 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1529 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1530 << " i=" << MaxGap);
1531
1532 // Stop before the interval gets so big we wouldn't be making progress.
1533 if (!LiveBefore && !LiveAfter) {
1534 DEBUG(dbgs() << " all\n");
1535 break;
1536 }
1537 // Should the interval be extended or shrunk?
1538 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001539
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001540 // How many gaps would the new range have?
1541 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1542
1543 // Legally, without causing looping?
1544 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1545
1546 if (Legal && MaxGap < HUGE_VALF) {
1547 // Estimate the new spill weight. Each instruction reads or writes the
1548 // register. Conservatively assume there are no read-modify-write
1549 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001550 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001551 // Try to guess the size of the new interval.
1552 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1553 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1554 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001555 // Would this split be possible to allocate?
1556 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001557 DEBUG(dbgs() << " w=" << EstWeight);
1558 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001559 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001560 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001561 if (Diff > BestDiff) {
1562 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001563 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001564 BestBefore = SplitBefore;
1565 BestAfter = SplitAfter;
1566 }
1567 }
1568 }
1569
1570 // Try to shrink.
1571 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001572 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001573 DEBUG(dbgs() << " shrink\n");
1574 // Recompute the max when necessary.
1575 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1576 MaxGap = GapWeight[SplitBefore];
1577 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1578 MaxGap = std::max(MaxGap, GapWeight[i]);
1579 }
1580 continue;
1581 }
1582 MaxGap = 0;
1583 }
1584
1585 // Try to extend the interval.
1586 if (SplitAfter >= NumGaps) {
1587 DEBUG(dbgs() << " end\n");
1588 break;
1589 }
1590
1591 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001592 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001593 }
1594 }
1595
1596 // Didn't find any candidates?
1597 if (BestBefore == NumGaps)
1598 return 0;
1599
1600 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1601 << '-' << Uses[BestAfter] << ", " << BestDiff
1602 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1603
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001604 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001605 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001606
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001607 SE->openIntv();
1608 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1609 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1610 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001611 SmallVector<unsigned, 8> IntvMap;
1612 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001613 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001614
1615 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001616 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001617 // leave the new intervals as RS_New so they can compete.
1618 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1619 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1620 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1621 if (NewGaps >= NumGaps) {
1622 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1623 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001624 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1625 if (IntvMap[i] == 1) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001626 setStage(*LREdit.get(i), RS_Split2);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001627 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1628 }
1629 DEBUG(dbgs() << '\n');
1630 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001631 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001632
1633 return 0;
1634}
1635
1636//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001637// Live Range Splitting
1638//===----------------------------------------------------------------------===//
1639
1640/// trySplit - Try to split VirtReg or one of its interferences, making it
1641/// assignable.
1642/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1643unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1644 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesenccfa4462011-08-05 23:50:33 +00001645 // Ranges must be Split2 or less.
1646 if (getStage(VirtReg) >= RS_Spill)
1647 return 0;
1648
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001649 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001650 if (LIS->intervalIsInOneMBB(VirtReg)) {
1651 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001652 SA->analyze(&VirtReg);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001653 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1654 if (PhysReg || !NewVRegs.empty())
1655 return PhysReg;
1656 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001657 }
1658
1659 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001660
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001661 SA->analyze(&VirtReg);
1662
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001663 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1664 // coalescer. That may cause the range to become allocatable which means that
1665 // tryRegionSplit won't be making progress. This check should be replaced with
1666 // an assertion when the coalescer is fixed.
1667 if (SA->didRepairRange()) {
1668 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001669 Matrix->invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001670 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1671 return PhysReg;
1672 }
1673
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001674 // First try to split around a region spanning multiple blocks. RS_Split2
1675 // ranges already made dubious progress with region splitting, so they go
1676 // straight to single block splitting.
1677 if (getStage(VirtReg) < RS_Split2) {
1678 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1679 if (PhysReg || !NewVRegs.empty())
1680 return PhysReg;
1681 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001682
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001683 // Then isolate blocks.
1684 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001685}
1686
1687
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001688//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001689// Main Entry Point
1690//===----------------------------------------------------------------------===//
1691
1692unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001693 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001694 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001695 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001696 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1697 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001698
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001699 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001700 DEBUG(dbgs() << StageName[Stage]
1701 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001702
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001703 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001704 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001705 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001706 if (Stage != RS_Split)
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001707 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1708 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001709
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001710 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1711
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001712 // The first time we see a live range, don't try to split or spill.
1713 // Wait until the second time, when all smaller ranges have been allocated.
1714 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001715 if (Stage < RS_Split) {
1716 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001717 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001718 NewVRegs.push_back(&VirtReg);
1719 return 0;
1720 }
1721
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001722 // If we couldn't allocate a register from spilling, there is probably some
1723 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001724 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001725 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001726
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001727 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001728 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1729 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001730 return PhysReg;
1731
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001732 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001733 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001734 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001735 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001736 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001737
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001738 if (VerifyEnabled)
1739 MF->verify(this, "After spilling");
1740
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001741 // The live virtual register requesting allocation was spilled, so tell
1742 // the caller not to allocate anything during this round.
1743 return 0;
1744}
1745
1746bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1747 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
David Blaikie986d76d2012-08-22 17:18:53 +00001748 << "********** Function: " << mf.getName() << '\n');
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001749
1750 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001751 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001752 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001753
Jakob Stoklund Olesend4348a22012-06-20 22:52:29 +00001754 RegAllocBase::init(getAnalysis<VirtRegMap>(),
1755 getAnalysis<LiveIntervals>(),
1756 getAnalysis<LiveRegMatrix>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001757 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001758 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001759 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001760 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001761 Bundles = &getAnalysis<EdgeBundles>();
1762 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001763 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001764
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001765 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001766 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001767 ExtraRegInfo.clear();
1768 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1769 NextCascade = 1;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001770 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001771 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001772
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001773 allocatePhysRegs();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001774 releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001775 return true;
1776}