blob: 6d84176af261d98b229aea8231d6419f5f8cb09e [file] [log] [blame]
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001//===-- RegAllocGreedy.cpp - greedy register allocator --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the RAGreedy function pass for register allocation in
11// optimized builds.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "regalloc"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +000017#include "AllocationOrder.h"
Jakob Stoklund Olesen5907d862011-04-02 06:03:35 +000018#include "InterferenceCache.h"
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +000019#include "LiveDebugVariables.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000020#include "RegAllocBase.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000021#include "SpillPlacement.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000022#include "Spiller.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000023#include "SplitKit.h"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000024#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000025#include "llvm/Analysis/AliasAnalysis.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000026#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000027#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000028#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper789d5d82012-04-02 22:44:18 +000029#include "llvm/CodeGen/LiveRangeEdit.h"
Jakob Stoklund Olesen1ead68d2012-11-28 19:13:06 +000030#include "llvm/CodeGen/LiveRegMatrix.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000031#include "llvm/CodeGen/LiveStackAnalysis.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000032#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000033#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000034#include "llvm/CodeGen/MachineLoopInfo.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000036#include "llvm/CodeGen/RegAllocRegistry.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000037#include "llvm/CodeGen/VirtRegMap.h"
38#include "llvm/PassAnalysisSupport.h"
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +000039#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000040#include "llvm/Support/Debug.h"
41#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000042#include "llvm/Support/Timer.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000043#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000044#include <queue>
45
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000046using namespace llvm;
47
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000048STATISTIC(NumGlobalSplits, "Number of split global live ranges");
49STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000050STATISTIC(NumEvicted, "Number of interferences evicted");
51
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +000052static cl::opt<SplitEditor::ComplementSpillMode>
53SplitSpillMode("split-spill-mode", cl::Hidden,
54 cl::desc("Spill mode for splitting live ranges"),
55 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
56 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
57 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
58 clEnumValEnd),
59 cl::init(SplitEditor::SM_Partition));
60
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000061static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
62 createGreedyRegisterAllocator);
63
64namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000065class RAGreedy : public MachineFunctionPass,
66 public RegAllocBase,
67 private LiveRangeEdit::Delegate {
68
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000069 // context
70 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000071
72 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000073 SlotIndexes *Indexes;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000074 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000075 MachineLoopInfo *Loops;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000076 EdgeBundles *Bundles;
77 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +000078 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000079
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000080 // state
81 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000082 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +000083 unsigned NextCascade;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000084
85 // Live ranges pass through a number of stages as we try to allocate them.
86 // Some of the stages may also create new live ranges:
87 //
88 // - Region splitting.
89 // - Per-block splitting.
90 // - Local splitting.
91 // - Spilling.
92 //
93 // Ranges produced by one of the stages skip the previous stages when they are
94 // dequeued. This improves performance because we can skip interference checks
95 // that are unlikely to give any results. It also guarantees that the live
96 // range splitting algorithm terminates, something that is otherwise hard to
97 // ensure.
98 enum LiveRangeStage {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +000099 /// Newly created live range that has never been queued.
100 RS_New,
101
102 /// Only attempt assignment and eviction. Then requeue as RS_Split.
103 RS_Assign,
104
105 /// Attempt live range splitting if assignment is impossible.
106 RS_Split,
107
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000108 /// Attempt more aggressive live range splitting that is guaranteed to make
109 /// progress. This is used for split products that may not be making
110 /// progress.
111 RS_Split2,
112
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000113 /// Live range will be spilled. No more splitting will be attempted.
114 RS_Spill,
115
116 /// There is nothing more we can do to this live range. Abort compilation
117 /// if it can't be assigned.
118 RS_Done
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000119 };
120
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000121 static const char *const StageName[];
122
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000123 // RegInfo - Keep additional information about each live range.
124 struct RegInfo {
125 LiveRangeStage Stage;
126
127 // Cascade - Eviction loop prevention. See canEvictInterference().
128 unsigned Cascade;
129
130 RegInfo() : Stage(RS_New), Cascade(0) {}
131 };
132
133 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000134
135 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000136 return ExtraRegInfo[VirtReg.reg].Stage;
137 }
138
139 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
140 ExtraRegInfo.resize(MRI->getNumVirtRegs());
141 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000142 }
143
144 template<typename Iterator>
145 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000146 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000147 for (;Begin != End; ++Begin) {
148 unsigned Reg = (*Begin)->reg;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000149 if (ExtraRegInfo[Reg].Stage == RS_New)
150 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000151 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000152 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000153
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000154 /// Cost of evicting interference.
155 struct EvictionCost {
156 unsigned BrokenHints; ///< Total number of broken hints.
157 float MaxWeight; ///< Maximum spill weight evicted.
158
159 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
160
161 bool operator<(const EvictionCost &O) const {
162 if (BrokenHints != O.BrokenHints)
163 return BrokenHints < O.BrokenHints;
164 return MaxWeight < O.MaxWeight;
165 }
166 };
167
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000168 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000169 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000170 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000171
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000172 /// Cached per-block interference maps
173 InterferenceCache IntfCache;
174
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000175 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000176 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000177
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000178 /// Global live range splitting candidate info.
179 struct GlobalSplitCandidate {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000180 // Register intended for assignment, or 0.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000181 unsigned PhysReg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000182
183 // SplitKit interval index for this candidate.
184 unsigned IntvIdx;
185
186 // Interference for PhysReg.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000187 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000188
189 // Bundles where this candidate should be live.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000190 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000191 SmallVector<unsigned, 8> ActiveBlocks;
192
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000193 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000194 PhysReg = Reg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000195 IntvIdx = 0;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000196 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000197 LiveBundles.clear();
198 ActiveBlocks.clear();
199 }
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000200
201 // Set B[i] = C for every live bundle where B[i] was NoCand.
202 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
203 unsigned Count = 0;
204 for (int i = LiveBundles.find_first(); i >= 0;
205 i = LiveBundles.find_next(i))
206 if (B[i] == NoCand) {
207 B[i] = C;
208 Count++;
209 }
210 return Count;
211 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000212 };
213
214 /// Candidate info for for each PhysReg in AllocationOrder.
215 /// This vector never shrinks, but grows to the size of the largest register
216 /// class.
217 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
218
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000219 enum { NoCand = ~0u };
220
221 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
222 /// NoCand which indicates the stack interval.
223 SmallVector<unsigned, 32> BundleCand;
224
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000225public:
226 RAGreedy();
227
228 /// Return the pass name.
229 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000230 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000231 }
232
233 /// RAGreedy analysis usage.
234 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000235 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000236 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000237 virtual void enqueue(LiveInterval *LI);
238 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000239 virtual unsigned selectOrSplit(LiveInterval&,
240 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000241
242 /// Perform register allocation.
243 virtual bool runOnMachineFunction(MachineFunction &mf);
244
245 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000246
247private:
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000248 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000249 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000250 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000251
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000252 float calcSpillCost();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000253 bool addSplitConstraints(InterferenceCache::Cursor, float&);
254 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000255 void growRegion(GlobalSplitCandidate &Cand);
256 float calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000257 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000258 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000259 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000260 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
261 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
262 void evictInterference(LiveInterval&, unsigned,
263 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000264
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000265 unsigned tryAssign(LiveInterval&, AllocationOrder&,
266 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000267 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000268 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000269 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
270 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +0000271 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
272 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +0000273 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
274 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000275 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
276 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000277 unsigned trySplit(LiveInterval&, AllocationOrder&,
278 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000279};
280} // end anonymous namespace
281
282char RAGreedy::ID = 0;
283
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000284#ifndef NDEBUG
285const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000286 "RS_New",
287 "RS_Assign",
288 "RS_Split",
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000289 "RS_Split2",
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000290 "RS_Spill",
291 "RS_Done"
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000292};
293#endif
294
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000295// Hysteresis to use when comparing floats.
296// This helps stabilize decisions based on float comparisons.
297const float Hysteresis = 0.98f;
298
299
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000300FunctionPass* llvm::createGreedyRegisterAllocator() {
301 return new RAGreedy();
302}
303
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000304RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000305 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000306 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000307 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
308 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000309 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Trick42b7a712012-01-17 06:55:03 +0000310 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000311 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
312 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
313 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
314 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
315 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000316 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000317 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
318 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000319}
320
321void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
322 AU.setPreservesCFG();
323 AU.addRequired<AliasAnalysis>();
324 AU.addPreserved<AliasAnalysis>();
325 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000326 AU.addPreserved<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000327 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000328 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000329 AU.addRequired<LiveDebugVariables>();
330 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000331 AU.addRequired<LiveStacks>();
332 AU.addPreserved<LiveStacks>();
Evan Chengbb36a432012-09-21 20:04:28 +0000333 AU.addRequired<CalculateSpillWeights>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000334 AU.addRequired<MachineDominatorTree>();
335 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000336 AU.addRequired<MachineLoopInfo>();
337 AU.addPreserved<MachineLoopInfo>();
338 AU.addRequired<VirtRegMap>();
339 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000340 AU.addRequired<LiveRegMatrix>();
341 AU.addPreserved<LiveRegMatrix>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000342 AU.addRequired<EdgeBundles>();
343 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000344 MachineFunctionPass::getAnalysisUsage(AU);
345}
346
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000347
348//===----------------------------------------------------------------------===//
349// LiveRangeEdit delegate methods
350//===----------------------------------------------------------------------===//
351
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000352bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000353 if (VRM->hasPhys(VirtReg)) {
354 Matrix->unassign(LIS->getInterval(VirtReg));
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000355 return true;
356 }
357 // Unassigned virtreg is probably in the priority queue.
358 // RegAllocBase will erase it after dequeueing.
359 return false;
360}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000361
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000362void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000363 if (!VRM->hasPhys(VirtReg))
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000364 return;
365
366 // Register is assigned, put it back on the queue for reassignment.
367 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000368 Matrix->unassign(LI);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000369 enqueue(&LI);
370}
371
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000372void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen0d4fea72011-09-14 17:34:37 +0000373 // Cloning a register we haven't even heard about yet? Just ignore it.
374 if (!ExtraRegInfo.inBounds(Old))
375 return;
376
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000377 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000378 // be split into connected components. The new components are much smaller
379 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000380 // same stage as the parent.
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000381 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000382 ExtraRegInfo.grow(New);
383 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000384}
385
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000386void RAGreedy::releaseMemory() {
387 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000388 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000389 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000390}
391
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000392void RAGreedy::enqueue(LiveInterval *LI) {
393 // Prioritize live ranges by size, assigning larger ranges first.
394 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000395 const unsigned Size = LI->getSize();
396 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000397 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
398 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000399 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000400
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000401 ExtraRegInfo.grow(Reg);
402 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000403 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000404
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000405 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000406 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000407 // everything else has been allocated.
408 Prio = Size;
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000409 } else {
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000410 // Everything is allocated in long->short order. Long ranges that don't fit
411 // should be spilled (or split) ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000412 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000413
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000414 // Boost ranges that have a physical register hint.
Jakob Stoklund Olesenfc637442012-12-03 23:23:50 +0000415 if (VRM->hasKnownPreference(Reg))
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000416 Prio |= (1u << 30);
417 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000418
Jakob Stoklund Olesene3b23cd2012-04-02 22:30:39 +0000419 Queue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000420}
421
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000422LiveInterval *RAGreedy::dequeue() {
423 if (Queue.empty())
424 return 0;
Jakob Stoklund Olesene3b23cd2012-04-02 22:30:39 +0000425 LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000426 Queue.pop();
427 return LI;
428}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000429
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000430
431//===----------------------------------------------------------------------===//
432// Direct Assignment
433//===----------------------------------------------------------------------===//
434
435/// tryAssign - Try to assign VirtReg to an available register.
436unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
437 AllocationOrder &Order,
438 SmallVectorImpl<LiveInterval*> &NewVRegs) {
439 Order.rewind();
440 unsigned PhysReg;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000441 while ((PhysReg = Order.next()))
442 if (!Matrix->checkInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000443 break;
Jakob Stoklund Olesenf7999fe2012-12-04 22:25:16 +0000444 if (!PhysReg || Order.isHint())
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000445 return PhysReg;
446
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000447 // PhysReg is available, but there may be a better choice.
448
449 // If we missed a simple hint, try to cheaply evict interference from the
450 // preferred register.
451 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000452 if (Order.isHint(Hint)) {
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000453 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
454 EvictionCost MaxCost(1);
455 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
456 evictInterference(VirtReg, Hint, NewVRegs);
457 return Hint;
458 }
459 }
460
461 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000462 unsigned Cost = TRI->getCostPerUse(PhysReg);
463
464 // Most registers have 0 additional cost.
465 if (!Cost)
466 return PhysReg;
467
468 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
469 << '\n');
470 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
471 return CheapReg ? CheapReg : PhysReg;
472}
473
474
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000475//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000476// Interference eviction
477//===----------------------------------------------------------------------===//
478
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000479/// shouldEvict - determine if A should evict the assigned live range B. The
480/// eviction policy defined by this function together with the allocation order
481/// defined by enqueue() decides which registers ultimately end up being split
482/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000483///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000484/// Cascade numbers are used to prevent infinite loops if this function is a
485/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000486///
487/// @param A The live range to be assigned.
488/// @param IsHint True when A is about to be assigned to its preferred
489/// register.
490/// @param B The live range to be evicted.
491/// @param BreaksHint True when B is already assigned to its preferred register.
492bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
493 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000494 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000495
496 // Be fairly aggressive about following hints as long as the evictee can be
497 // split.
498 if (CanSplit && IsHint && !BreaksHint)
499 return true;
500
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000501 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000502}
503
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000504/// canEvictInterference - Return true if all interferences between VirtReg and
505/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
506///
507/// @param VirtReg Live range that is about to be assigned.
508/// @param PhysReg Desired register for assignment.
Dmitri Gribenko67c89782012-09-12 16:59:47 +0000509/// @param IsHint True when PhysReg is VirtReg's preferred register.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000510/// @param MaxCost Only look for cheaper candidates and update with new cost
511/// when returning true.
512/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000513bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000514 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000515 // It is only possible to evict virtual register interference.
516 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
517 return false;
518
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000519 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
520 // involved in an eviction before. If a cascade number was assigned, deny
521 // evicting anything with the same or a newer cascade number. This prevents
522 // infinite eviction loops.
523 //
524 // This works out so a register without a cascade number is allowed to evict
525 // anything, and it can be evicted by anything.
526 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
527 if (!Cascade)
528 Cascade = NextCascade;
529
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000530 EvictionCost Cost;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000531 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
532 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000533 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000534 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000535 return false;
536
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000537 // Check if any interfering live range is heavier than MaxWeight.
538 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
539 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000540 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
541 "Only expecting virtual register interference from query");
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000542 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000543 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000544 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000545 // Once a live range becomes small enough, it is urgent that we find a
546 // register for it. This is indicated by an infinite spill weight. These
547 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen9cda1be2012-05-30 21:46:58 +0000548 //
549 // Also allow urgent evictions of unspillable ranges from a strictly
550 // larger allocation order.
551 bool Urgent = !VirtReg.isSpillable() &&
552 (Intf->isSpillable() ||
553 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
554 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000555 // Only evict older cascades or live ranges without a cascade.
556 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
557 if (Cascade <= IntfCascade) {
558 if (!Urgent)
559 return false;
560 // We permit breaking cascades for urgent evictions. It should be the
561 // last resort, though, so make it really expensive.
562 Cost.BrokenHints += 10;
563 }
564 // Would this break a satisfied hint?
565 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
566 // Update eviction cost.
567 Cost.BrokenHints += BreaksHint;
568 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
569 // Abort if this would be too expensive.
570 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000571 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000572 // Finally, apply the eviction policy for non-urgent evictions.
573 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000574 return false;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000575 }
576 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000577 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000578 return true;
579}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000580
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000581/// evictInterference - Evict any interferring registers that prevent VirtReg
582/// from being assigned to Physreg. This assumes that canEvictInterference
583/// returned true.
584void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
585 SmallVectorImpl<LiveInterval*> &NewVRegs) {
586 // Make sure that VirtReg has a cascade number, and assign that cascade
587 // number to every evicted register. These live ranges than then only be
588 // evicted by a newer cascade, preventing infinite loops.
589 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
590 if (!Cascade)
591 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
592
593 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
594 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000595
596 // Collect all interfering virtregs first.
597 SmallVector<LiveInterval*, 8> Intfs;
598 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
599 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000600 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000601 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
602 Intfs.append(IVR.begin(), IVR.end());
603 }
604
605 // Evict them second. This will invalidate the queries.
606 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
607 LiveInterval *Intf = Intfs[i];
608 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
609 if (!VRM->hasPhys(Intf->reg))
610 continue;
611 Matrix->unassign(*Intf);
612 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
613 VirtReg.isSpillable() < Intf->isSpillable()) &&
614 "Cannot decrease cascade number, illegal eviction");
615 ExtraRegInfo[Intf->reg].Cascade = Cascade;
616 ++NumEvicted;
617 NewVRegs.push_back(Intf);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000618 }
619}
620
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000621/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000622/// @param VirtReg Currently unassigned virtual register.
623/// @param Order Physregs to try.
624/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000625unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
626 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000627 SmallVectorImpl<LiveInterval*> &NewVRegs,
628 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000629 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
630
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000631 // Keep track of the cheapest interference seen so far.
632 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000633 unsigned BestPhys = 0;
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000634 unsigned OrderLimit = Order.getOrder().size();
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000635
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000636 // When we are just looking for a reduced cost per use, don't break any
637 // hints, and only evict smaller spill weights.
638 if (CostPerUseLimit < ~0u) {
639 BestCost.BrokenHints = 0;
640 BestCost.MaxWeight = VirtReg.weight;
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000641
642 // Check of any registers in RC are below CostPerUseLimit.
643 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
644 unsigned MinCost = RegClassInfo.getMinCost(RC);
645 if (MinCost >= CostPerUseLimit) {
646 DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
647 << ", no cheaper registers to be found.\n");
648 return 0;
649 }
650
651 // It is normal for register classes to have a long tail of registers with
652 // the same cost. We don't need to look at them if they're too expensive.
653 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
654 OrderLimit = RegClassInfo.getLastCostChange(RC);
655 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
656 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000657 }
658
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000659 Order.rewind();
Jakob Stoklund Olesen6d613292013-01-12 00:57:44 +0000660 while (unsigned PhysReg = Order.nextWithDups(OrderLimit)) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000661 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
662 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000663 // The first use of a callee-saved register in a function has cost 1.
664 // Don't start using a CSR when the CostPerUseLimit is low.
665 if (CostPerUseLimit == 1)
666 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
667 if (!MRI->isPhysRegUsed(CSR)) {
668 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
669 << PrintReg(CSR, TRI) << '\n');
670 continue;
671 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000672
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000673 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000674 continue;
675
676 // Best so far.
677 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000678
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000679 // Stop if the hint can be used.
Jakob Stoklund Olesenf7999fe2012-12-04 22:25:16 +0000680 if (Order.isHint())
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000681 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000682 }
683
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000684 if (!BestPhys)
685 return 0;
686
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000687 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000688 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000689}
690
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000691
692//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000693// Region Splitting
694//===----------------------------------------------------------------------===//
695
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000696/// addSplitConstraints - Fill out the SplitConstraints vector based on the
697/// interference pattern in Physreg and its aliases. Add the constraints to
698/// SpillPlacement and return the static cost of this split in Cost, assuming
699/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000700/// Return false if there are no bundles with positive bias.
701bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
702 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000703 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000704
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000705 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000706 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000707 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000708 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
709 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000710 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000711
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000712 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000713 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000714 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
715 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesen5ebca792011-08-02 23:04:06 +0000716 BC.ChangesValue = BI.FirstDef;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000717
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000718 if (!Intf.hasInterference())
719 continue;
720
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000721 // Number of spill code instructions to insert.
722 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000723
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000724 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000725 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000726 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000727 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000728 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000729 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000730 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000731 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000732 }
733
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000734 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000735 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000736 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000737 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000738 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000739 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000740 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000741 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000742 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000743
744 // Accumulate the total frequency of inserted spill code.
745 if (Ins)
746 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000747 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000748 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000749
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000750 // Add constraints for use-blocks. Note that these are the only constraints
751 // that may add a positive bias, it is downhill from here.
752 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000753 return SpillPlacer->scanActiveBundles();
754}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000755
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000756
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000757/// addThroughConstraints - Add constraints and links to SpillPlacer from the
758/// live-through blocks in Blocks.
759void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
760 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000761 const unsigned GroupSize = 8;
762 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000763 unsigned TBS[GroupSize];
764 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000765
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000766 for (unsigned i = 0; i != Blocks.size(); ++i) {
767 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000768 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000769
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000770 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000771 assert(T < GroupSize && "Array overflow");
772 TBS[T] = Number;
773 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000774 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000775 T = 0;
776 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000777 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000778 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000779
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000780 assert(B < GroupSize && "Array overflow");
781 BCS[B].Number = Number;
782
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000783 // Interference for the live-in value.
784 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
785 BCS[B].Entry = SpillPlacement::MustSpill;
786 else
787 BCS[B].Entry = SpillPlacement::PrefSpill;
788
789 // Interference for the live-out value.
790 if (Intf.last() >= SA->getLastSplitPoint(Number))
791 BCS[B].Exit = SpillPlacement::MustSpill;
792 else
793 BCS[B].Exit = SpillPlacement::PrefSpill;
794
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000795 if (++B == GroupSize) {
796 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
797 SpillPlacer->addConstraints(Array);
798 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000799 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000800 }
801
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000802 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
803 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000804 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000805}
806
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000807void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000808 // Keep track of through blocks that have not been added to SpillPlacer.
809 BitVector Todo = SA->getThroughBlocks();
810 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
811 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000812#ifndef NDEBUG
813 unsigned Visited = 0;
814#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000815
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000816 for (;;) {
817 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000818 // Find new through blocks in the periphery of PrefRegBundles.
819 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
820 unsigned Bundle = NewBundles[i];
821 // Look at all blocks connected to Bundle in the full graph.
822 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
823 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
824 I != E; ++I) {
825 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000826 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000827 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000828 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000829 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000830 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000831#ifndef NDEBUG
832 ++Visited;
833#endif
834 }
835 }
836 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000837 if (ActiveBlocks.size() == AddedTo)
838 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000839
840 // Compute through constraints from the interference, or assume that all
841 // through blocks prefer spilling when forming compact regions.
842 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
843 if (Cand.PhysReg)
844 addThroughConstraints(Cand.Intf, NewBlocks);
845 else
Jakob Stoklund Olesenb87f91b2011-08-03 23:09:38 +0000846 // Provide a strong negative bias on through blocks to prevent unwanted
847 // liveness on loop backedges.
848 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000849 AddedTo = ActiveBlocks.size();
850
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000851 // Perhaps iterating can enable more bundles?
852 SpillPlacer->iterate();
853 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000854 DEBUG(dbgs() << ", v=" << Visited);
855}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000856
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000857/// calcCompactRegion - Compute the set of edge bundles that should be live
858/// when splitting the current live range into compact regions. Compact
859/// regions can be computed without looking at interference. They are the
860/// regions formed by removing all the live-through blocks from the live range.
861///
862/// Returns false if the current live range is already compact, or if the
863/// compact regions would form single block regions anyway.
864bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
865 // Without any through blocks, the live range is already compact.
866 if (!SA->getNumThroughBlocks())
867 return false;
868
869 // Compact regions don't correspond to any physreg.
870 Cand.reset(IntfCache, 0);
871
872 DEBUG(dbgs() << "Compact region bundles");
873
874 // Use the spill placer to determine the live bundles. GrowRegion pretends
875 // that all the through blocks have interference when PhysReg is unset.
876 SpillPlacer->prepare(Cand.LiveBundles);
877
878 // The static split cost will be zero since Cand.Intf reports no interference.
879 float Cost;
880 if (!addSplitConstraints(Cand.Intf, Cost)) {
881 DEBUG(dbgs() << ", none.\n");
882 return false;
883 }
884
885 growRegion(Cand);
886 SpillPlacer->finish();
887
888 if (!Cand.LiveBundles.any()) {
889 DEBUG(dbgs() << ", none.\n");
890 return false;
891 }
892
893 DEBUG({
894 for (int i = Cand.LiveBundles.find_first(); i>=0;
895 i = Cand.LiveBundles.find_next(i))
896 dbgs() << " EB#" << i;
897 dbgs() << ".\n";
898 });
899 return true;
900}
901
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000902/// calcSpillCost - Compute how expensive it would be to split the live range in
903/// SA around all use blocks instead of forming bundle regions.
904float RAGreedy::calcSpillCost() {
905 float Cost = 0;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000906 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
907 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
908 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
909 unsigned Number = BI.MBB->getNumber();
910 // We normally only need one spill instruction - a load or a store.
911 Cost += SpillPlacer->getBlockFrequency(Number);
912
913 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3f5beed2011-08-02 23:04:08 +0000914 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
915 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000916 }
917 return Cost;
918}
919
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000920/// calcGlobalSplitCost - Return the global split cost of following the split
921/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000922/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000923///
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000924float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000925 float GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000926 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000927 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
928 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
929 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000930 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000931 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
932 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
933 unsigned Ins = 0;
934
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000935 if (BI.LiveIn)
936 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
937 if (BI.LiveOut)
938 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000939 if (Ins)
940 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000941 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000942
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000943 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
944 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000945 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
946 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000947 if (!RegIn && !RegOut)
948 continue;
949 if (RegIn && RegOut) {
950 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000951 Cand.Intf.moveToBlock(Number);
952 if (Cand.Intf.hasInterference())
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000953 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
954 continue;
955 }
956 // live-in / stack-out or stack-in live-out.
957 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000958 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000959 return GlobalCost;
960}
961
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000962/// splitAroundRegion - Split the current live range around the regions
963/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000964///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000965/// Before calling this function, GlobalCand and BundleCand must be initialized
966/// so each bundle is assigned to a valid candidate, or NoCand for the
967/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
968/// objects must be initialized for the current live range, and intervals
969/// created for the used candidates.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000970///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000971/// @param LREdit The LiveRangeEdit object handling the current split.
972/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
973/// must appear in this list.
974void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
975 ArrayRef<unsigned> UsedCands) {
976 // These are the intervals created for new global ranges. We may create more
977 // intervals for local ranges.
978 const unsigned NumGlobalIntvs = LREdit.size();
979 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
980 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000981
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000982 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen69145ba2011-08-06 18:20:24 +0000983 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000984 // is all copies.
985 unsigned Reg = SA->getParent().reg;
986 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
987
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000988 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000989 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
990 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
991 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000992 unsigned Number = BI.MBB->getNumber();
993 unsigned IntvIn = 0, IntvOut = 0;
994 SlotIndex IntfIn, IntfOut;
995 if (BI.LiveIn) {
996 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
997 if (CandIn != NoCand) {
998 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
999 IntvIn = Cand.IntvIdx;
1000 Cand.Intf.moveToBlock(Number);
1001 IntfIn = Cand.Intf.first();
1002 }
1003 }
1004 if (BI.LiveOut) {
1005 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1006 if (CandOut != NoCand) {
1007 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1008 IntvOut = Cand.IntvIdx;
1009 Cand.Intf.moveToBlock(Number);
1010 IntfOut = Cand.Intf.last();
1011 }
1012 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001013
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001014 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001015 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001016 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001017 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +00001018 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001019 continue;
1020 }
1021
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001022 if (IntvIn && IntvOut)
1023 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1024 else if (IntvIn)
1025 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +00001026 else
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001027 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001028 }
1029
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001030 // Handle live-through blocks. The relevant live-through blocks are stored in
1031 // the ActiveBlocks list with each candidate. We need to filter out
1032 // duplicates.
1033 BitVector Todo = SA->getThroughBlocks();
1034 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1035 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1036 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1037 unsigned Number = Blocks[i];
1038 if (!Todo.test(Number))
1039 continue;
1040 Todo.reset(Number);
1041
1042 unsigned IntvIn = 0, IntvOut = 0;
1043 SlotIndex IntfIn, IntfOut;
1044
1045 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1046 if (CandIn != NoCand) {
1047 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1048 IntvIn = Cand.IntvIdx;
1049 Cand.Intf.moveToBlock(Number);
1050 IntfIn = Cand.Intf.first();
1051 }
1052
1053 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1054 if (CandOut != NoCand) {
1055 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1056 IntvOut = Cand.IntvIdx;
1057 Cand.Intf.moveToBlock(Number);
1058 IntfOut = Cand.Intf.last();
1059 }
1060 if (!IntvIn && !IntvOut)
1061 continue;
1062 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1063 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001064 }
1065
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001066 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001067
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001068 SmallVector<unsigned, 8> IntvMap;
1069 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001070 DebugVars->splitRegister(Reg, LREdit.regs());
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001071
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001072 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +00001073 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001074
1075 // Sort out the new intervals created by splitting. We get four kinds:
1076 // - Remainder intervals should not be split again.
1077 // - Candidate intervals can be assigned to Cand.PhysReg.
1078 // - Block-local splits are candidates for local splitting.
1079 // - DCE leftovers should go back on the queue.
1080 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001081 LiveInterval &Reg = *LREdit.get(i);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001082
1083 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001084 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001085 continue;
1086
1087 // Remainder interval. Don't try splitting again, spill if it doesn't
1088 // allocate.
1089 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001090 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001091 continue;
1092 }
1093
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001094 // Global intervals. Allow repeated splitting as long as the number of live
1095 // blocks is strictly decreasing.
1096 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001097 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001098 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1099 << " blocks as original.\n");
1100 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001101 setStage(Reg, RS_Split2);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001102 }
1103 continue;
1104 }
1105
1106 // Other intervals are treated as new. This includes local intervals created
1107 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001108 }
1109
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001110 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001111 MF->verify(this, "After splitting live range around region");
1112}
1113
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001114unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1115 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001116 unsigned NumCands = 0;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001117 unsigned BestCand = NoCand;
1118 float BestCost;
1119 SmallVector<unsigned, 8> UsedCands;
1120
1121 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +00001122 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001123 if (HasCompact) {
1124 // Yes, keep GlobalCand[0] as the compact region candidate.
1125 NumCands = 1;
1126 BestCost = HUGE_VALF;
1127 } else {
1128 // No benefit from the compact region, our fallback will be per-block
1129 // splitting. Make sure we find a solution that is cheaper than spilling.
1130 BestCost = Hysteresis * calcSpillCost();
1131 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1132 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001133
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001134 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001135 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001136 // Discard bad candidates before we run out of interference cache cursors.
1137 // This will only affect register classes with a lot of registers (>32).
1138 if (NumCands == IntfCache.getMaxCursors()) {
1139 unsigned WorstCount = ~0u;
1140 unsigned Worst = 0;
1141 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001142 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001143 continue;
1144 unsigned Count = GlobalCand[i].LiveBundles.count();
1145 if (Count < WorstCount)
1146 Worst = i, WorstCount = Count;
1147 }
1148 --NumCands;
1149 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen7bdf0062011-11-01 00:02:31 +00001150 if (BestCand == NumCands)
1151 BestCand = Worst;
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001152 }
1153
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001154 if (GlobalCand.size() <= NumCands)
1155 GlobalCand.resize(NumCands+1);
1156 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1157 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001158
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001159 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001160 float Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001161 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001162 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001163 continue;
1164 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001165 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001166 if (Cost >= BestCost) {
1167 DEBUG({
1168 if (BestCand == NoCand)
1169 dbgs() << " worse than no bundles\n";
1170 else
1171 dbgs() << " worse than "
1172 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1173 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001174 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001175 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001176 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001177
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001178 SpillPlacer->finish();
1179
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001180 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001181 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001182 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001183 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001184 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001185
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001186 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001187 DEBUG({
1188 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001189 for (int i = Cand.LiveBundles.find_first(); i>=0;
1190 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001191 dbgs() << " EB#" << i;
1192 dbgs() << ".\n";
1193 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001194 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001195 BestCand = NumCands;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001196 BestCost = Hysteresis * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001197 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001198 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001199 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001200
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001201 // No solutions found, fall back to single block splitting.
1202 if (!HasCompact && BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001203 return 0;
1204
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001205 // Prepare split editor.
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001206 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001207 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001208
1209 // Assign all edge bundles to the preferred candidate, or NoCand.
1210 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1211
1212 // Assign bundles for the best candidate region.
1213 if (BestCand != NoCand) {
1214 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1215 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1216 UsedCands.push_back(BestCand);
1217 Cand.IntvIdx = SE->openIntv();
1218 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1219 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001220 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001221 }
1222 }
1223
1224 // Assign bundles for the compact region.
1225 if (HasCompact) {
1226 GlobalSplitCandidate &Cand = GlobalCand.front();
1227 assert(!Cand.PhysReg && "Compact region has no physreg");
1228 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1229 UsedCands.push_back(0);
1230 Cand.IntvIdx = SE->openIntv();
1231 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1232 << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001233 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001234 }
1235 }
1236
1237 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001238 return 0;
1239}
1240
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001241
1242//===----------------------------------------------------------------------===//
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001243// Per-Block Splitting
1244//===----------------------------------------------------------------------===//
1245
1246/// tryBlockSplit - Split a global live range around every block with uses. This
1247/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1248/// they don't allocate.
1249unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1250 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1251 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1252 unsigned Reg = VirtReg.reg;
1253 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001254 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001255 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001256 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1257 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1258 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1259 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1260 SE->splitSingleBlock(BI);
1261 }
1262 // No blocks were split.
1263 if (LREdit.empty())
1264 return 0;
1265
1266 // We did split for some blocks.
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001267 SmallVector<unsigned, 8> IntvMap;
1268 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001269
1270 // Tell LiveDebugVariables about the new ranges.
1271 DebugVars->splitRegister(Reg, LREdit.regs());
1272
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001273 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1274
1275 // Sort out the new intervals created by splitting. The remainder interval
1276 // goes straight to spilling, the new local ranges get to stay RS_New.
1277 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1278 LiveInterval &LI = *LREdit.get(i);
1279 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1280 setStage(LI, RS_Spill);
1281 }
1282
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001283 if (VerifyEnabled)
1284 MF->verify(this, "After splitting live range around basic blocks");
1285 return 0;
1286}
1287
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001288
1289//===----------------------------------------------------------------------===//
1290// Per-Instruction Splitting
1291//===----------------------------------------------------------------------===//
1292
1293/// tryInstructionSplit - Split a live range around individual instructions.
1294/// This is normally not worthwhile since the spiller is doing essentially the
1295/// same thing. However, when the live range is in a constrained register
1296/// class, it may help to insert copies such that parts of the live range can
1297/// be moved to a larger register class.
1298///
1299/// This is similar to spilling to a larger register class.
1300unsigned
1301RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1302 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1303 // There is no point to this if there are no larger sub-classes.
1304 if (!RegClassInfo.isProperSubClass(MRI->getRegClass(VirtReg.reg)))
1305 return 0;
1306
1307 // Always enable split spill mode, since we're effectively spilling to a
1308 // register.
1309 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1310 SE->reset(LREdit, SplitEditor::SM_Size);
1311
1312 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1313 if (Uses.size() <= 1)
1314 return 0;
1315
1316 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1317
1318 // Split around every non-copy instruction.
1319 for (unsigned i = 0; i != Uses.size(); ++i) {
1320 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1321 if (MI->isFullCopy()) {
1322 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1323 continue;
1324 }
1325 SE->openIntv();
1326 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1327 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1328 SE->useIntv(SegStart, SegStop);
1329 }
1330
1331 if (LREdit.empty()) {
1332 DEBUG(dbgs() << "All uses were copies.\n");
1333 return 0;
1334 }
1335
1336 SmallVector<unsigned, 8> IntvMap;
1337 SE->finish(&IntvMap);
1338 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1339 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1340
1341 // Assign all new registers to RS_Spill. This was the last chance.
1342 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1343 return 0;
1344}
1345
1346
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001347//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001348// Local Splitting
1349//===----------------------------------------------------------------------===//
1350
1351
1352/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1353/// in order to use PhysReg between two entries in SA->UseSlots.
1354///
1355/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1356///
1357void RAGreedy::calcGapWeights(unsigned PhysReg,
1358 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001359 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1360 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001361 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001362 const unsigned NumGaps = Uses.size()-1;
1363
1364 // Start and end points for the interference check.
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001365 SlotIndex StartIdx =
1366 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1367 SlotIndex StopIdx =
1368 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001369
1370 GapWeight.assign(NumGaps, 0.0f);
1371
1372 // Add interference from each overlapping register.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001373 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1374 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1375 .checkInterference())
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001376 continue;
1377
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001378 // We know that VirtReg is a continuous interval from FirstInstr to
1379 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001380 //
1381 // Interference that overlaps an instruction is counted in both gaps
1382 // surrounding the instruction. The exception is interference before
1383 // StartIdx and after StopIdx.
1384 //
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001385 LiveIntervalUnion::SegmentIter IntI =
1386 Matrix->getLiveUnions()[*Units] .find(StartIdx);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001387 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1388 // Skip the gaps before IntI.
1389 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1390 if (++Gap == NumGaps)
1391 break;
1392 if (Gap == NumGaps)
1393 break;
1394
1395 // Update the gaps covered by IntI.
1396 const float weight = IntI.value()->weight;
1397 for (; Gap != NumGaps; ++Gap) {
1398 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1399 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1400 break;
1401 }
1402 if (Gap == NumGaps)
1403 break;
1404 }
1405 }
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001406
1407 // Add fixed interference.
1408 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1409 const LiveInterval &LI = LIS->getRegUnit(*Units);
1410 LiveInterval::const_iterator I = LI.find(StartIdx);
1411 LiveInterval::const_iterator E = LI.end();
1412
1413 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1414 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1415 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1416 if (++Gap == NumGaps)
1417 break;
1418 if (Gap == NumGaps)
1419 break;
1420
1421 for (; Gap != NumGaps; ++Gap) {
1422 GapWeight[Gap] = HUGE_VALF;
1423 if (Uses[Gap+1].getBaseIndex() >= I->end)
1424 break;
1425 }
1426 if (Gap == NumGaps)
1427 break;
1428 }
1429 }
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001430}
1431
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001432/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1433/// basic block.
1434///
1435unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1436 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001437 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1438 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001439
1440 // Note that it is possible to have an interval that is live-in or live-out
1441 // while only covering a single block - A phi-def can use undef values from
1442 // predecessors, and the block could be a single-block loop.
1443 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001444 // that the interval is continuous from FirstInstr to LastInstr. We should
1445 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001446
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001447 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001448 if (Uses.size() <= 2)
1449 return 0;
1450 const unsigned NumGaps = Uses.size()-1;
1451
1452 DEBUG({
1453 dbgs() << "tryLocalSplit: ";
1454 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001455 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001456 dbgs() << '\n';
1457 });
1458
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001459 // If VirtReg is live across any register mask operands, compute a list of
1460 // gaps with register masks.
1461 SmallVector<unsigned, 8> RegMaskGaps;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001462 if (Matrix->checkRegMaskInterference(VirtReg)) {
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001463 // Get regmask slots for the whole block.
1464 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001465 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001466 // Constrain to VirtReg's live range.
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001467 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1468 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001469 unsigned re = RMS.size();
1470 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001471 // Look for Uses[i] <= RMS <= Uses[i+1].
1472 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1473 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001474 continue;
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001475 // Skip a regmask on the same instruction as the last use. It doesn't
1476 // overlap the live range.
1477 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1478 break;
1479 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001480 RegMaskGaps.push_back(i);
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001481 // Advance ri to the next gap. A regmask on one of the uses counts in
1482 // both gaps.
1483 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1484 ++ri;
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001485 }
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001486 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001487 }
1488
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001489 // Since we allow local split results to be split again, there is a risk of
1490 // creating infinite loops. It is tempting to require that the new live
1491 // ranges have less instructions than the original. That would guarantee
1492 // convergence, but it is too strict. A live range with 3 instructions can be
1493 // split 2+3 (including the COPY), and we want to allow that.
1494 //
1495 // Instead we use these rules:
1496 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001497 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001498 // noop split, of course).
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001499 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001500 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001501 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001502 // smaller ranges are marked RS_New.
1503 //
1504 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1505 // excessive splitting and infinite loops.
1506 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001507 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001508
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001509 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001510 unsigned BestBefore = NumGaps;
1511 unsigned BestAfter = 0;
1512 float BestDiff = 0;
1513
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001514 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001515 SmallVector<float, 8> GapWeight;
1516
1517 Order.rewind();
1518 while (unsigned PhysReg = Order.next()) {
1519 // Keep track of the largest spill weight that would need to be evicted in
1520 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1521 calcGapWeights(PhysReg, GapWeight);
1522
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001523 // Remove any gaps with regmask clobbers.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001524 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001525 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1526 GapWeight[RegMaskGaps[i]] = HUGE_VALF;
1527
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001528 // Try to find the best sequence of gaps to close.
1529 // The new spill weight must be larger than any gap interference.
1530
1531 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001532 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001533
1534 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1535 // It is the spill weight that needs to be evicted.
1536 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001537
1538 for (;;) {
1539 // Live before/after split?
1540 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1541 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1542
1543 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1544 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1545 << " i=" << MaxGap);
1546
1547 // Stop before the interval gets so big we wouldn't be making progress.
1548 if (!LiveBefore && !LiveAfter) {
1549 DEBUG(dbgs() << " all\n");
1550 break;
1551 }
1552 // Should the interval be extended or shrunk?
1553 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001554
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001555 // How many gaps would the new range have?
1556 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1557
1558 // Legally, without causing looping?
1559 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1560
1561 if (Legal && MaxGap < HUGE_VALF) {
1562 // Estimate the new spill weight. Each instruction reads or writes the
1563 // register. Conservatively assume there are no read-modify-write
1564 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001565 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001566 // Try to guess the size of the new interval.
1567 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1568 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1569 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001570 // Would this split be possible to allocate?
1571 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001572 DEBUG(dbgs() << " w=" << EstWeight);
1573 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001574 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001575 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001576 if (Diff > BestDiff) {
1577 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001578 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001579 BestBefore = SplitBefore;
1580 BestAfter = SplitAfter;
1581 }
1582 }
1583 }
1584
1585 // Try to shrink.
1586 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001587 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001588 DEBUG(dbgs() << " shrink\n");
1589 // Recompute the max when necessary.
1590 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1591 MaxGap = GapWeight[SplitBefore];
1592 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1593 MaxGap = std::max(MaxGap, GapWeight[i]);
1594 }
1595 continue;
1596 }
1597 MaxGap = 0;
1598 }
1599
1600 // Try to extend the interval.
1601 if (SplitAfter >= NumGaps) {
1602 DEBUG(dbgs() << " end\n");
1603 break;
1604 }
1605
1606 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001607 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001608 }
1609 }
1610
1611 // Didn't find any candidates?
1612 if (BestBefore == NumGaps)
1613 return 0;
1614
1615 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1616 << '-' << Uses[BestAfter] << ", " << BestDiff
1617 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1618
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001619 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001620 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001621
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001622 SE->openIntv();
1623 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1624 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1625 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001626 SmallVector<unsigned, 8> IntvMap;
1627 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001628 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001629
1630 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001631 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001632 // leave the new intervals as RS_New so they can compete.
1633 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1634 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1635 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1636 if (NewGaps >= NumGaps) {
1637 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1638 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001639 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1640 if (IntvMap[i] == 1) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001641 setStage(*LREdit.get(i), RS_Split2);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001642 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1643 }
1644 DEBUG(dbgs() << '\n');
1645 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001646 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001647
1648 return 0;
1649}
1650
1651//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001652// Live Range Splitting
1653//===----------------------------------------------------------------------===//
1654
1655/// trySplit - Try to split VirtReg or one of its interferences, making it
1656/// assignable.
1657/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1658unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1659 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesenccfa4462011-08-05 23:50:33 +00001660 // Ranges must be Split2 or less.
1661 if (getStage(VirtReg) >= RS_Spill)
1662 return 0;
1663
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001664 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001665 if (LIS->intervalIsInOneMBB(VirtReg)) {
1666 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001667 SA->analyze(&VirtReg);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001668 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1669 if (PhysReg || !NewVRegs.empty())
1670 return PhysReg;
1671 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001672 }
1673
1674 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001675
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001676 SA->analyze(&VirtReg);
1677
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001678 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1679 // coalescer. That may cause the range to become allocatable which means that
1680 // tryRegionSplit won't be making progress. This check should be replaced with
1681 // an assertion when the coalescer is fixed.
1682 if (SA->didRepairRange()) {
1683 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001684 Matrix->invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001685 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1686 return PhysReg;
1687 }
1688
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001689 // First try to split around a region spanning multiple blocks. RS_Split2
1690 // ranges already made dubious progress with region splitting, so they go
1691 // straight to single block splitting.
1692 if (getStage(VirtReg) < RS_Split2) {
1693 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1694 if (PhysReg || !NewVRegs.empty())
1695 return PhysReg;
1696 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001697
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001698 // Then isolate blocks.
1699 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001700}
1701
1702
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001703//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001704// Main Entry Point
1705//===----------------------------------------------------------------------===//
1706
1707unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001708 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001709 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001710 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001711 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1712 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001713
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001714 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001715 DEBUG(dbgs() << StageName[Stage]
1716 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001717
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001718 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001719 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001720 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001721 if (Stage != RS_Split)
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001722 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1723 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001724
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001725 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1726
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001727 // The first time we see a live range, don't try to split or spill.
1728 // Wait until the second time, when all smaller ranges have been allocated.
1729 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001730 if (Stage < RS_Split) {
1731 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001732 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001733 NewVRegs.push_back(&VirtReg);
1734 return 0;
1735 }
1736
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001737 // If we couldn't allocate a register from spilling, there is probably some
1738 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001739 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001740 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001741
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001742 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001743 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1744 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001745 return PhysReg;
1746
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001747 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001748 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001749 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001750 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001751 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001752
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001753 if (VerifyEnabled)
1754 MF->verify(this, "After spilling");
1755
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001756 // The live virtual register requesting allocation was spilled, so tell
1757 // the caller not to allocate anything during this round.
1758 return 0;
1759}
1760
1761bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1762 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
David Blaikie986d76d2012-08-22 17:18:53 +00001763 << "********** Function: " << mf.getName() << '\n');
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001764
1765 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001766 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001767 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001768
Jakob Stoklund Olesend4348a22012-06-20 22:52:29 +00001769 RegAllocBase::init(getAnalysis<VirtRegMap>(),
1770 getAnalysis<LiveIntervals>(),
1771 getAnalysis<LiveRegMatrix>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001772 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001773 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001774 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001775 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001776 Bundles = &getAnalysis<EdgeBundles>();
1777 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001778 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001779
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001780 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001781 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001782 ExtraRegInfo.clear();
1783 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1784 NextCascade = 1;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001785 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001786 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001787
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001788 allocatePhysRegs();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001789 releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001790 return true;
1791}