blob: bced80ca5405501e9bff6691a5c669fe7385fc9e [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 Olesenf428eb62010-12-17 23:16:32 +000019#include "LiveRangeEdit.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"
27#include "llvm/Function.h"
28#include "llvm/PassAnalysisSupport.h"
29#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000030#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000031#include "llvm/CodeGen/LiveIntervalAnalysis.h"
32#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 Olesencba2e062010-12-08 03:26:16 +000076 LiveStacks *LS;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000077 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000078 MachineLoopInfo *Loops;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000079 EdgeBundles *Bundles;
80 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +000081 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000082
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000083 // state
84 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000085 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +000086 unsigned NextCascade;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000087
88 // Live ranges pass through a number of stages as we try to allocate them.
89 // Some of the stages may also create new live ranges:
90 //
91 // - Region splitting.
92 // - Per-block splitting.
93 // - Local splitting.
94 // - Spilling.
95 //
96 // Ranges produced by one of the stages skip the previous stages when they are
97 // dequeued. This improves performance because we can skip interference checks
98 // that are unlikely to give any results. It also guarantees that the live
99 // range splitting algorithm terminates, something that is otherwise hard to
100 // ensure.
101 enum LiveRangeStage {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000102 /// Newly created live range that has never been queued.
103 RS_New,
104
105 /// Only attempt assignment and eviction. Then requeue as RS_Split.
106 RS_Assign,
107
108 /// Attempt live range splitting if assignment is impossible.
109 RS_Split,
110
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000111 /// Attempt more aggressive live range splitting that is guaranteed to make
112 /// progress. This is used for split products that may not be making
113 /// progress.
114 RS_Split2,
115
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000116 /// Live range will be spilled. No more splitting will be attempted.
117 RS_Spill,
118
119 /// There is nothing more we can do to this live range. Abort compilation
120 /// if it can't be assigned.
121 RS_Done
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000122 };
123
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000124 static const char *const StageName[];
125
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000126 // RegInfo - Keep additional information about each live range.
127 struct RegInfo {
128 LiveRangeStage Stage;
129
130 // Cascade - Eviction loop prevention. See canEvictInterference().
131 unsigned Cascade;
132
133 RegInfo() : Stage(RS_New), Cascade(0) {}
134 };
135
136 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000137
138 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000139 return ExtraRegInfo[VirtReg.reg].Stage;
140 }
141
142 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
143 ExtraRegInfo.resize(MRI->getNumVirtRegs());
144 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000145 }
146
147 template<typename Iterator>
148 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000149 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000150 for (;Begin != End; ++Begin) {
151 unsigned Reg = (*Begin)->reg;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000152 if (ExtraRegInfo[Reg].Stage == RS_New)
153 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000154 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000155 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000156
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000157 /// Cost of evicting interference.
158 struct EvictionCost {
159 unsigned BrokenHints; ///< Total number of broken hints.
160 float MaxWeight; ///< Maximum spill weight evicted.
161
162 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
163
164 bool operator<(const EvictionCost &O) const {
165 if (BrokenHints != O.BrokenHints)
166 return BrokenHints < O.BrokenHints;
167 return MaxWeight < O.MaxWeight;
168 }
169 };
170
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000171 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000172 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000173 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000174
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000175 /// Cached per-block interference maps
176 InterferenceCache IntfCache;
177
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000178 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000179 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000180
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000181 /// Global live range splitting candidate info.
182 struct GlobalSplitCandidate {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000183 // Register intended for assignment, or 0.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000184 unsigned PhysReg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000185
186 // SplitKit interval index for this candidate.
187 unsigned IntvIdx;
188
189 // Interference for PhysReg.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000190 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000191
192 // Bundles where this candidate should be live.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000193 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000194 SmallVector<unsigned, 8> ActiveBlocks;
195
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000196 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000197 PhysReg = Reg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000198 IntvIdx = 0;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000199 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000200 LiveBundles.clear();
201 ActiveBlocks.clear();
202 }
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000203
204 // Set B[i] = C for every live bundle where B[i] was NoCand.
205 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
206 unsigned Count = 0;
207 for (int i = LiveBundles.find_first(); i >= 0;
208 i = LiveBundles.find_next(i))
209 if (B[i] == NoCand) {
210 B[i] = C;
211 Count++;
212 }
213 return Count;
214 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000215 };
216
217 /// Candidate info for for each PhysReg in AllocationOrder.
218 /// This vector never shrinks, but grows to the size of the largest register
219 /// class.
220 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
221
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000222 enum { NoCand = ~0u };
223
224 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
225 /// NoCand which indicates the stack interval.
226 SmallVector<unsigned, 32> BundleCand;
227
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000228public:
229 RAGreedy();
230
231 /// Return the pass name.
232 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000233 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000234 }
235
236 /// RAGreedy analysis usage.
237 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000238 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000239 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000240 virtual void enqueue(LiveInterval *LI);
241 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000242 virtual unsigned selectOrSplit(LiveInterval&,
243 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000244
245 /// Perform register allocation.
246 virtual bool runOnMachineFunction(MachineFunction &mf);
247
248 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000249
250private:
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000251 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000252 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000253 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000254
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000255 float calcSpillCost();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000256 bool addSplitConstraints(InterferenceCache::Cursor, float&);
257 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000258 void growRegion(GlobalSplitCandidate &Cand);
259 float calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000260 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000261 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000262 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000263 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
264 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
265 void evictInterference(LiveInterval&, unsigned,
266 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000267
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000268 unsigned tryAssign(LiveInterval&, AllocationOrder&,
269 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000270 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000271 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000272 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
273 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +0000274 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
275 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000276 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
277 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000278 unsigned trySplit(LiveInterval&, AllocationOrder&,
279 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000280};
281} // end anonymous namespace
282
283char RAGreedy::ID = 0;
284
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000285#ifndef NDEBUG
286const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000287 "RS_New",
288 "RS_Assign",
289 "RS_Split",
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000290 "RS_Split2",
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000291 "RS_Spill",
292 "RS_Done"
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000293};
294#endif
295
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000296// Hysteresis to use when comparing floats.
297// This helps stabilize decisions based on float comparisons.
298const float Hysteresis = 0.98f;
299
300
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000301FunctionPass* llvm::createGreedyRegisterAllocator() {
302 return new RAGreedy();
303}
304
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000305RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000306 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000307 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000308 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
309 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
310 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000311 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Trick96f678f2012-01-13 06:30:30 +0000312 initializeMachineSchedulerPassPass(*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 Olesenb5fa9332011-01-18 21:13:27 +0000318 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
319 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000320}
321
322void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
323 AU.setPreservesCFG();
324 AU.addRequired<AliasAnalysis>();
325 AU.addPreserved<AliasAnalysis>();
326 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000327 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000328 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000329 AU.addRequired<LiveDebugVariables>();
330 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000331 if (StrongPHIElim)
332 AU.addRequiredID(StrongPHIEliminationID);
Jakob Stoklund Olesen27215672011-08-09 00:29:53 +0000333 AU.addRequiredTransitiveID(RegisterCoalescerPassID);
Andrew Trick96f678f2012-01-13 06:30:30 +0000334 if (EnableMachineSched)
335 AU.addRequiredID(MachineSchedulerPassID);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000336 AU.addRequired<CalculateSpillWeights>();
337 AU.addRequired<LiveStacks>();
338 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000339 AU.addRequired<MachineDominatorTree>();
340 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000341 AU.addRequired<MachineLoopInfo>();
342 AU.addPreserved<MachineLoopInfo>();
343 AU.addRequired<VirtRegMap>();
344 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000345 AU.addRequired<EdgeBundles>();
346 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000347 MachineFunctionPass::getAnalysisUsage(AU);
348}
349
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000350
351//===----------------------------------------------------------------------===//
352// LiveRangeEdit delegate methods
353//===----------------------------------------------------------------------===//
354
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000355bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
356 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
357 unassign(LIS->getInterval(VirtReg), PhysReg);
358 return true;
359 }
360 // Unassigned virtreg is probably in the priority queue.
361 // RegAllocBase will erase it after dequeueing.
362 return false;
363}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000364
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000365void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
366 unsigned PhysReg = VRM->getPhys(VirtReg);
367 if (!PhysReg)
368 return;
369
370 // Register is assigned, put it back on the queue for reassignment.
371 LiveInterval &LI = LIS->getInterval(VirtReg);
372 unassign(LI, PhysReg);
373 enqueue(&LI);
374}
375
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000376void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen0d4fea72011-09-14 17:34:37 +0000377 // Cloning a register we haven't even heard about yet? Just ignore it.
378 if (!ExtraRegInfo.inBounds(Old))
379 return;
380
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000381 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000382 // be split into connected components. The new components are much smaller
383 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000384 // same stage as the parent.
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000385 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000386 ExtraRegInfo.grow(New);
387 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000388}
389
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000390void RAGreedy::releaseMemory() {
391 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000392 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000393 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000394 RegAllocBase::releaseMemory();
395}
396
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000397void RAGreedy::enqueue(LiveInterval *LI) {
398 // Prioritize live ranges by size, assigning larger ranges first.
399 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000400 const unsigned Size = LI->getSize();
401 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000402 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
403 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000404 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000405
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000406 ExtraRegInfo.grow(Reg);
407 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000408 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000409
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000410 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000411 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000412 // everything else has been allocated.
413 Prio = Size;
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000414 } else {
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000415 // Everything is allocated in long->short order. Long ranges that don't fit
416 // should be spilled (or split) ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000417 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000418
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000419 // Boost ranges that have a physical register hint.
420 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
421 Prio |= (1u << 30);
422 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000423
424 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000425}
426
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000427LiveInterval *RAGreedy::dequeue() {
428 if (Queue.empty())
429 return 0;
430 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
431 Queue.pop();
432 return LI;
433}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000434
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000435
436//===----------------------------------------------------------------------===//
437// Direct Assignment
438//===----------------------------------------------------------------------===//
439
440/// tryAssign - Try to assign VirtReg to an available register.
441unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
442 AllocationOrder &Order,
443 SmallVectorImpl<LiveInterval*> &NewVRegs) {
444 Order.rewind();
445 unsigned PhysReg;
446 while ((PhysReg = Order.next()))
447 if (!checkPhysRegInterference(VirtReg, PhysReg))
448 break;
449 if (!PhysReg || Order.isHint(PhysReg))
450 return PhysReg;
451
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000452 // PhysReg is available, but there may be a better choice.
453
454 // If we missed a simple hint, try to cheaply evict interference from the
455 // preferred register.
456 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
457 if (Order.isHint(Hint)) {
458 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
459 EvictionCost MaxCost(1);
460 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
461 evictInterference(VirtReg, Hint, NewVRegs);
462 return Hint;
463 }
464 }
465
466 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000467 unsigned Cost = TRI->getCostPerUse(PhysReg);
468
469 // Most registers have 0 additional cost.
470 if (!Cost)
471 return PhysReg;
472
473 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
474 << '\n');
475 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
476 return CheapReg ? CheapReg : PhysReg;
477}
478
479
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000480//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000481// Interference eviction
482//===----------------------------------------------------------------------===//
483
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000484/// shouldEvict - determine if A should evict the assigned live range B. The
485/// eviction policy defined by this function together with the allocation order
486/// defined by enqueue() decides which registers ultimately end up being split
487/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000488///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000489/// Cascade numbers are used to prevent infinite loops if this function is a
490/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000491///
492/// @param A The live range to be assigned.
493/// @param IsHint True when A is about to be assigned to its preferred
494/// register.
495/// @param B The live range to be evicted.
496/// @param BreaksHint True when B is already assigned to its preferred register.
497bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
498 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000499 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000500
501 // Be fairly aggressive about following hints as long as the evictee can be
502 // split.
503 if (CanSplit && IsHint && !BreaksHint)
504 return true;
505
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000506 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000507}
508
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000509/// canEvictInterference - Return true if all interferences between VirtReg and
510/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
511///
512/// @param VirtReg Live range that is about to be assigned.
513/// @param PhysReg Desired register for assignment.
514/// @prarm IsHint True when PhysReg is VirtReg's preferred register.
515/// @param MaxCost Only look for cheaper candidates and update with new cost
516/// when returning true.
517/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000518bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000519 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000520 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
521 // involved in an eviction before. If a cascade number was assigned, deny
522 // evicting anything with the same or a newer cascade number. This prevents
523 // infinite eviction loops.
524 //
525 // This works out so a register without a cascade number is allowed to evict
526 // anything, and it can be evicted by anything.
527 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
528 if (!Cascade)
529 Cascade = NextCascade;
530
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000531 EvictionCost Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000532 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
533 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000534 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000535 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000536 return false;
537
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000538 // Check if any interfering live range is heavier than MaxWeight.
539 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
540 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000541 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
542 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000543 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000544 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000545 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000546 // Once a live range becomes small enough, it is urgent that we find a
547 // register for it. This is indicated by an infinite spill weight. These
548 // urgent live ranges get to evict almost anything.
549 bool Urgent = !VirtReg.isSpillable() && Intf->isSpillable();
550 // Only evict older cascades or live ranges without a cascade.
551 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
552 if (Cascade <= IntfCascade) {
553 if (!Urgent)
554 return false;
555 // We permit breaking cascades for urgent evictions. It should be the
556 // last resort, though, so make it really expensive.
557 Cost.BrokenHints += 10;
558 }
559 // Would this break a satisfied hint?
560 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
561 // Update eviction cost.
562 Cost.BrokenHints += BreaksHint;
563 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
564 // Abort if this would be too expensive.
565 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000566 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000567 // Finally, apply the eviction policy for non-urgent evictions.
568 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000569 return false;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000570 }
571 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000572 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000573 return true;
574}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000575
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000576/// evictInterference - Evict any interferring registers that prevent VirtReg
577/// from being assigned to Physreg. This assumes that canEvictInterference
578/// returned true.
579void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
580 SmallVectorImpl<LiveInterval*> &NewVRegs) {
581 // Make sure that VirtReg has a cascade number, and assign that cascade
582 // number to every evicted register. These live ranges than then only be
583 // evicted by a newer cascade, preventing infinite loops.
584 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
585 if (!Cascade)
586 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
587
588 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
589 << " interference: Cascade " << Cascade << '\n');
590 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
591 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
592 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
593 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
594 LiveInterval *Intf = Q.interferingVRegs()[i];
595 unassign(*Intf, VRM->getPhys(Intf->reg));
596 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
597 VirtReg.isSpillable() < Intf->isSpillable()) &&
598 "Cannot decrease cascade number, illegal eviction");
599 ExtraRegInfo[Intf->reg].Cascade = Cascade;
600 ++NumEvicted;
601 NewVRegs.push_back(Intf);
602 }
603 }
604}
605
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000606/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000607/// @param VirtReg Currently unassigned virtual register.
608/// @param Order Physregs to try.
609/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000610unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
611 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000612 SmallVectorImpl<LiveInterval*> &NewVRegs,
613 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000614 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
615
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000616 // Keep track of the cheapest interference seen so far.
617 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000618 unsigned BestPhys = 0;
619
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000620 // When we are just looking for a reduced cost per use, don't break any
621 // hints, and only evict smaller spill weights.
622 if (CostPerUseLimit < ~0u) {
623 BestCost.BrokenHints = 0;
624 BestCost.MaxWeight = VirtReg.weight;
625 }
626
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000627 Order.rewind();
628 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000629 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
630 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000631 // The first use of a callee-saved register in a function has cost 1.
632 // Don't start using a CSR when the CostPerUseLimit is low.
633 if (CostPerUseLimit == 1)
634 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
635 if (!MRI->isPhysRegUsed(CSR)) {
636 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
637 << PrintReg(CSR, TRI) << '\n');
638 continue;
639 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000640
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000641 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000642 continue;
643
644 // Best so far.
645 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000646
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000647 // Stop if the hint can be used.
648 if (Order.isHint(PhysReg))
649 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000650 }
651
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000652 if (!BestPhys)
653 return 0;
654
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000655 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000656 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000657}
658
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000659
660//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000661// Region Splitting
662//===----------------------------------------------------------------------===//
663
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000664/// addSplitConstraints - Fill out the SplitConstraints vector based on the
665/// interference pattern in Physreg and its aliases. Add the constraints to
666/// SpillPlacement and return the static cost of this split in Cost, assuming
667/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000668/// Return false if there are no bundles with positive bias.
669bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
670 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000671 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000672
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000673 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000674 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000675 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000676 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
677 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000678 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000679
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000680 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000681 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000682 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
683 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesen5ebca792011-08-02 23:04:06 +0000684 BC.ChangesValue = BI.FirstDef;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000685
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000686 if (!Intf.hasInterference())
687 continue;
688
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000689 // Number of spill code instructions to insert.
690 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000691
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000692 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000693 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000694 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000695 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000696 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000697 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000698 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000699 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000700 }
701
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000702 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000703 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000704 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000705 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000706 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000707 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000708 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000709 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000710 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000711
712 // Accumulate the total frequency of inserted spill code.
713 if (Ins)
714 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000715 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000716 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000717
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000718 // Add constraints for use-blocks. Note that these are the only constraints
719 // that may add a positive bias, it is downhill from here.
720 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000721 return SpillPlacer->scanActiveBundles();
722}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000723
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000724
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000725/// addThroughConstraints - Add constraints and links to SpillPlacer from the
726/// live-through blocks in Blocks.
727void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
728 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000729 const unsigned GroupSize = 8;
730 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000731 unsigned TBS[GroupSize];
732 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000733
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000734 for (unsigned i = 0; i != Blocks.size(); ++i) {
735 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000736 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000737
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000738 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000739 assert(T < GroupSize && "Array overflow");
740 TBS[T] = Number;
741 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000742 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000743 T = 0;
744 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000745 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000746 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000747
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000748 assert(B < GroupSize && "Array overflow");
749 BCS[B].Number = Number;
750
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000751 // Interference for the live-in value.
752 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
753 BCS[B].Entry = SpillPlacement::MustSpill;
754 else
755 BCS[B].Entry = SpillPlacement::PrefSpill;
756
757 // Interference for the live-out value.
758 if (Intf.last() >= SA->getLastSplitPoint(Number))
759 BCS[B].Exit = SpillPlacement::MustSpill;
760 else
761 BCS[B].Exit = SpillPlacement::PrefSpill;
762
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000763 if (++B == GroupSize) {
764 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
765 SpillPlacer->addConstraints(Array);
766 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000767 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000768 }
769
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000770 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
771 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000772 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000773}
774
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000775void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000776 // Keep track of through blocks that have not been added to SpillPlacer.
777 BitVector Todo = SA->getThroughBlocks();
778 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
779 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000780#ifndef NDEBUG
781 unsigned Visited = 0;
782#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000783
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000784 for (;;) {
785 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000786 // Find new through blocks in the periphery of PrefRegBundles.
787 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
788 unsigned Bundle = NewBundles[i];
789 // Look at all blocks connected to Bundle in the full graph.
790 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
791 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
792 I != E; ++I) {
793 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000794 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000795 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000796 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000797 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000798 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000799#ifndef NDEBUG
800 ++Visited;
801#endif
802 }
803 }
804 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000805 if (ActiveBlocks.size() == AddedTo)
806 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000807
808 // Compute through constraints from the interference, or assume that all
809 // through blocks prefer spilling when forming compact regions.
810 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
811 if (Cand.PhysReg)
812 addThroughConstraints(Cand.Intf, NewBlocks);
813 else
Jakob Stoklund Olesenb87f91b2011-08-03 23:09:38 +0000814 // Provide a strong negative bias on through blocks to prevent unwanted
815 // liveness on loop backedges.
816 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000817 AddedTo = ActiveBlocks.size();
818
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000819 // Perhaps iterating can enable more bundles?
820 SpillPlacer->iterate();
821 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000822 DEBUG(dbgs() << ", v=" << Visited);
823}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000824
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000825/// calcCompactRegion - Compute the set of edge bundles that should be live
826/// when splitting the current live range into compact regions. Compact
827/// regions can be computed without looking at interference. They are the
828/// regions formed by removing all the live-through blocks from the live range.
829///
830/// Returns false if the current live range is already compact, or if the
831/// compact regions would form single block regions anyway.
832bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
833 // Without any through blocks, the live range is already compact.
834 if (!SA->getNumThroughBlocks())
835 return false;
836
837 // Compact regions don't correspond to any physreg.
838 Cand.reset(IntfCache, 0);
839
840 DEBUG(dbgs() << "Compact region bundles");
841
842 // Use the spill placer to determine the live bundles. GrowRegion pretends
843 // that all the through blocks have interference when PhysReg is unset.
844 SpillPlacer->prepare(Cand.LiveBundles);
845
846 // The static split cost will be zero since Cand.Intf reports no interference.
847 float Cost;
848 if (!addSplitConstraints(Cand.Intf, Cost)) {
849 DEBUG(dbgs() << ", none.\n");
850 return false;
851 }
852
853 growRegion(Cand);
854 SpillPlacer->finish();
855
856 if (!Cand.LiveBundles.any()) {
857 DEBUG(dbgs() << ", none.\n");
858 return false;
859 }
860
861 DEBUG({
862 for (int i = Cand.LiveBundles.find_first(); i>=0;
863 i = Cand.LiveBundles.find_next(i))
864 dbgs() << " EB#" << i;
865 dbgs() << ".\n";
866 });
867 return true;
868}
869
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000870/// calcSpillCost - Compute how expensive it would be to split the live range in
871/// SA around all use blocks instead of forming bundle regions.
872float RAGreedy::calcSpillCost() {
873 float Cost = 0;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000874 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
875 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
876 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
877 unsigned Number = BI.MBB->getNumber();
878 // We normally only need one spill instruction - a load or a store.
879 Cost += SpillPlacer->getBlockFrequency(Number);
880
881 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3f5beed2011-08-02 23:04:08 +0000882 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
883 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000884 }
885 return Cost;
886}
887
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000888/// calcGlobalSplitCost - Return the global split cost of following the split
889/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000890/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000891///
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000892float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000893 float GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000894 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000895 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
896 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
897 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000898 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000899 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
900 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
901 unsigned Ins = 0;
902
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000903 if (BI.LiveIn)
904 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
905 if (BI.LiveOut)
906 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000907 if (Ins)
908 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000909 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000910
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000911 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
912 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000913 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
914 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000915 if (!RegIn && !RegOut)
916 continue;
917 if (RegIn && RegOut) {
918 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000919 Cand.Intf.moveToBlock(Number);
920 if (Cand.Intf.hasInterference())
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000921 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
922 continue;
923 }
924 // live-in / stack-out or stack-in live-out.
925 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000926 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000927 return GlobalCost;
928}
929
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000930/// splitAroundRegion - Split the current live range around the regions
931/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000932///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000933/// Before calling this function, GlobalCand and BundleCand must be initialized
934/// so each bundle is assigned to a valid candidate, or NoCand for the
935/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
936/// objects must be initialized for the current live range, and intervals
937/// created for the used candidates.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000938///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000939/// @param LREdit The LiveRangeEdit object handling the current split.
940/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
941/// must appear in this list.
942void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
943 ArrayRef<unsigned> UsedCands) {
944 // These are the intervals created for new global ranges. We may create more
945 // intervals for local ranges.
946 const unsigned NumGlobalIntvs = LREdit.size();
947 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
948 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000949
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000950 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen69145ba2011-08-06 18:20:24 +0000951 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000952 // is all copies.
953 unsigned Reg = SA->getParent().reg;
954 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
955
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000956 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000957 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
958 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
959 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000960 unsigned Number = BI.MBB->getNumber();
961 unsigned IntvIn = 0, IntvOut = 0;
962 SlotIndex IntfIn, IntfOut;
963 if (BI.LiveIn) {
964 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
965 if (CandIn != NoCand) {
966 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
967 IntvIn = Cand.IntvIdx;
968 Cand.Intf.moveToBlock(Number);
969 IntfIn = Cand.Intf.first();
970 }
971 }
972 if (BI.LiveOut) {
973 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
974 if (CandOut != NoCand) {
975 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
976 IntvOut = Cand.IntvIdx;
977 Cand.Intf.moveToBlock(Number);
978 IntfOut = Cand.Intf.last();
979 }
980 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000981
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000982 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000983 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000984 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000985 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000986 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000987 continue;
988 }
989
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000990 if (IntvIn && IntvOut)
991 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
992 else if (IntvIn)
993 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +0000994 else
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000995 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000996 }
997
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000998 // Handle live-through blocks. The relevant live-through blocks are stored in
999 // the ActiveBlocks list with each candidate. We need to filter out
1000 // duplicates.
1001 BitVector Todo = SA->getThroughBlocks();
1002 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1003 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1004 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1005 unsigned Number = Blocks[i];
1006 if (!Todo.test(Number))
1007 continue;
1008 Todo.reset(Number);
1009
1010 unsigned IntvIn = 0, IntvOut = 0;
1011 SlotIndex IntfIn, IntfOut;
1012
1013 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1014 if (CandIn != NoCand) {
1015 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1016 IntvIn = Cand.IntvIdx;
1017 Cand.Intf.moveToBlock(Number);
1018 IntfIn = Cand.Intf.first();
1019 }
1020
1021 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1022 if (CandOut != NoCand) {
1023 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1024 IntvOut = Cand.IntvIdx;
1025 Cand.Intf.moveToBlock(Number);
1026 IntfOut = Cand.Intf.last();
1027 }
1028 if (!IntvIn && !IntvOut)
1029 continue;
1030 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1031 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001032 }
1033
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001034 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001035
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001036 SmallVector<unsigned, 8> IntvMap;
1037 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001038 DebugVars->splitRegister(Reg, LREdit.regs());
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001039
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001040 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +00001041 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001042
1043 // Sort out the new intervals created by splitting. We get four kinds:
1044 // - Remainder intervals should not be split again.
1045 // - Candidate intervals can be assigned to Cand.PhysReg.
1046 // - Block-local splits are candidates for local splitting.
1047 // - DCE leftovers should go back on the queue.
1048 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001049 LiveInterval &Reg = *LREdit.get(i);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001050
1051 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001052 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001053 continue;
1054
1055 // Remainder interval. Don't try splitting again, spill if it doesn't
1056 // allocate.
1057 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001058 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001059 continue;
1060 }
1061
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001062 // Global intervals. Allow repeated splitting as long as the number of live
1063 // blocks is strictly decreasing.
1064 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001065 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001066 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1067 << " blocks as original.\n");
1068 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001069 setStage(Reg, RS_Split2);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001070 }
1071 continue;
1072 }
1073
1074 // Other intervals are treated as new. This includes local intervals created
1075 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001076 }
1077
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001078 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001079 MF->verify(this, "After splitting live range around region");
1080}
1081
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001082unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1083 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001084 unsigned NumCands = 0;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001085 unsigned BestCand = NoCand;
1086 float BestCost;
1087 SmallVector<unsigned, 8> UsedCands;
1088
1089 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +00001090 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001091 if (HasCompact) {
1092 // Yes, keep GlobalCand[0] as the compact region candidate.
1093 NumCands = 1;
1094 BestCost = HUGE_VALF;
1095 } else {
1096 // No benefit from the compact region, our fallback will be per-block
1097 // splitting. Make sure we find a solution that is cheaper than spilling.
1098 BestCost = Hysteresis * calcSpillCost();
1099 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1100 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001101
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001102 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001103 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001104 // Discard bad candidates before we run out of interference cache cursors.
1105 // This will only affect register classes with a lot of registers (>32).
1106 if (NumCands == IntfCache.getMaxCursors()) {
1107 unsigned WorstCount = ~0u;
1108 unsigned Worst = 0;
1109 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001110 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001111 continue;
1112 unsigned Count = GlobalCand[i].LiveBundles.count();
1113 if (Count < WorstCount)
1114 Worst = i, WorstCount = Count;
1115 }
1116 --NumCands;
1117 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen7bdf0062011-11-01 00:02:31 +00001118 if (BestCand == NumCands)
1119 BestCand = Worst;
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001120 }
1121
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001122 if (GlobalCand.size() <= NumCands)
1123 GlobalCand.resize(NumCands+1);
1124 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1125 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001126
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001127 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001128 float Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001129 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001130 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001131 continue;
1132 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001133 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001134 if (Cost >= BestCost) {
1135 DEBUG({
1136 if (BestCand == NoCand)
1137 dbgs() << " worse than no bundles\n";
1138 else
1139 dbgs() << " worse than "
1140 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1141 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001142 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001143 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001144 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001145
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001146 SpillPlacer->finish();
1147
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001148 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001149 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001150 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001151 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001152 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001153
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001154 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001155 DEBUG({
1156 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001157 for (int i = Cand.LiveBundles.find_first(); i>=0;
1158 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001159 dbgs() << " EB#" << i;
1160 dbgs() << ".\n";
1161 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001162 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001163 BestCand = NumCands;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001164 BestCost = Hysteresis * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001165 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001166 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001167 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001168
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001169 // No solutions found, fall back to single block splitting.
1170 if (!HasCompact && BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001171 return 0;
1172
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001173 // Prepare split editor.
1174 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001175 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001176
1177 // Assign all edge bundles to the preferred candidate, or NoCand.
1178 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1179
1180 // Assign bundles for the best candidate region.
1181 if (BestCand != NoCand) {
1182 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1183 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1184 UsedCands.push_back(BestCand);
1185 Cand.IntvIdx = SE->openIntv();
1186 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1187 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001188 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001189 }
1190 }
1191
1192 // Assign bundles for the compact region.
1193 if (HasCompact) {
1194 GlobalSplitCandidate &Cand = GlobalCand.front();
1195 assert(!Cand.PhysReg && "Compact region has no physreg");
1196 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1197 UsedCands.push_back(0);
1198 Cand.IntvIdx = SE->openIntv();
1199 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1200 << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001201 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001202 }
1203 }
1204
1205 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001206 return 0;
1207}
1208
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001209
1210//===----------------------------------------------------------------------===//
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001211// Per-Block Splitting
1212//===----------------------------------------------------------------------===//
1213
1214/// tryBlockSplit - Split a global live range around every block with uses. This
1215/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1216/// they don't allocate.
1217unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1218 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1219 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1220 unsigned Reg = VirtReg.reg;
1221 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1222 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001223 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001224 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1225 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1226 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1227 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1228 SE->splitSingleBlock(BI);
1229 }
1230 // No blocks were split.
1231 if (LREdit.empty())
1232 return 0;
1233
1234 // We did split for some blocks.
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001235 SmallVector<unsigned, 8> IntvMap;
1236 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001237
1238 // Tell LiveDebugVariables about the new ranges.
1239 DebugVars->splitRegister(Reg, LREdit.regs());
1240
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001241 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1242
1243 // Sort out the new intervals created by splitting. The remainder interval
1244 // goes straight to spilling, the new local ranges get to stay RS_New.
1245 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1246 LiveInterval &LI = *LREdit.get(i);
1247 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1248 setStage(LI, RS_Spill);
1249 }
1250
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001251 if (VerifyEnabled)
1252 MF->verify(this, "After splitting live range around basic blocks");
1253 return 0;
1254}
1255
1256//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001257// Local Splitting
1258//===----------------------------------------------------------------------===//
1259
1260
1261/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1262/// in order to use PhysReg between two entries in SA->UseSlots.
1263///
1264/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1265///
1266void RAGreedy::calcGapWeights(unsigned PhysReg,
1267 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001268 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1269 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001270 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001271 const unsigned NumGaps = Uses.size()-1;
1272
1273 // Start and end points for the interference check.
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001274 SlotIndex StartIdx =
1275 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1276 SlotIndex StopIdx =
1277 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001278
1279 GapWeight.assign(NumGaps, 0.0f);
1280
1281 // Add interference from each overlapping register.
1282 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
1283 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
1284 .checkInterference())
1285 continue;
1286
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001287 // We know that VirtReg is a continuous interval from FirstInstr to
1288 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001289 //
1290 // Interference that overlaps an instruction is counted in both gaps
1291 // surrounding the instruction. The exception is interference before
1292 // StartIdx and after StopIdx.
1293 //
Jakob Stoklund Olesen93841112012-01-11 23:19:08 +00001294 LiveIntervalUnion::SegmentIter IntI = getLiveUnion(*AI).find(StartIdx);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001295 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1296 // Skip the gaps before IntI.
1297 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1298 if (++Gap == NumGaps)
1299 break;
1300 if (Gap == NumGaps)
1301 break;
1302
1303 // Update the gaps covered by IntI.
1304 const float weight = IntI.value()->weight;
1305 for (; Gap != NumGaps; ++Gap) {
1306 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1307 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1308 break;
1309 }
1310 if (Gap == NumGaps)
1311 break;
1312 }
1313 }
1314}
1315
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001316/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1317/// basic block.
1318///
1319unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1320 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001321 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1322 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001323
1324 // Note that it is possible to have an interval that is live-in or live-out
1325 // while only covering a single block - A phi-def can use undef values from
1326 // predecessors, and the block could be a single-block loop.
1327 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001328 // that the interval is continuous from FirstInstr to LastInstr. We should
1329 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001330
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001331 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001332 if (Uses.size() <= 2)
1333 return 0;
1334 const unsigned NumGaps = Uses.size()-1;
1335
1336 DEBUG({
1337 dbgs() << "tryLocalSplit: ";
1338 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001339 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001340 dbgs() << '\n';
1341 });
1342
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001343 // Since we allow local split results to be split again, there is a risk of
1344 // creating infinite loops. It is tempting to require that the new live
1345 // ranges have less instructions than the original. That would guarantee
1346 // convergence, but it is too strict. A live range with 3 instructions can be
1347 // split 2+3 (including the COPY), and we want to allow that.
1348 //
1349 // Instead we use these rules:
1350 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001351 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001352 // noop split, of course).
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001353 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001354 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001355 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001356 // smaller ranges are marked RS_New.
1357 //
1358 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1359 // excessive splitting and infinite loops.
1360 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001361 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001362
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001363 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001364 unsigned BestBefore = NumGaps;
1365 unsigned BestAfter = 0;
1366 float BestDiff = 0;
1367
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001368 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001369 SmallVector<float, 8> GapWeight;
1370
1371 Order.rewind();
1372 while (unsigned PhysReg = Order.next()) {
1373 // Keep track of the largest spill weight that would need to be evicted in
1374 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1375 calcGapWeights(PhysReg, GapWeight);
1376
1377 // Try to find the best sequence of gaps to close.
1378 // The new spill weight must be larger than any gap interference.
1379
1380 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001381 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001382
1383 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1384 // It is the spill weight that needs to be evicted.
1385 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001386
1387 for (;;) {
1388 // Live before/after split?
1389 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1390 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1391
1392 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1393 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1394 << " i=" << MaxGap);
1395
1396 // Stop before the interval gets so big we wouldn't be making progress.
1397 if (!LiveBefore && !LiveAfter) {
1398 DEBUG(dbgs() << " all\n");
1399 break;
1400 }
1401 // Should the interval be extended or shrunk?
1402 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001403
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001404 // How many gaps would the new range have?
1405 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1406
1407 // Legally, without causing looping?
1408 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1409
1410 if (Legal && MaxGap < HUGE_VALF) {
1411 // Estimate the new spill weight. Each instruction reads or writes the
1412 // register. Conservatively assume there are no read-modify-write
1413 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001414 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001415 // Try to guess the size of the new interval.
1416 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1417 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1418 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001419 // Would this split be possible to allocate?
1420 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001421 DEBUG(dbgs() << " w=" << EstWeight);
1422 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001423 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001424 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001425 if (Diff > BestDiff) {
1426 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001427 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001428 BestBefore = SplitBefore;
1429 BestAfter = SplitAfter;
1430 }
1431 }
1432 }
1433
1434 // Try to shrink.
1435 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001436 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001437 DEBUG(dbgs() << " shrink\n");
1438 // Recompute the max when necessary.
1439 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1440 MaxGap = GapWeight[SplitBefore];
1441 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1442 MaxGap = std::max(MaxGap, GapWeight[i]);
1443 }
1444 continue;
1445 }
1446 MaxGap = 0;
1447 }
1448
1449 // Try to extend the interval.
1450 if (SplitAfter >= NumGaps) {
1451 DEBUG(dbgs() << " end\n");
1452 break;
1453 }
1454
1455 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001456 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001457 }
1458 }
1459
1460 // Didn't find any candidates?
1461 if (BestBefore == NumGaps)
1462 return 0;
1463
1464 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1465 << '-' << Uses[BestAfter] << ", " << BestDiff
1466 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1467
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001468 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001469 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001470
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001471 SE->openIntv();
1472 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1473 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1474 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001475 SmallVector<unsigned, 8> IntvMap;
1476 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001477 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001478
1479 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001480 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001481 // leave the new intervals as RS_New so they can compete.
1482 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1483 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1484 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1485 if (NewGaps >= NumGaps) {
1486 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1487 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001488 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1489 if (IntvMap[i] == 1) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001490 setStage(*LREdit.get(i), RS_Split2);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001491 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1492 }
1493 DEBUG(dbgs() << '\n');
1494 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001495 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001496
1497 return 0;
1498}
1499
1500//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001501// Live Range Splitting
1502//===----------------------------------------------------------------------===//
1503
1504/// trySplit - Try to split VirtReg or one of its interferences, making it
1505/// assignable.
1506/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1507unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1508 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesenccfa4462011-08-05 23:50:33 +00001509 // Ranges must be Split2 or less.
1510 if (getStage(VirtReg) >= RS_Spill)
1511 return 0;
1512
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001513 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001514 if (LIS->intervalIsInOneMBB(VirtReg)) {
1515 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001516 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001517 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001518 }
1519
1520 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001521
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001522 SA->analyze(&VirtReg);
1523
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001524 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1525 // coalescer. That may cause the range to become allocatable which means that
1526 // tryRegionSplit won't be making progress. This check should be replaced with
1527 // an assertion when the coalescer is fixed.
1528 if (SA->didRepairRange()) {
1529 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesenbdda37d2011-05-10 17:37:41 +00001530 invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001531 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1532 return PhysReg;
1533 }
1534
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001535 // First try to split around a region spanning multiple blocks. RS_Split2
1536 // ranges already made dubious progress with region splitting, so they go
1537 // straight to single block splitting.
1538 if (getStage(VirtReg) < RS_Split2) {
1539 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1540 if (PhysReg || !NewVRegs.empty())
1541 return PhysReg;
1542 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001543
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001544 // Then isolate blocks.
1545 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001546}
1547
1548
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001549//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001550// Main Entry Point
1551//===----------------------------------------------------------------------===//
1552
1553unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001554 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001555 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001556 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001557 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1558 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001559
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001560 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001561 DEBUG(dbgs() << StageName[Stage]
1562 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001563
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001564 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001565 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001566 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001567 if (Stage != RS_Split)
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001568 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1569 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001570
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001571 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1572
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001573 // The first time we see a live range, don't try to split or spill.
1574 // Wait until the second time, when all smaller ranges have been allocated.
1575 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001576 if (Stage < RS_Split) {
1577 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001578 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001579 NewVRegs.push_back(&VirtReg);
1580 return 0;
1581 }
1582
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001583 // If we couldn't allocate a register from spilling, there is probably some
1584 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001585 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001586 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001587
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001588 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001589 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1590 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001591 return PhysReg;
1592
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001593 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001594 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001595 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1596 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001597 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001598
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001599 if (VerifyEnabled)
1600 MF->verify(this, "After spilling");
1601
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001602 // The live virtual register requesting allocation was spilled, so tell
1603 // the caller not to allocate anything during this round.
1604 return 0;
1605}
1606
1607bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1608 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1609 << "********** Function: "
1610 << ((Value*)mf.getFunction())->getName() << '\n');
1611
1612 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001613 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001614 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001615
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001616 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001617 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001618 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001619 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001620 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001621 Bundles = &getAnalysis<EdgeBundles>();
1622 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001623 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001624
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001625 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001626 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001627 ExtraRegInfo.clear();
1628 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1629 NextCascade = 1;
Jakob Stoklund Olesen93841112012-01-11 23:19:08 +00001630 IntfCache.init(MF, &getLiveUnion(0), Indexes, TRI);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001631 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001632
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001633 allocatePhysRegs();
1634 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001635 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001636
1637 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001638 {
1639 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001640 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001641 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001642
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001643 // Write out new DBG_VALUE instructions.
Jakob Stoklund Olesenc4769022011-07-31 03:53:42 +00001644 {
1645 NamedRegionTimer T("Emit Debug Info", TimerGroupName, TimePassesIsEnabled);
1646 DebugVars->emitDebugValues(VRM);
1647 }
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001648
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001649 // The pass output is in VirtRegMap. Release all the transient data.
1650 releaseMemory();
1651
1652 return true;
1653}