blob: 16832ceaf3df037133100bb9b658fa2e17eea945 [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
Andrew Trickc1b1c7b2012-01-17 06:54:59 +000054/// EnableMachineSched - temporary flag to enable the machine scheduling pass
55/// until we complete the register allocation pass configuration cleanup.
56static cl::opt<bool>
57EnableMachineSched("enable-misched",
58 cl::desc("Enable the machine instruction scheduling pass."),
59 cl::init(false), cl::Hidden);
60
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +000061static cl::opt<SplitEditor::ComplementSpillMode>
62SplitSpillMode("split-spill-mode", cl::Hidden,
63 cl::desc("Spill mode for splitting live ranges"),
64 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
65 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
66 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
67 clEnumValEnd),
68 cl::init(SplitEditor::SM_Partition));
69
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000070static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
71 createGreedyRegisterAllocator);
72
73namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000074class RAGreedy : public MachineFunctionPass,
75 public RegAllocBase,
76 private LiveRangeEdit::Delegate {
77
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000078 // context
79 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000080
81 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000082 SlotIndexes *Indexes;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000083 LiveStacks *LS;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000084 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000085 MachineLoopInfo *Loops;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000086 EdgeBundles *Bundles;
87 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +000088 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000089
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000090 // state
91 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000092 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +000093 unsigned NextCascade;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000094
95 // Live ranges pass through a number of stages as we try to allocate them.
96 // Some of the stages may also create new live ranges:
97 //
98 // - Region splitting.
99 // - Per-block splitting.
100 // - Local splitting.
101 // - Spilling.
102 //
103 // Ranges produced by one of the stages skip the previous stages when they are
104 // dequeued. This improves performance because we can skip interference checks
105 // that are unlikely to give any results. It also guarantees that the live
106 // range splitting algorithm terminates, something that is otherwise hard to
107 // ensure.
108 enum LiveRangeStage {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000109 /// Newly created live range that has never been queued.
110 RS_New,
111
112 /// Only attempt assignment and eviction. Then requeue as RS_Split.
113 RS_Assign,
114
115 /// Attempt live range splitting if assignment is impossible.
116 RS_Split,
117
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000118 /// Attempt more aggressive live range splitting that is guaranteed to make
119 /// progress. This is used for split products that may not be making
120 /// progress.
121 RS_Split2,
122
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000123 /// Live range will be spilled. No more splitting will be attempted.
124 RS_Spill,
125
126 /// There is nothing more we can do to this live range. Abort compilation
127 /// if it can't be assigned.
128 RS_Done
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000129 };
130
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000131 static const char *const StageName[];
132
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000133 // RegInfo - Keep additional information about each live range.
134 struct RegInfo {
135 LiveRangeStage Stage;
136
137 // Cascade - Eviction loop prevention. See canEvictInterference().
138 unsigned Cascade;
139
140 RegInfo() : Stage(RS_New), Cascade(0) {}
141 };
142
143 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000144
145 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000146 return ExtraRegInfo[VirtReg.reg].Stage;
147 }
148
149 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
150 ExtraRegInfo.resize(MRI->getNumVirtRegs());
151 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000152 }
153
154 template<typename Iterator>
155 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000156 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000157 for (;Begin != End; ++Begin) {
158 unsigned Reg = (*Begin)->reg;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000159 if (ExtraRegInfo[Reg].Stage == RS_New)
160 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000161 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000162 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000163
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000164 /// Cost of evicting interference.
165 struct EvictionCost {
166 unsigned BrokenHints; ///< Total number of broken hints.
167 float MaxWeight; ///< Maximum spill weight evicted.
168
169 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
170
171 bool operator<(const EvictionCost &O) const {
172 if (BrokenHints != O.BrokenHints)
173 return BrokenHints < O.BrokenHints;
174 return MaxWeight < O.MaxWeight;
175 }
176 };
177
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000178 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000179 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000180 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000181
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000182 /// Cached per-block interference maps
183 InterferenceCache IntfCache;
184
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000185 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000186 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000187
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000188 /// Global live range splitting candidate info.
189 struct GlobalSplitCandidate {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000190 // Register intended for assignment, or 0.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000191 unsigned PhysReg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000192
193 // SplitKit interval index for this candidate.
194 unsigned IntvIdx;
195
196 // Interference for PhysReg.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000197 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000198
199 // Bundles where this candidate should be live.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000200 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000201 SmallVector<unsigned, 8> ActiveBlocks;
202
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000203 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000204 PhysReg = Reg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000205 IntvIdx = 0;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000206 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000207 LiveBundles.clear();
208 ActiveBlocks.clear();
209 }
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000210
211 // Set B[i] = C for every live bundle where B[i] was NoCand.
212 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
213 unsigned Count = 0;
214 for (int i = LiveBundles.find_first(); i >= 0;
215 i = LiveBundles.find_next(i))
216 if (B[i] == NoCand) {
217 B[i] = C;
218 Count++;
219 }
220 return Count;
221 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000222 };
223
224 /// Candidate info for for each PhysReg in AllocationOrder.
225 /// This vector never shrinks, but grows to the size of the largest register
226 /// class.
227 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
228
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000229 enum { NoCand = ~0u };
230
231 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
232 /// NoCand which indicates the stack interval.
233 SmallVector<unsigned, 32> BundleCand;
234
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000235public:
236 RAGreedy();
237
238 /// Return the pass name.
239 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000240 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000241 }
242
243 /// RAGreedy analysis usage.
244 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000245 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000246 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000247 virtual void enqueue(LiveInterval *LI);
248 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000249 virtual unsigned selectOrSplit(LiveInterval&,
250 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000251
252 /// Perform register allocation.
253 virtual bool runOnMachineFunction(MachineFunction &mf);
254
255 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000256
257private:
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000258 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000259 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000260 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000261
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000262 float calcSpillCost();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000263 bool addSplitConstraints(InterferenceCache::Cursor, float&);
264 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000265 void growRegion(GlobalSplitCandidate &Cand);
266 float calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000267 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000268 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000269 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000270 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
271 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
272 void evictInterference(LiveInterval&, unsigned,
273 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000274
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000275 unsigned tryAssign(LiveInterval&, AllocationOrder&,
276 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000277 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000278 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000279 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
280 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +0000281 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
282 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000283 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
284 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000285 unsigned trySplit(LiveInterval&, AllocationOrder&,
286 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000287};
288} // end anonymous namespace
289
290char RAGreedy::ID = 0;
291
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000292#ifndef NDEBUG
293const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000294 "RS_New",
295 "RS_Assign",
296 "RS_Split",
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000297 "RS_Split2",
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000298 "RS_Spill",
299 "RS_Done"
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000300};
301#endif
302
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000303// Hysteresis to use when comparing floats.
304// This helps stabilize decisions based on float comparisons.
305const float Hysteresis = 0.98f;
306
307
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000308FunctionPass* llvm::createGreedyRegisterAllocator() {
309 return new RAGreedy();
310}
311
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000312RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000313 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000314 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000315 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
316 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
317 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000318 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Trick96f678f2012-01-13 06:30:30 +0000319 initializeMachineSchedulerPassPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000320 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
321 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
322 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
323 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
324 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000325 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
326 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000327}
328
329void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
330 AU.setPreservesCFG();
331 AU.addRequired<AliasAnalysis>();
332 AU.addPreserved<AliasAnalysis>();
333 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000334 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000335 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000336 AU.addRequired<LiveDebugVariables>();
337 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000338 if (StrongPHIElim)
339 AU.addRequiredID(StrongPHIEliminationID);
Jakob Stoklund Olesen27215672011-08-09 00:29:53 +0000340 AU.addRequiredTransitiveID(RegisterCoalescerPassID);
Andrew Trick96f678f2012-01-13 06:30:30 +0000341 if (EnableMachineSched)
342 AU.addRequiredID(MachineSchedulerPassID);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000343 AU.addRequired<CalculateSpillWeights>();
344 AU.addRequired<LiveStacks>();
345 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000346 AU.addRequired<MachineDominatorTree>();
347 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000348 AU.addRequired<MachineLoopInfo>();
349 AU.addPreserved<MachineLoopInfo>();
350 AU.addRequired<VirtRegMap>();
351 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000352 AU.addRequired<EdgeBundles>();
353 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000354 MachineFunctionPass::getAnalysisUsage(AU);
355}
356
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000357
358//===----------------------------------------------------------------------===//
359// LiveRangeEdit delegate methods
360//===----------------------------------------------------------------------===//
361
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000362bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
363 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
364 unassign(LIS->getInterval(VirtReg), PhysReg);
365 return true;
366 }
367 // Unassigned virtreg is probably in the priority queue.
368 // RegAllocBase will erase it after dequeueing.
369 return false;
370}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000371
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000372void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
373 unsigned PhysReg = VRM->getPhys(VirtReg);
374 if (!PhysReg)
375 return;
376
377 // Register is assigned, put it back on the queue for reassignment.
378 LiveInterval &LI = LIS->getInterval(VirtReg);
379 unassign(LI, PhysReg);
380 enqueue(&LI);
381}
382
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000383void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen0d4fea72011-09-14 17:34:37 +0000384 // Cloning a register we haven't even heard about yet? Just ignore it.
385 if (!ExtraRegInfo.inBounds(Old))
386 return;
387
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000388 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000389 // be split into connected components. The new components are much smaller
390 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000391 // same stage as the parent.
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000392 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000393 ExtraRegInfo.grow(New);
394 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000395}
396
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000397void RAGreedy::releaseMemory() {
398 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000399 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000400 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000401 RegAllocBase::releaseMemory();
402}
403
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000404void RAGreedy::enqueue(LiveInterval *LI) {
405 // Prioritize live ranges by size, assigning larger ranges first.
406 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000407 const unsigned Size = LI->getSize();
408 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000409 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
410 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000411 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000412
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000413 ExtraRegInfo.grow(Reg);
414 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000415 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000416
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000417 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000418 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000419 // everything else has been allocated.
420 Prio = Size;
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000421 } else {
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000422 // Everything is allocated in long->short order. Long ranges that don't fit
423 // should be spilled (or split) ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000424 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000425
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000426 // Boost ranges that have a physical register hint.
427 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
428 Prio |= (1u << 30);
429 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000430
431 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000432}
433
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000434LiveInterval *RAGreedy::dequeue() {
435 if (Queue.empty())
436 return 0;
437 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
438 Queue.pop();
439 return LI;
440}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000441
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000442
443//===----------------------------------------------------------------------===//
444// Direct Assignment
445//===----------------------------------------------------------------------===//
446
447/// tryAssign - Try to assign VirtReg to an available register.
448unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
449 AllocationOrder &Order,
450 SmallVectorImpl<LiveInterval*> &NewVRegs) {
451 Order.rewind();
452 unsigned PhysReg;
453 while ((PhysReg = Order.next()))
454 if (!checkPhysRegInterference(VirtReg, PhysReg))
455 break;
456 if (!PhysReg || Order.isHint(PhysReg))
457 return PhysReg;
458
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000459 // PhysReg is available, but there may be a better choice.
460
461 // If we missed a simple hint, try to cheaply evict interference from the
462 // preferred register.
463 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
464 if (Order.isHint(Hint)) {
465 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
466 EvictionCost MaxCost(1);
467 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
468 evictInterference(VirtReg, Hint, NewVRegs);
469 return Hint;
470 }
471 }
472
473 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000474 unsigned Cost = TRI->getCostPerUse(PhysReg);
475
476 // Most registers have 0 additional cost.
477 if (!Cost)
478 return PhysReg;
479
480 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
481 << '\n');
482 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
483 return CheapReg ? CheapReg : PhysReg;
484}
485
486
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000487//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000488// Interference eviction
489//===----------------------------------------------------------------------===//
490
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000491/// shouldEvict - determine if A should evict the assigned live range B. The
492/// eviction policy defined by this function together with the allocation order
493/// defined by enqueue() decides which registers ultimately end up being split
494/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000495///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000496/// Cascade numbers are used to prevent infinite loops if this function is a
497/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000498///
499/// @param A The live range to be assigned.
500/// @param IsHint True when A is about to be assigned to its preferred
501/// register.
502/// @param B The live range to be evicted.
503/// @param BreaksHint True when B is already assigned to its preferred register.
504bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
505 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000506 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000507
508 // Be fairly aggressive about following hints as long as the evictee can be
509 // split.
510 if (CanSplit && IsHint && !BreaksHint)
511 return true;
512
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000513 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000514}
515
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000516/// canEvictInterference - Return true if all interferences between VirtReg and
517/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
518///
519/// @param VirtReg Live range that is about to be assigned.
520/// @param PhysReg Desired register for assignment.
521/// @prarm IsHint True when PhysReg is VirtReg's preferred register.
522/// @param MaxCost Only look for cheaper candidates and update with new cost
523/// when returning true.
524/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000525bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000526 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000527 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
528 // involved in an eviction before. If a cascade number was assigned, deny
529 // evicting anything with the same or a newer cascade number. This prevents
530 // infinite eviction loops.
531 //
532 // This works out so a register without a cascade number is allowed to evict
533 // anything, and it can be evicted by anything.
534 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
535 if (!Cascade)
536 Cascade = NextCascade;
537
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000538 EvictionCost Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000539 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
540 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000541 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000542 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000543 return false;
544
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000545 // Check if any interfering live range is heavier than MaxWeight.
546 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
547 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000548 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
549 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000550 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000551 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000552 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000553 // Once a live range becomes small enough, it is urgent that we find a
554 // register for it. This is indicated by an infinite spill weight. These
555 // urgent live ranges get to evict almost anything.
556 bool Urgent = !VirtReg.isSpillable() && Intf->isSpillable();
557 // 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');
597 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
598 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
599 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
600 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
601 LiveInterval *Intf = Q.interferingVRegs()[i];
602 unassign(*Intf, VRM->getPhys(Intf->reg));
603 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
604 VirtReg.isSpillable() < Intf->isSpillable()) &&
605 "Cannot decrease cascade number, illegal eviction");
606 ExtraRegInfo[Intf->reg].Cascade = Cascade;
607 ++NumEvicted;
608 NewVRegs.push_back(Intf);
609 }
610 }
611}
612
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000613/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000614/// @param VirtReg Currently unassigned virtual register.
615/// @param Order Physregs to try.
616/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000617unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
618 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000619 SmallVectorImpl<LiveInterval*> &NewVRegs,
620 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000621 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
622
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000623 // Keep track of the cheapest interference seen so far.
624 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000625 unsigned BestPhys = 0;
626
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000627 // When we are just looking for a reduced cost per use, don't break any
628 // hints, and only evict smaller spill weights.
629 if (CostPerUseLimit < ~0u) {
630 BestCost.BrokenHints = 0;
631 BestCost.MaxWeight = VirtReg.weight;
632 }
633
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000634 Order.rewind();
635 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000636 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
637 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000638 // The first use of a callee-saved register in a function has cost 1.
639 // Don't start using a CSR when the CostPerUseLimit is low.
640 if (CostPerUseLimit == 1)
641 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
642 if (!MRI->isPhysRegUsed(CSR)) {
643 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
644 << PrintReg(CSR, TRI) << '\n');
645 continue;
646 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000647
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000648 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000649 continue;
650
651 // Best so far.
652 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000653
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000654 // Stop if the hint can be used.
655 if (Order.isHint(PhysReg))
656 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000657 }
658
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000659 if (!BestPhys)
660 return 0;
661
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000662 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000663 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000664}
665
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000666
667//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000668// Region Splitting
669//===----------------------------------------------------------------------===//
670
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000671/// addSplitConstraints - Fill out the SplitConstraints vector based on the
672/// interference pattern in Physreg and its aliases. Add the constraints to
673/// SpillPlacement and return the static cost of this split in Cost, assuming
674/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000675/// Return false if there are no bundles with positive bias.
676bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
677 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000678 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000679
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000680 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000681 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000682 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000683 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
684 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000685 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000686
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000687 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000688 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000689 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
690 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesen5ebca792011-08-02 23:04:06 +0000691 BC.ChangesValue = BI.FirstDef;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000692
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000693 if (!Intf.hasInterference())
694 continue;
695
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000696 // Number of spill code instructions to insert.
697 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000698
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000699 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000700 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000701 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000702 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000703 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000704 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000705 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000706 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000707 }
708
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000709 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000710 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000711 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000712 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000713 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000714 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000715 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000716 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000717 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000718
719 // Accumulate the total frequency of inserted spill code.
720 if (Ins)
721 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000722 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000723 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000724
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000725 // Add constraints for use-blocks. Note that these are the only constraints
726 // that may add a positive bias, it is downhill from here.
727 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000728 return SpillPlacer->scanActiveBundles();
729}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000730
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000731
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000732/// addThroughConstraints - Add constraints and links to SpillPlacer from the
733/// live-through blocks in Blocks.
734void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
735 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000736 const unsigned GroupSize = 8;
737 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000738 unsigned TBS[GroupSize];
739 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000740
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000741 for (unsigned i = 0; i != Blocks.size(); ++i) {
742 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000743 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000744
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000745 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000746 assert(T < GroupSize && "Array overflow");
747 TBS[T] = Number;
748 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000749 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000750 T = 0;
751 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000752 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000753 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000754
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000755 assert(B < GroupSize && "Array overflow");
756 BCS[B].Number = Number;
757
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000758 // Interference for the live-in value.
759 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
760 BCS[B].Entry = SpillPlacement::MustSpill;
761 else
762 BCS[B].Entry = SpillPlacement::PrefSpill;
763
764 // Interference for the live-out value.
765 if (Intf.last() >= SA->getLastSplitPoint(Number))
766 BCS[B].Exit = SpillPlacement::MustSpill;
767 else
768 BCS[B].Exit = SpillPlacement::PrefSpill;
769
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000770 if (++B == GroupSize) {
771 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
772 SpillPlacer->addConstraints(Array);
773 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000774 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000775 }
776
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000777 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
778 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000779 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000780}
781
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000782void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000783 // Keep track of through blocks that have not been added to SpillPlacer.
784 BitVector Todo = SA->getThroughBlocks();
785 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
786 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000787#ifndef NDEBUG
788 unsigned Visited = 0;
789#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000790
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000791 for (;;) {
792 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000793 // Find new through blocks in the periphery of PrefRegBundles.
794 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
795 unsigned Bundle = NewBundles[i];
796 // Look at all blocks connected to Bundle in the full graph.
797 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
798 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
799 I != E; ++I) {
800 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000801 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000802 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000803 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000804 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000805 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000806#ifndef NDEBUG
807 ++Visited;
808#endif
809 }
810 }
811 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000812 if (ActiveBlocks.size() == AddedTo)
813 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000814
815 // Compute through constraints from the interference, or assume that all
816 // through blocks prefer spilling when forming compact regions.
817 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
818 if (Cand.PhysReg)
819 addThroughConstraints(Cand.Intf, NewBlocks);
820 else
Jakob Stoklund Olesenb87f91b2011-08-03 23:09:38 +0000821 // Provide a strong negative bias on through blocks to prevent unwanted
822 // liveness on loop backedges.
823 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000824 AddedTo = ActiveBlocks.size();
825
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000826 // Perhaps iterating can enable more bundles?
827 SpillPlacer->iterate();
828 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000829 DEBUG(dbgs() << ", v=" << Visited);
830}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000831
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000832/// calcCompactRegion - Compute the set of edge bundles that should be live
833/// when splitting the current live range into compact regions. Compact
834/// regions can be computed without looking at interference. They are the
835/// regions formed by removing all the live-through blocks from the live range.
836///
837/// Returns false if the current live range is already compact, or if the
838/// compact regions would form single block regions anyway.
839bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
840 // Without any through blocks, the live range is already compact.
841 if (!SA->getNumThroughBlocks())
842 return false;
843
844 // Compact regions don't correspond to any physreg.
845 Cand.reset(IntfCache, 0);
846
847 DEBUG(dbgs() << "Compact region bundles");
848
849 // Use the spill placer to determine the live bundles. GrowRegion pretends
850 // that all the through blocks have interference when PhysReg is unset.
851 SpillPlacer->prepare(Cand.LiveBundles);
852
853 // The static split cost will be zero since Cand.Intf reports no interference.
854 float Cost;
855 if (!addSplitConstraints(Cand.Intf, Cost)) {
856 DEBUG(dbgs() << ", none.\n");
857 return false;
858 }
859
860 growRegion(Cand);
861 SpillPlacer->finish();
862
863 if (!Cand.LiveBundles.any()) {
864 DEBUG(dbgs() << ", none.\n");
865 return false;
866 }
867
868 DEBUG({
869 for (int i = Cand.LiveBundles.find_first(); i>=0;
870 i = Cand.LiveBundles.find_next(i))
871 dbgs() << " EB#" << i;
872 dbgs() << ".\n";
873 });
874 return true;
875}
876
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000877/// calcSpillCost - Compute how expensive it would be to split the live range in
878/// SA around all use blocks instead of forming bundle regions.
879float RAGreedy::calcSpillCost() {
880 float Cost = 0;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000881 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
882 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
883 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
884 unsigned Number = BI.MBB->getNumber();
885 // We normally only need one spill instruction - a load or a store.
886 Cost += SpillPlacer->getBlockFrequency(Number);
887
888 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3f5beed2011-08-02 23:04:08 +0000889 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
890 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000891 }
892 return Cost;
893}
894
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000895/// calcGlobalSplitCost - Return the global split cost of following the split
896/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000897/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000898///
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000899float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000900 float GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000901 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000902 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
903 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
904 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000905 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000906 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
907 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
908 unsigned Ins = 0;
909
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000910 if (BI.LiveIn)
911 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
912 if (BI.LiveOut)
913 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000914 if (Ins)
915 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000916 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000917
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000918 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
919 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000920 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
921 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000922 if (!RegIn && !RegOut)
923 continue;
924 if (RegIn && RegOut) {
925 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000926 Cand.Intf.moveToBlock(Number);
927 if (Cand.Intf.hasInterference())
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000928 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
929 continue;
930 }
931 // live-in / stack-out or stack-in live-out.
932 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000933 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000934 return GlobalCost;
935}
936
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000937/// splitAroundRegion - Split the current live range around the regions
938/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000939///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000940/// Before calling this function, GlobalCand and BundleCand must be initialized
941/// so each bundle is assigned to a valid candidate, or NoCand for the
942/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
943/// objects must be initialized for the current live range, and intervals
944/// created for the used candidates.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000945///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000946/// @param LREdit The LiveRangeEdit object handling the current split.
947/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
948/// must appear in this list.
949void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
950 ArrayRef<unsigned> UsedCands) {
951 // These are the intervals created for new global ranges. We may create more
952 // intervals for local ranges.
953 const unsigned NumGlobalIntvs = LREdit.size();
954 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
955 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000956
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000957 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen69145ba2011-08-06 18:20:24 +0000958 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000959 // is all copies.
960 unsigned Reg = SA->getParent().reg;
961 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
962
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000963 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000964 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
965 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
966 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000967 unsigned Number = BI.MBB->getNumber();
968 unsigned IntvIn = 0, IntvOut = 0;
969 SlotIndex IntfIn, IntfOut;
970 if (BI.LiveIn) {
971 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
972 if (CandIn != NoCand) {
973 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
974 IntvIn = Cand.IntvIdx;
975 Cand.Intf.moveToBlock(Number);
976 IntfIn = Cand.Intf.first();
977 }
978 }
979 if (BI.LiveOut) {
980 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
981 if (CandOut != NoCand) {
982 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
983 IntvOut = Cand.IntvIdx;
984 Cand.Intf.moveToBlock(Number);
985 IntfOut = Cand.Intf.last();
986 }
987 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000988
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000989 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000990 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000991 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000992 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000993 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000994 continue;
995 }
996
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000997 if (IntvIn && IntvOut)
998 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
999 else if (IntvIn)
1000 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +00001001 else
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001002 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001003 }
1004
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001005 // Handle live-through blocks. The relevant live-through blocks are stored in
1006 // the ActiveBlocks list with each candidate. We need to filter out
1007 // duplicates.
1008 BitVector Todo = SA->getThroughBlocks();
1009 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1010 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1011 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1012 unsigned Number = Blocks[i];
1013 if (!Todo.test(Number))
1014 continue;
1015 Todo.reset(Number);
1016
1017 unsigned IntvIn = 0, IntvOut = 0;
1018 SlotIndex IntfIn, IntfOut;
1019
1020 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1021 if (CandIn != NoCand) {
1022 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1023 IntvIn = Cand.IntvIdx;
1024 Cand.Intf.moveToBlock(Number);
1025 IntfIn = Cand.Intf.first();
1026 }
1027
1028 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1029 if (CandOut != NoCand) {
1030 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1031 IntvOut = Cand.IntvIdx;
1032 Cand.Intf.moveToBlock(Number);
1033 IntfOut = Cand.Intf.last();
1034 }
1035 if (!IntvIn && !IntvOut)
1036 continue;
1037 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1038 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001039 }
1040
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001041 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001042
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001043 SmallVector<unsigned, 8> IntvMap;
1044 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001045 DebugVars->splitRegister(Reg, LREdit.regs());
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001046
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001047 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +00001048 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001049
1050 // Sort out the new intervals created by splitting. We get four kinds:
1051 // - Remainder intervals should not be split again.
1052 // - Candidate intervals can be assigned to Cand.PhysReg.
1053 // - Block-local splits are candidates for local splitting.
1054 // - DCE leftovers should go back on the queue.
1055 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001056 LiveInterval &Reg = *LREdit.get(i);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001057
1058 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001059 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001060 continue;
1061
1062 // Remainder interval. Don't try splitting again, spill if it doesn't
1063 // allocate.
1064 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001065 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001066 continue;
1067 }
1068
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001069 // Global intervals. Allow repeated splitting as long as the number of live
1070 // blocks is strictly decreasing.
1071 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001072 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001073 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1074 << " blocks as original.\n");
1075 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001076 setStage(Reg, RS_Split2);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001077 }
1078 continue;
1079 }
1080
1081 // Other intervals are treated as new. This includes local intervals created
1082 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001083 }
1084
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001085 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001086 MF->verify(this, "After splitting live range around region");
1087}
1088
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001089unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1090 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001091 unsigned NumCands = 0;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001092 unsigned BestCand = NoCand;
1093 float BestCost;
1094 SmallVector<unsigned, 8> UsedCands;
1095
1096 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +00001097 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001098 if (HasCompact) {
1099 // Yes, keep GlobalCand[0] as the compact region candidate.
1100 NumCands = 1;
1101 BestCost = HUGE_VALF;
1102 } else {
1103 // No benefit from the compact region, our fallback will be per-block
1104 // splitting. Make sure we find a solution that is cheaper than spilling.
1105 BestCost = Hysteresis * calcSpillCost();
1106 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1107 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001108
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001109 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001110 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001111 // Discard bad candidates before we run out of interference cache cursors.
1112 // This will only affect register classes with a lot of registers (>32).
1113 if (NumCands == IntfCache.getMaxCursors()) {
1114 unsigned WorstCount = ~0u;
1115 unsigned Worst = 0;
1116 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001117 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001118 continue;
1119 unsigned Count = GlobalCand[i].LiveBundles.count();
1120 if (Count < WorstCount)
1121 Worst = i, WorstCount = Count;
1122 }
1123 --NumCands;
1124 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen7bdf0062011-11-01 00:02:31 +00001125 if (BestCand == NumCands)
1126 BestCand = Worst;
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001127 }
1128
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001129 if (GlobalCand.size() <= NumCands)
1130 GlobalCand.resize(NumCands+1);
1131 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1132 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001133
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001134 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001135 float Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001136 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001137 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001138 continue;
1139 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001140 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001141 if (Cost >= BestCost) {
1142 DEBUG({
1143 if (BestCand == NoCand)
1144 dbgs() << " worse than no bundles\n";
1145 else
1146 dbgs() << " worse than "
1147 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1148 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001149 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001150 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001151 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001152
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001153 SpillPlacer->finish();
1154
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001155 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001156 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001157 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001158 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001159 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001160
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001161 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001162 DEBUG({
1163 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001164 for (int i = Cand.LiveBundles.find_first(); i>=0;
1165 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001166 dbgs() << " EB#" << i;
1167 dbgs() << ".\n";
1168 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001169 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001170 BestCand = NumCands;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001171 BestCost = Hysteresis * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001172 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001173 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001174 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001175
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001176 // No solutions found, fall back to single block splitting.
1177 if (!HasCompact && BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001178 return 0;
1179
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001180 // Prepare split editor.
1181 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001182 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001183
1184 // Assign all edge bundles to the preferred candidate, or NoCand.
1185 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1186
1187 // Assign bundles for the best candidate region.
1188 if (BestCand != NoCand) {
1189 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1190 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1191 UsedCands.push_back(BestCand);
1192 Cand.IntvIdx = SE->openIntv();
1193 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1194 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001195 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001196 }
1197 }
1198
1199 // Assign bundles for the compact region.
1200 if (HasCompact) {
1201 GlobalSplitCandidate &Cand = GlobalCand.front();
1202 assert(!Cand.PhysReg && "Compact region has no physreg");
1203 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1204 UsedCands.push_back(0);
1205 Cand.IntvIdx = SE->openIntv();
1206 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1207 << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001208 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001209 }
1210 }
1211
1212 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001213 return 0;
1214}
1215
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001216
1217//===----------------------------------------------------------------------===//
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001218// Per-Block Splitting
1219//===----------------------------------------------------------------------===//
1220
1221/// tryBlockSplit - Split a global live range around every block with uses. This
1222/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1223/// they don't allocate.
1224unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1225 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1226 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1227 unsigned Reg = VirtReg.reg;
1228 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1229 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001230 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001231 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1232 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1233 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1234 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1235 SE->splitSingleBlock(BI);
1236 }
1237 // No blocks were split.
1238 if (LREdit.empty())
1239 return 0;
1240
1241 // We did split for some blocks.
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001242 SmallVector<unsigned, 8> IntvMap;
1243 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001244
1245 // Tell LiveDebugVariables about the new ranges.
1246 DebugVars->splitRegister(Reg, LREdit.regs());
1247
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001248 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1249
1250 // Sort out the new intervals created by splitting. The remainder interval
1251 // goes straight to spilling, the new local ranges get to stay RS_New.
1252 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1253 LiveInterval &LI = *LREdit.get(i);
1254 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1255 setStage(LI, RS_Spill);
1256 }
1257
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001258 if (VerifyEnabled)
1259 MF->verify(this, "After splitting live range around basic blocks");
1260 return 0;
1261}
1262
1263//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001264// Local Splitting
1265//===----------------------------------------------------------------------===//
1266
1267
1268/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1269/// in order to use PhysReg between two entries in SA->UseSlots.
1270///
1271/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1272///
1273void RAGreedy::calcGapWeights(unsigned PhysReg,
1274 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001275 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1276 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001277 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001278 const unsigned NumGaps = Uses.size()-1;
1279
1280 // Start and end points for the interference check.
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001281 SlotIndex StartIdx =
1282 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1283 SlotIndex StopIdx =
1284 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001285
1286 GapWeight.assign(NumGaps, 0.0f);
1287
1288 // Add interference from each overlapping register.
1289 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
1290 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
1291 .checkInterference())
1292 continue;
1293
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001294 // We know that VirtReg is a continuous interval from FirstInstr to
1295 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001296 //
1297 // Interference that overlaps an instruction is counted in both gaps
1298 // surrounding the instruction. The exception is interference before
1299 // StartIdx and after StopIdx.
1300 //
Jakob Stoklund Olesen93841112012-01-11 23:19:08 +00001301 LiveIntervalUnion::SegmentIter IntI = getLiveUnion(*AI).find(StartIdx);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001302 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1303 // Skip the gaps before IntI.
1304 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1305 if (++Gap == NumGaps)
1306 break;
1307 if (Gap == NumGaps)
1308 break;
1309
1310 // Update the gaps covered by IntI.
1311 const float weight = IntI.value()->weight;
1312 for (; Gap != NumGaps; ++Gap) {
1313 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1314 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1315 break;
1316 }
1317 if (Gap == NumGaps)
1318 break;
1319 }
1320 }
1321}
1322
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001323/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1324/// basic block.
1325///
1326unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1327 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001328 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1329 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001330
1331 // Note that it is possible to have an interval that is live-in or live-out
1332 // while only covering a single block - A phi-def can use undef values from
1333 // predecessors, and the block could be a single-block loop.
1334 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001335 // that the interval is continuous from FirstInstr to LastInstr. We should
1336 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001337
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001338 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001339 if (Uses.size() <= 2)
1340 return 0;
1341 const unsigned NumGaps = Uses.size()-1;
1342
1343 DEBUG({
1344 dbgs() << "tryLocalSplit: ";
1345 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001346 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001347 dbgs() << '\n';
1348 });
1349
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001350 // Since we allow local split results to be split again, there is a risk of
1351 // creating infinite loops. It is tempting to require that the new live
1352 // ranges have less instructions than the original. That would guarantee
1353 // convergence, but it is too strict. A live range with 3 instructions can be
1354 // split 2+3 (including the COPY), and we want to allow that.
1355 //
1356 // Instead we use these rules:
1357 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001358 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001359 // noop split, of course).
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001360 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001361 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001362 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001363 // smaller ranges are marked RS_New.
1364 //
1365 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1366 // excessive splitting and infinite loops.
1367 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001368 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001369
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001370 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001371 unsigned BestBefore = NumGaps;
1372 unsigned BestAfter = 0;
1373 float BestDiff = 0;
1374
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001375 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001376 SmallVector<float, 8> GapWeight;
1377
1378 Order.rewind();
1379 while (unsigned PhysReg = Order.next()) {
1380 // Keep track of the largest spill weight that would need to be evicted in
1381 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1382 calcGapWeights(PhysReg, GapWeight);
1383
1384 // Try to find the best sequence of gaps to close.
1385 // The new spill weight must be larger than any gap interference.
1386
1387 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001388 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001389
1390 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1391 // It is the spill weight that needs to be evicted.
1392 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001393
1394 for (;;) {
1395 // Live before/after split?
1396 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1397 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1398
1399 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1400 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1401 << " i=" << MaxGap);
1402
1403 // Stop before the interval gets so big we wouldn't be making progress.
1404 if (!LiveBefore && !LiveAfter) {
1405 DEBUG(dbgs() << " all\n");
1406 break;
1407 }
1408 // Should the interval be extended or shrunk?
1409 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001410
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001411 // How many gaps would the new range have?
1412 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1413
1414 // Legally, without causing looping?
1415 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1416
1417 if (Legal && MaxGap < HUGE_VALF) {
1418 // Estimate the new spill weight. Each instruction reads or writes the
1419 // register. Conservatively assume there are no read-modify-write
1420 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001421 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001422 // Try to guess the size of the new interval.
1423 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1424 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1425 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001426 // Would this split be possible to allocate?
1427 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001428 DEBUG(dbgs() << " w=" << EstWeight);
1429 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001430 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001431 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001432 if (Diff > BestDiff) {
1433 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001434 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001435 BestBefore = SplitBefore;
1436 BestAfter = SplitAfter;
1437 }
1438 }
1439 }
1440
1441 // Try to shrink.
1442 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001443 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001444 DEBUG(dbgs() << " shrink\n");
1445 // Recompute the max when necessary.
1446 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1447 MaxGap = GapWeight[SplitBefore];
1448 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1449 MaxGap = std::max(MaxGap, GapWeight[i]);
1450 }
1451 continue;
1452 }
1453 MaxGap = 0;
1454 }
1455
1456 // Try to extend the interval.
1457 if (SplitAfter >= NumGaps) {
1458 DEBUG(dbgs() << " end\n");
1459 break;
1460 }
1461
1462 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001463 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001464 }
1465 }
1466
1467 // Didn't find any candidates?
1468 if (BestBefore == NumGaps)
1469 return 0;
1470
1471 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1472 << '-' << Uses[BestAfter] << ", " << BestDiff
1473 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1474
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001475 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001476 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001477
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001478 SE->openIntv();
1479 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1480 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1481 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001482 SmallVector<unsigned, 8> IntvMap;
1483 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001484 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001485
1486 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001487 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001488 // leave the new intervals as RS_New so they can compete.
1489 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1490 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1491 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1492 if (NewGaps >= NumGaps) {
1493 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1494 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001495 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1496 if (IntvMap[i] == 1) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001497 setStage(*LREdit.get(i), RS_Split2);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001498 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1499 }
1500 DEBUG(dbgs() << '\n');
1501 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001502 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001503
1504 return 0;
1505}
1506
1507//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001508// Live Range Splitting
1509//===----------------------------------------------------------------------===//
1510
1511/// trySplit - Try to split VirtReg or one of its interferences, making it
1512/// assignable.
1513/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1514unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1515 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesenccfa4462011-08-05 23:50:33 +00001516 // Ranges must be Split2 or less.
1517 if (getStage(VirtReg) >= RS_Spill)
1518 return 0;
1519
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001520 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001521 if (LIS->intervalIsInOneMBB(VirtReg)) {
1522 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001523 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001524 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001525 }
1526
1527 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001528
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001529 SA->analyze(&VirtReg);
1530
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001531 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1532 // coalescer. That may cause the range to become allocatable which means that
1533 // tryRegionSplit won't be making progress. This check should be replaced with
1534 // an assertion when the coalescer is fixed.
1535 if (SA->didRepairRange()) {
1536 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesenbdda37d2011-05-10 17:37:41 +00001537 invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001538 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1539 return PhysReg;
1540 }
1541
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001542 // First try to split around a region spanning multiple blocks. RS_Split2
1543 // ranges already made dubious progress with region splitting, so they go
1544 // straight to single block splitting.
1545 if (getStage(VirtReg) < RS_Split2) {
1546 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1547 if (PhysReg || !NewVRegs.empty())
1548 return PhysReg;
1549 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001550
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001551 // Then isolate blocks.
1552 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001553}
1554
1555
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001556//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001557// Main Entry Point
1558//===----------------------------------------------------------------------===//
1559
1560unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001561 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001562 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001563 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001564 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1565 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001566
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001567 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001568 DEBUG(dbgs() << StageName[Stage]
1569 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001570
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001571 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001572 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001573 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001574 if (Stage != RS_Split)
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001575 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1576 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001577
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001578 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1579
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001580 // The first time we see a live range, don't try to split or spill.
1581 // Wait until the second time, when all smaller ranges have been allocated.
1582 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001583 if (Stage < RS_Split) {
1584 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001585 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001586 NewVRegs.push_back(&VirtReg);
1587 return 0;
1588 }
1589
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001590 // If we couldn't allocate a register from spilling, there is probably some
1591 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001592 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001593 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001594
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001595 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001596 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1597 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001598 return PhysReg;
1599
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001600 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001601 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001602 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1603 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001604 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001605
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001606 if (VerifyEnabled)
1607 MF->verify(this, "After spilling");
1608
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001609 // The live virtual register requesting allocation was spilled, so tell
1610 // the caller not to allocate anything during this round.
1611 return 0;
1612}
1613
1614bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1615 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1616 << "********** Function: "
1617 << ((Value*)mf.getFunction())->getName() << '\n');
1618
1619 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001620 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001621 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001622
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001623 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001624 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001625 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001626 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001627 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001628 Bundles = &getAnalysis<EdgeBundles>();
1629 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001630 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001631
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001632 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001633 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001634 ExtraRegInfo.clear();
1635 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1636 NextCascade = 1;
Jakob Stoklund Olesen93841112012-01-11 23:19:08 +00001637 IntfCache.init(MF, &getLiveUnion(0), Indexes, TRI);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001638 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001639
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001640 allocatePhysRegs();
1641 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001642 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001643
1644 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001645 {
1646 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001647 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001648 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001649
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001650 // Write out new DBG_VALUE instructions.
Jakob Stoklund Olesenc4769022011-07-31 03:53:42 +00001651 {
1652 NamedRegionTimer T("Emit Debug Info", TimerGroupName, TimePassesIsEnabled);
1653 DebugVars->emitDebugValues(VRM);
1654 }
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001655
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001656 // The pass output is in VirtRegMap. Release all the transient data.
1657 releaseMemory();
1658
1659 return true;
1660}