blob: d0b40dd113d249c03cb67ef0e265eeaf8d2ee9ef [file] [log] [blame]
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001//===-- RegAllocGreedy.cpp - greedy register allocator --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the RAGreedy function pass for register allocation in
11// optimized builds.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "regalloc"
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +000016#include "AllocationOrder.h"
Jakob Stoklund Olesen5907d862011-04-02 06:03:35 +000017#include "InterferenceCache.h"
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +000018#include "LiveDebugVariables.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000019#include "LiveRangeEdit.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000020#include "RegAllocBase.h"
21#include "Spiller.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000022#include "SpillPlacement.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000023#include "SplitKit.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000024#include "VirtRegMap.h"
Rafael Espindolafdf16ca2011-06-26 21:41:06 +000025#include "RegisterCoalescer.h"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000026#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000027#include "llvm/Analysis/AliasAnalysis.h"
28#include "llvm/Function.h"
29#include "llvm/PassAnalysisSupport.h"
30#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000031#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000032#include "llvm/CodeGen/LiveIntervalAnalysis.h"
33#include "llvm/CodeGen/LiveStackAnalysis.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000034#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000035#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000036#include "llvm/CodeGen/MachineLoopInfo.h"
37#include "llvm/CodeGen/MachineRegisterInfo.h"
38#include "llvm/CodeGen/Passes.h"
39#include "llvm/CodeGen/RegAllocRegistry.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000040#include "llvm/Target/TargetOptions.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000041#include "llvm/Support/Debug.h"
42#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000044#include "llvm/Support/Timer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000045
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000046#include <queue>
47
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000048using namespace llvm;
49
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000050STATISTIC(NumGlobalSplits, "Number of split global live ranges");
51STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000052STATISTIC(NumEvicted, "Number of interferences evicted");
53
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000054static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
55 createGreedyRegisterAllocator);
56
57namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000058class RAGreedy : public MachineFunctionPass,
59 public RegAllocBase,
60 private LiveRangeEdit::Delegate {
61
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000062 // context
63 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000064
65 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000066 SlotIndexes *Indexes;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000067 LiveStacks *LS;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000068 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000069 MachineLoopInfo *Loops;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000070 EdgeBundles *Bundles;
71 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +000072 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000073
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000074 // state
75 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000076 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +000077 unsigned NextCascade;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000078
79 // Live ranges pass through a number of stages as we try to allocate them.
80 // Some of the stages may also create new live ranges:
81 //
82 // - Region splitting.
83 // - Per-block splitting.
84 // - Local splitting.
85 // - Spilling.
86 //
87 // Ranges produced by one of the stages skip the previous stages when they are
88 // dequeued. This improves performance because we can skip interference checks
89 // that are unlikely to give any results. It also guarantees that the live
90 // range splitting algorithm terminates, something that is otherwise hard to
91 // ensure.
92 enum LiveRangeStage {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +000093 /// Newly created live range that has never been queued.
94 RS_New,
95
96 /// Only attempt assignment and eviction. Then requeue as RS_Split.
97 RS_Assign,
98
99 /// Attempt live range splitting if assignment is impossible.
100 RS_Split,
101
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000102 /// Attempt more aggressive live range splitting that is guaranteed to make
103 /// progress. This is used for split products that may not be making
104 /// progress.
105 RS_Split2,
106
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000107 /// Live range will be spilled. No more splitting will be attempted.
108 RS_Spill,
109
110 /// There is nothing more we can do to this live range. Abort compilation
111 /// if it can't be assigned.
112 RS_Done
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000113 };
114
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000115 static const char *const StageName[];
116
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000117 // RegInfo - Keep additional information about each live range.
118 struct RegInfo {
119 LiveRangeStage Stage;
120
121 // Cascade - Eviction loop prevention. See canEvictInterference().
122 unsigned Cascade;
123
124 RegInfo() : Stage(RS_New), Cascade(0) {}
125 };
126
127 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000128
129 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000130 return ExtraRegInfo[VirtReg.reg].Stage;
131 }
132
133 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
134 ExtraRegInfo.resize(MRI->getNumVirtRegs());
135 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000136 }
137
138 template<typename Iterator>
139 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000140 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000141 for (;Begin != End; ++Begin) {
142 unsigned Reg = (*Begin)->reg;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000143 if (ExtraRegInfo[Reg].Stage == RS_New)
144 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000145 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000146 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000147
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000148 /// Cost of evicting interference.
149 struct EvictionCost {
150 unsigned BrokenHints; ///< Total number of broken hints.
151 float MaxWeight; ///< Maximum spill weight evicted.
152
153 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
154
155 bool operator<(const EvictionCost &O) const {
156 if (BrokenHints != O.BrokenHints)
157 return BrokenHints < O.BrokenHints;
158 return MaxWeight < O.MaxWeight;
159 }
160 };
161
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000162 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000163 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000164 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000165
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000166 /// Cached per-block interference maps
167 InterferenceCache IntfCache;
168
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000169 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000170 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000171
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000172 /// Global live range splitting candidate info.
173 struct GlobalSplitCandidate {
174 unsigned PhysReg;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000175 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000176 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000177 SmallVector<unsigned, 8> ActiveBlocks;
178
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000179 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000180 PhysReg = Reg;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000181 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000182 LiveBundles.clear();
183 ActiveBlocks.clear();
184 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000185 };
186
187 /// Candidate info for for each PhysReg in AllocationOrder.
188 /// This vector never shrinks, but grows to the size of the largest register
189 /// class.
190 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
191
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000192public:
193 RAGreedy();
194
195 /// Return the pass name.
196 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000197 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000198 }
199
200 /// RAGreedy analysis usage.
201 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000202 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000203 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000204 virtual void enqueue(LiveInterval *LI);
205 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000206 virtual unsigned selectOrSplit(LiveInterval&,
207 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000208
209 /// Perform register allocation.
210 virtual bool runOnMachineFunction(MachineFunction &mf);
211
212 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000213
214private:
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000215 void LRE_WillEraseInstruction(MachineInstr*);
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000216 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000217 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000218 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000219
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000220 float calcSpillCost();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000221 bool addSplitConstraints(InterferenceCache::Cursor, float&);
222 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000223 void growRegion(GlobalSplitCandidate &Cand);
224 float calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000225 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000226 void splitAroundRegion(LiveInterval&, GlobalSplitCandidate&,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000227 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000228 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000229 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
230 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
231 void evictInterference(LiveInterval&, unsigned,
232 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000233
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000234 unsigned tryAssign(LiveInterval&, AllocationOrder&,
235 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000236 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000237 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000238 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
239 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000240 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
241 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000242 unsigned trySplit(LiveInterval&, AllocationOrder&,
243 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000244};
245} // end anonymous namespace
246
247char RAGreedy::ID = 0;
248
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000249#ifndef NDEBUG
250const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000251 "RS_New",
252 "RS_Assign",
253 "RS_Split",
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000254 "RS_Split2",
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000255 "RS_Spill",
256 "RS_Done"
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000257};
258#endif
259
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000260// Hysteresis to use when comparing floats.
261// This helps stabilize decisions based on float comparisons.
262const float Hysteresis = 0.98f;
263
264
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000265FunctionPass* llvm::createGreedyRegisterAllocator() {
266 return new RAGreedy();
267}
268
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000269RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000270 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000271 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000272 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
273 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
274 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000275 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000276 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
277 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
278 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
279 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
280 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000281 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
282 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000283}
284
285void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
286 AU.setPreservesCFG();
287 AU.addRequired<AliasAnalysis>();
288 AU.addPreserved<AliasAnalysis>();
289 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000290 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000291 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000292 AU.addRequired<LiveDebugVariables>();
293 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000294 if (StrongPHIElim)
295 AU.addRequiredID(StrongPHIEliminationID);
296 AU.addRequiredTransitive<RegisterCoalescer>();
297 AU.addRequired<CalculateSpillWeights>();
298 AU.addRequired<LiveStacks>();
299 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000300 AU.addRequired<MachineDominatorTree>();
301 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000302 AU.addRequired<MachineLoopInfo>();
303 AU.addPreserved<MachineLoopInfo>();
304 AU.addRequired<VirtRegMap>();
305 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000306 AU.addRequired<EdgeBundles>();
307 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000308 MachineFunctionPass::getAnalysisUsage(AU);
309}
310
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000311
312//===----------------------------------------------------------------------===//
313// LiveRangeEdit delegate methods
314//===----------------------------------------------------------------------===//
315
316void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
317 // LRE itself will remove from SlotIndexes and parent basic block.
318 VRM->RemoveMachineInstrFromMaps(MI);
319}
320
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000321bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
322 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
323 unassign(LIS->getInterval(VirtReg), PhysReg);
324 return true;
325 }
326 // Unassigned virtreg is probably in the priority queue.
327 // RegAllocBase will erase it after dequeueing.
328 return false;
329}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000330
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000331void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
332 unsigned PhysReg = VRM->getPhys(VirtReg);
333 if (!PhysReg)
334 return;
335
336 // Register is assigned, put it back on the queue for reassignment.
337 LiveInterval &LI = LIS->getInterval(VirtReg);
338 unassign(LI, PhysReg);
339 enqueue(&LI);
340}
341
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000342void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
343 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000344 // be split into connected components. The new components are much smaller
345 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000346 // same stage as the parent.
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000347 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000348 ExtraRegInfo.grow(New);
349 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000350}
351
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000352void RAGreedy::releaseMemory() {
353 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000354 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000355 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000356 RegAllocBase::releaseMemory();
357}
358
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000359void RAGreedy::enqueue(LiveInterval *LI) {
360 // Prioritize live ranges by size, assigning larger ranges first.
361 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000362 const unsigned Size = LI->getSize();
363 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000364 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
365 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000366 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000367
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000368 ExtraRegInfo.grow(Reg);
369 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000370 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000371
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000372 if (ExtraRegInfo[Reg].Stage == RS_Split)
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000373 // Unsplit ranges that couldn't be allocated immediately are deferred until
374 // everything else has been allocated. Long ranges are allocated last so
375 // they are split against realistic interference.
376 Prio = (1u << 31) - Size;
377 else {
378 // Everything else is allocated in long->short order. Long ranges that don't
379 // fit should be spilled ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000380 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000381
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000382 // Boost ranges that have a physical register hint.
383 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
384 Prio |= (1u << 30);
385 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000386
387 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000388}
389
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000390LiveInterval *RAGreedy::dequeue() {
391 if (Queue.empty())
392 return 0;
393 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
394 Queue.pop();
395 return LI;
396}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000397
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000398
399//===----------------------------------------------------------------------===//
400// Direct Assignment
401//===----------------------------------------------------------------------===//
402
403/// tryAssign - Try to assign VirtReg to an available register.
404unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
405 AllocationOrder &Order,
406 SmallVectorImpl<LiveInterval*> &NewVRegs) {
407 Order.rewind();
408 unsigned PhysReg;
409 while ((PhysReg = Order.next()))
410 if (!checkPhysRegInterference(VirtReg, PhysReg))
411 break;
412 if (!PhysReg || Order.isHint(PhysReg))
413 return PhysReg;
414
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000415 // PhysReg is available, but there may be a better choice.
416
417 // If we missed a simple hint, try to cheaply evict interference from the
418 // preferred register.
419 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
420 if (Order.isHint(Hint)) {
421 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
422 EvictionCost MaxCost(1);
423 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
424 evictInterference(VirtReg, Hint, NewVRegs);
425 return Hint;
426 }
427 }
428
429 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000430 unsigned Cost = TRI->getCostPerUse(PhysReg);
431
432 // Most registers have 0 additional cost.
433 if (!Cost)
434 return PhysReg;
435
436 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
437 << '\n');
438 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
439 return CheapReg ? CheapReg : PhysReg;
440}
441
442
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000443//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000444// Interference eviction
445//===----------------------------------------------------------------------===//
446
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000447/// shouldEvict - determine if A should evict the assigned live range B. The
448/// eviction policy defined by this function together with the allocation order
449/// defined by enqueue() decides which registers ultimately end up being split
450/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000451///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000452/// Cascade numbers are used to prevent infinite loops if this function is a
453/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000454///
455/// @param A The live range to be assigned.
456/// @param IsHint True when A is about to be assigned to its preferred
457/// register.
458/// @param B The live range to be evicted.
459/// @param BreaksHint True when B is already assigned to its preferred register.
460bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
461 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000462 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000463
464 // Be fairly aggressive about following hints as long as the evictee can be
465 // split.
466 if (CanSplit && IsHint && !BreaksHint)
467 return true;
468
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000469 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000470}
471
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000472/// canEvictInterference - Return true if all interferences between VirtReg and
473/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
474///
475/// @param VirtReg Live range that is about to be assigned.
476/// @param PhysReg Desired register for assignment.
477/// @prarm IsHint True when PhysReg is VirtReg's preferred register.
478/// @param MaxCost Only look for cheaper candidates and update with new cost
479/// when returning true.
480/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000481bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000482 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000483 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
484 // involved in an eviction before. If a cascade number was assigned, deny
485 // evicting anything with the same or a newer cascade number. This prevents
486 // infinite eviction loops.
487 //
488 // This works out so a register without a cascade number is allowed to evict
489 // anything, and it can be evicted by anything.
490 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
491 if (!Cascade)
492 Cascade = NextCascade;
493
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000494 EvictionCost Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000495 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
496 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000497 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000498 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000499 return false;
500
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000501 // Check if any interfering live range is heavier than MaxWeight.
502 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
503 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000504 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
505 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000506 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000507 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000508 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000509 // Once a live range becomes small enough, it is urgent that we find a
510 // register for it. This is indicated by an infinite spill weight. These
511 // urgent live ranges get to evict almost anything.
512 bool Urgent = !VirtReg.isSpillable() && Intf->isSpillable();
513 // Only evict older cascades or live ranges without a cascade.
514 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
515 if (Cascade <= IntfCascade) {
516 if (!Urgent)
517 return false;
518 // We permit breaking cascades for urgent evictions. It should be the
519 // last resort, though, so make it really expensive.
520 Cost.BrokenHints += 10;
521 }
522 // Would this break a satisfied hint?
523 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
524 // Update eviction cost.
525 Cost.BrokenHints += BreaksHint;
526 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
527 // Abort if this would be too expensive.
528 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000529 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000530 // Finally, apply the eviction policy for non-urgent evictions.
531 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000532 return false;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000533 }
534 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000535 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000536 return true;
537}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000538
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000539/// evictInterference - Evict any interferring registers that prevent VirtReg
540/// from being assigned to Physreg. This assumes that canEvictInterference
541/// returned true.
542void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
543 SmallVectorImpl<LiveInterval*> &NewVRegs) {
544 // Make sure that VirtReg has a cascade number, and assign that cascade
545 // number to every evicted register. These live ranges than then only be
546 // evicted by a newer cascade, preventing infinite loops.
547 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
548 if (!Cascade)
549 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
550
551 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
552 << " interference: Cascade " << Cascade << '\n');
553 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
554 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
555 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
556 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
557 LiveInterval *Intf = Q.interferingVRegs()[i];
558 unassign(*Intf, VRM->getPhys(Intf->reg));
559 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
560 VirtReg.isSpillable() < Intf->isSpillable()) &&
561 "Cannot decrease cascade number, illegal eviction");
562 ExtraRegInfo[Intf->reg].Cascade = Cascade;
563 ++NumEvicted;
564 NewVRegs.push_back(Intf);
565 }
566 }
567}
568
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000569/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000570/// @param VirtReg Currently unassigned virtual register.
571/// @param Order Physregs to try.
572/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000573unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
574 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000575 SmallVectorImpl<LiveInterval*> &NewVRegs,
576 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000577 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
578
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000579 // Keep track of the cheapest interference seen so far.
580 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000581 unsigned BestPhys = 0;
582
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000583 // When we are just looking for a reduced cost per use, don't break any
584 // hints, and only evict smaller spill weights.
585 if (CostPerUseLimit < ~0u) {
586 BestCost.BrokenHints = 0;
587 BestCost.MaxWeight = VirtReg.weight;
588 }
589
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000590 Order.rewind();
591 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000592 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
593 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000594 // The first use of a callee-saved register in a function has cost 1.
595 // Don't start using a CSR when the CostPerUseLimit is low.
596 if (CostPerUseLimit == 1)
597 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
598 if (!MRI->isPhysRegUsed(CSR)) {
599 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
600 << PrintReg(CSR, TRI) << '\n');
601 continue;
602 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000603
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000604 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000605 continue;
606
607 // Best so far.
608 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000609
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000610 // Stop if the hint can be used.
611 if (Order.isHint(PhysReg))
612 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000613 }
614
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000615 if (!BestPhys)
616 return 0;
617
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000618 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000619 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000620}
621
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000622
623//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000624// Region Splitting
625//===----------------------------------------------------------------------===//
626
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000627/// addSplitConstraints - Fill out the SplitConstraints vector based on the
628/// interference pattern in Physreg and its aliases. Add the constraints to
629/// SpillPlacement and return the static cost of this split in Cost, assuming
630/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000631/// Return false if there are no bundles with positive bias.
632bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
633 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000634 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000635
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000636 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000637 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000638 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000639 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
640 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000641 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000642
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000643 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000644 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000645 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
646 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000647
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000648 if (!Intf.hasInterference())
649 continue;
650
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000651 // Number of spill code instructions to insert.
652 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000653
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000654 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000655 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000656 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000657 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000658 else if (Intf.first() < BI.FirstUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000659 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesena2e79ef2011-05-30 01:33:26 +0000660 else if (Intf.first() < BI.LastUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000661 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000662 }
663
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000664 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000665 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000666 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000667 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000668 else if (Intf.last() > BI.LastUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000669 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesena2e79ef2011-05-30 01:33:26 +0000670 else if (Intf.last() > BI.FirstUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000671 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000672 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000673
674 // Accumulate the total frequency of inserted spill code.
675 if (Ins)
676 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000677 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000678 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000679
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000680 // Add constraints for use-blocks. Note that these are the only constraints
681 // that may add a positive bias, it is downhill from here.
682 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000683 return SpillPlacer->scanActiveBundles();
684}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000685
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000686
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000687/// addThroughConstraints - Add constraints and links to SpillPlacer from the
688/// live-through blocks in Blocks.
689void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
690 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000691 const unsigned GroupSize = 8;
692 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000693 unsigned TBS[GroupSize];
694 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000695
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000696 for (unsigned i = 0; i != Blocks.size(); ++i) {
697 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000698 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000699
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000700 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000701 assert(T < GroupSize && "Array overflow");
702 TBS[T] = Number;
703 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000704 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000705 T = 0;
706 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000707 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000708 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000709
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000710 assert(B < GroupSize && "Array overflow");
711 BCS[B].Number = Number;
712
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000713 // Interference for the live-in value.
714 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
715 BCS[B].Entry = SpillPlacement::MustSpill;
716 else
717 BCS[B].Entry = SpillPlacement::PrefSpill;
718
719 // Interference for the live-out value.
720 if (Intf.last() >= SA->getLastSplitPoint(Number))
721 BCS[B].Exit = SpillPlacement::MustSpill;
722 else
723 BCS[B].Exit = SpillPlacement::PrefSpill;
724
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000725 if (++B == GroupSize) {
726 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
727 SpillPlacer->addConstraints(Array);
728 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000729 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000730 }
731
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000732 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
733 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000734 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000735}
736
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000737void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000738 // Keep track of through blocks that have not been added to SpillPlacer.
739 BitVector Todo = SA->getThroughBlocks();
740 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
741 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000742#ifndef NDEBUG
743 unsigned Visited = 0;
744#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000745
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000746 for (;;) {
747 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000748 // Find new through blocks in the periphery of PrefRegBundles.
749 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
750 unsigned Bundle = NewBundles[i];
751 // Look at all blocks connected to Bundle in the full graph.
752 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
753 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
754 I != E; ++I) {
755 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000756 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000757 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000758 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000759 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000760 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000761#ifndef NDEBUG
762 ++Visited;
763#endif
764 }
765 }
766 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000767 if (ActiveBlocks.size() == AddedTo)
768 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000769
770 // Compute through constraints from the interference, or assume that all
771 // through blocks prefer spilling when forming compact regions.
772 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
773 if (Cand.PhysReg)
774 addThroughConstraints(Cand.Intf, NewBlocks);
775 else
776 SpillPlacer->addPrefSpill(NewBlocks);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000777 AddedTo = ActiveBlocks.size();
778
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000779 // Perhaps iterating can enable more bundles?
780 SpillPlacer->iterate();
781 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000782 DEBUG(dbgs() << ", v=" << Visited);
783}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000784
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000785/// calcCompactRegion - Compute the set of edge bundles that should be live
786/// when splitting the current live range into compact regions. Compact
787/// regions can be computed without looking at interference. They are the
788/// regions formed by removing all the live-through blocks from the live range.
789///
790/// Returns false if the current live range is already compact, or if the
791/// compact regions would form single block regions anyway.
792bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
793 // Without any through blocks, the live range is already compact.
794 if (!SA->getNumThroughBlocks())
795 return false;
796
797 // Compact regions don't correspond to any physreg.
798 Cand.reset(IntfCache, 0);
799
800 DEBUG(dbgs() << "Compact region bundles");
801
802 // Use the spill placer to determine the live bundles. GrowRegion pretends
803 // that all the through blocks have interference when PhysReg is unset.
804 SpillPlacer->prepare(Cand.LiveBundles);
805
806 // The static split cost will be zero since Cand.Intf reports no interference.
807 float Cost;
808 if (!addSplitConstraints(Cand.Intf, Cost)) {
809 DEBUG(dbgs() << ", none.\n");
810 return false;
811 }
812
813 growRegion(Cand);
814 SpillPlacer->finish();
815
816 if (!Cand.LiveBundles.any()) {
817 DEBUG(dbgs() << ", none.\n");
818 return false;
819 }
820
821 DEBUG({
822 for (int i = Cand.LiveBundles.find_first(); i>=0;
823 i = Cand.LiveBundles.find_next(i))
824 dbgs() << " EB#" << i;
825 dbgs() << ".\n";
826 });
827 return true;
828}
829
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000830/// calcSpillCost - Compute how expensive it would be to split the live range in
831/// SA around all use blocks instead of forming bundle regions.
832float RAGreedy::calcSpillCost() {
833 float Cost = 0;
834 const LiveInterval &LI = SA->getParent();
835 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
836 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
837 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
838 unsigned Number = BI.MBB->getNumber();
839 // We normally only need one spill instruction - a load or a store.
840 Cost += SpillPlacer->getBlockFrequency(Number);
841
842 // Unless the value is redefined in the block.
843 if (BI.LiveIn && BI.LiveOut) {
844 SlotIndex Start, Stop;
845 tie(Start, Stop) = Indexes->getMBBRange(Number);
846 LiveInterval::const_iterator I = LI.find(Start);
847 assert(I != LI.end() && "Expected live-in value");
848 // Is there a different live-out value? If so, we need an extra spill
849 // instruction.
850 if (I->end < Stop)
851 Cost += SpillPlacer->getBlockFrequency(Number);
852 }
853 }
854 return Cost;
855}
856
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000857/// calcGlobalSplitCost - Return the global split cost of following the split
858/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000859/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000860///
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000861float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000862 float GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000863 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000864 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
865 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
866 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000867 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000868 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
869 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
870 unsigned Ins = 0;
871
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000872 if (BI.LiveIn)
873 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
874 if (BI.LiveOut)
875 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000876 if (Ins)
877 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000878 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000879
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000880 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
881 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000882 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
883 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000884 if (!RegIn && !RegOut)
885 continue;
886 if (RegIn && RegOut) {
887 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000888 Cand.Intf.moveToBlock(Number);
889 if (Cand.Intf.hasInterference())
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000890 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
891 continue;
892 }
893 // live-in / stack-out or stack-in live-out.
894 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000895 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000896 return GlobalCost;
897}
898
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000899/// splitAroundRegion - Split VirtReg around the region determined by
900/// LiveBundles. Make an effort to avoid interference from PhysReg.
901///
902/// The 'register' interval is going to contain as many uses as possible while
903/// avoiding interference. The 'stack' interval is the complement constructed by
904/// SplitEditor. It will contain the rest.
905///
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000906void RAGreedy::splitAroundRegion(LiveInterval &VirtReg,
907 GlobalSplitCandidate &Cand,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000908 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000909 const BitVector &LiveBundles = Cand.LiveBundles;
910
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000911 DEBUG({
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000912 dbgs() << "Splitting around region for " << PrintReg(Cand.PhysReg, TRI)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000913 << " with bundles";
914 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
915 dbgs() << " EB#" << i;
916 dbgs() << ".\n";
917 });
918
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000919 InterferenceCache::Cursor &Intf = Cand.Intf;
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000920 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000921 SE->reset(LREdit);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000922
923 // Create the main cross-block interval.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000924 const unsigned MainIntv = SE->openIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000925
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000926 // First handle all the blocks with uses.
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 Olesen87360f72011-06-30 01:30:39 +0000930 bool RegIn = BI.LiveIn &&
931 LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
932 bool RegOut = BI.LiveOut &&
933 LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000934
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000935 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000936 if (!RegIn && !RegOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000937 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000938 if (!BI.isOneInstr()) {
939 SE->splitSingleBlock(BI);
940 SE->selectIntv(MainIntv);
941 }
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000942 continue;
943 }
944
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000945 Intf.moveToBlock(BI.MBB->getNumber());
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000946
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +0000947 if (RegIn && RegOut)
948 SE->splitLiveThroughBlock(BI.MBB->getNumber(),
949 MainIntv, Intf.first(),
950 MainIntv, Intf.last());
951 else if (RegIn)
952 SE->splitRegInBlock(BI, MainIntv, Intf.first());
953 else
954 SE->splitRegOutBlock(BI, MainIntv, Intf.last());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000955 }
956
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000957 // Handle live-through blocks.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000958 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
959 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000960 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
961 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +0000962 if (!RegIn && !RegOut)
963 continue;
964 Intf.moveToBlock(Number);
965 SE->splitLiveThroughBlock(Number, RegIn ? MainIntv : 0, Intf.first(),
966 RegOut ? MainIntv : 0, Intf.last());
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000967 }
968
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000969 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000970
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000971 SmallVector<unsigned, 8> IntvMap;
972 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000973 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
974
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000975 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +0000976 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000977
978 // Sort out the new intervals created by splitting. We get four kinds:
979 // - Remainder intervals should not be split again.
980 // - Candidate intervals can be assigned to Cand.PhysReg.
981 // - Block-local splits are candidates for local splitting.
982 // - DCE leftovers should go back on the queue.
983 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000984 LiveInterval &Reg = *LREdit.get(i);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000985
986 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000987 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000988 continue;
989
990 // Remainder interval. Don't try splitting again, spill if it doesn't
991 // allocate.
992 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000993 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000994 continue;
995 }
996
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +0000997 // Main interval. Allow repeated splitting as long as the number of live
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000998 // blocks is strictly decreasing. Otherwise force per-block splitting.
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +0000999 if (IntvMap[i] == MainIntv) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001000 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001001 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1002 << " blocks as original.\n");
1003 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001004 setStage(Reg, RS_Split2);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001005 }
1006 continue;
1007 }
1008
1009 // Other intervals are treated as new. This includes local intervals created
1010 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001011 }
1012
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001013 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001014 MF->verify(this, "After splitting live range around region");
1015}
1016
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001017unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1018 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001019 float BestCost = Hysteresis * calcSpillCost();
1020 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001021 const unsigned NoCand = ~0u;
1022 unsigned BestCand = NoCand;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001023 unsigned NumCands = 0;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001024
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001025 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001026 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001027 // Discard bad candidates before we run out of interference cache cursors.
1028 // This will only affect register classes with a lot of registers (>32).
1029 if (NumCands == IntfCache.getMaxCursors()) {
1030 unsigned WorstCount = ~0u;
1031 unsigned Worst = 0;
1032 for (unsigned i = 0; i != NumCands; ++i) {
1033 if (i == BestCand)
1034 continue;
1035 unsigned Count = GlobalCand[i].LiveBundles.count();
1036 if (Count < WorstCount)
1037 Worst = i, WorstCount = Count;
1038 }
1039 --NumCands;
1040 GlobalCand[Worst] = GlobalCand[NumCands];
1041 }
1042
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001043 if (GlobalCand.size() <= NumCands)
1044 GlobalCand.resize(NumCands+1);
1045 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1046 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001047
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001048 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001049 float Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001050 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001051 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001052 continue;
1053 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001054 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001055 if (Cost >= BestCost) {
1056 DEBUG({
1057 if (BestCand == NoCand)
1058 dbgs() << " worse than no bundles\n";
1059 else
1060 dbgs() << " worse than "
1061 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1062 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001063 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001064 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001065 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001066
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001067 SpillPlacer->finish();
1068
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001069 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001070 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001071 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001072 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001073 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001074
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001075 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001076 DEBUG({
1077 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001078 for (int i = Cand.LiveBundles.find_first(); i>=0;
1079 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001080 dbgs() << " EB#" << i;
1081 dbgs() << ".\n";
1082 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001083 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001084 BestCand = NumCands;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001085 BestCost = Hysteresis * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001086 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001087 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001088 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001089
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001090 if (BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001091 return 0;
1092
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001093 splitAroundRegion(VirtReg, GlobalCand[BestCand], NewVRegs);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001094 return 0;
1095}
1096
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001097
1098//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001099// Local Splitting
1100//===----------------------------------------------------------------------===//
1101
1102
1103/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1104/// in order to use PhysReg between two entries in SA->UseSlots.
1105///
1106/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1107///
1108void RAGreedy::calcGapWeights(unsigned PhysReg,
1109 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001110 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1111 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001112 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1113 const unsigned NumGaps = Uses.size()-1;
1114
1115 // Start and end points for the interference check.
1116 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
1117 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
1118
1119 GapWeight.assign(NumGaps, 0.0f);
1120
1121 // Add interference from each overlapping register.
1122 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
1123 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
1124 .checkInterference())
1125 continue;
1126
1127 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
1128 // so we don't need InterferenceQuery.
1129 //
1130 // Interference that overlaps an instruction is counted in both gaps
1131 // surrounding the instruction. The exception is interference before
1132 // StartIdx and after StopIdx.
1133 //
1134 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
1135 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1136 // Skip the gaps before IntI.
1137 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1138 if (++Gap == NumGaps)
1139 break;
1140 if (Gap == NumGaps)
1141 break;
1142
1143 // Update the gaps covered by IntI.
1144 const float weight = IntI.value()->weight;
1145 for (; Gap != NumGaps; ++Gap) {
1146 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1147 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1148 break;
1149 }
1150 if (Gap == NumGaps)
1151 break;
1152 }
1153 }
1154}
1155
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001156/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1157/// basic block.
1158///
1159unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1160 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001161 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1162 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001163
1164 // Note that it is possible to have an interval that is live-in or live-out
1165 // while only covering a single block - A phi-def can use undef values from
1166 // predecessors, and the block could be a single-block loop.
1167 // We don't bother doing anything clever about such a case, we simply assume
1168 // that the interval is continuous from FirstUse to LastUse. We should make
1169 // sure that we don't do anything illegal to such an interval, though.
1170
1171 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1172 if (Uses.size() <= 2)
1173 return 0;
1174 const unsigned NumGaps = Uses.size()-1;
1175
1176 DEBUG({
1177 dbgs() << "tryLocalSplit: ";
1178 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1179 dbgs() << ' ' << SA->UseSlots[i];
1180 dbgs() << '\n';
1181 });
1182
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001183 // Since we allow local split results to be split again, there is a risk of
1184 // creating infinite loops. It is tempting to require that the new live
1185 // ranges have less instructions than the original. That would guarantee
1186 // convergence, but it is too strict. A live range with 3 instructions can be
1187 // split 2+3 (including the COPY), and we want to allow that.
1188 //
1189 // Instead we use these rules:
1190 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001191 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001192 // noop split, of course).
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001193 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001194 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001195 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001196 // smaller ranges are marked RS_New.
1197 //
1198 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1199 // excessive splitting and infinite loops.
1200 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001201 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001202
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001203 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001204 unsigned BestBefore = NumGaps;
1205 unsigned BestAfter = 0;
1206 float BestDiff = 0;
1207
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001208 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001209 SmallVector<float, 8> GapWeight;
1210
1211 Order.rewind();
1212 while (unsigned PhysReg = Order.next()) {
1213 // Keep track of the largest spill weight that would need to be evicted in
1214 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1215 calcGapWeights(PhysReg, GapWeight);
1216
1217 // Try to find the best sequence of gaps to close.
1218 // The new spill weight must be larger than any gap interference.
1219
1220 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001221 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001222
1223 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1224 // It is the spill weight that needs to be evicted.
1225 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001226
1227 for (;;) {
1228 // Live before/after split?
1229 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1230 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1231
1232 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1233 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1234 << " i=" << MaxGap);
1235
1236 // Stop before the interval gets so big we wouldn't be making progress.
1237 if (!LiveBefore && !LiveAfter) {
1238 DEBUG(dbgs() << " all\n");
1239 break;
1240 }
1241 // Should the interval be extended or shrunk?
1242 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001243
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001244 // How many gaps would the new range have?
1245 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1246
1247 // Legally, without causing looping?
1248 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1249
1250 if (Legal && MaxGap < HUGE_VALF) {
1251 // Estimate the new spill weight. Each instruction reads or writes the
1252 // register. Conservatively assume there are no read-modify-write
1253 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001254 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001255 // Try to guess the size of the new interval.
1256 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1257 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1258 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001259 // Would this split be possible to allocate?
1260 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001261 DEBUG(dbgs() << " w=" << EstWeight);
1262 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001263 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001264 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001265 if (Diff > BestDiff) {
1266 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001267 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001268 BestBefore = SplitBefore;
1269 BestAfter = SplitAfter;
1270 }
1271 }
1272 }
1273
1274 // Try to shrink.
1275 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001276 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001277 DEBUG(dbgs() << " shrink\n");
1278 // Recompute the max when necessary.
1279 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1280 MaxGap = GapWeight[SplitBefore];
1281 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1282 MaxGap = std::max(MaxGap, GapWeight[i]);
1283 }
1284 continue;
1285 }
1286 MaxGap = 0;
1287 }
1288
1289 // Try to extend the interval.
1290 if (SplitAfter >= NumGaps) {
1291 DEBUG(dbgs() << " end\n");
1292 break;
1293 }
1294
1295 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001296 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001297 }
1298 }
1299
1300 // Didn't find any candidates?
1301 if (BestBefore == NumGaps)
1302 return 0;
1303
1304 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1305 << '-' << Uses[BestAfter] << ", " << BestDiff
1306 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1307
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001308 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001309 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001310
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001311 SE->openIntv();
1312 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1313 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1314 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001315 SmallVector<unsigned, 8> IntvMap;
1316 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001317 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001318
1319 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001320 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001321 // leave the new intervals as RS_New so they can compete.
1322 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1323 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1324 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1325 if (NewGaps >= NumGaps) {
1326 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1327 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001328 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1329 if (IntvMap[i] == 1) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001330 setStage(*LREdit.get(i), RS_Split2);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001331 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1332 }
1333 DEBUG(dbgs() << '\n');
1334 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001335 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001336
1337 return 0;
1338}
1339
1340//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001341// Live Range Splitting
1342//===----------------------------------------------------------------------===//
1343
1344/// trySplit - Try to split VirtReg or one of its interferences, making it
1345/// assignable.
1346/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1347unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1348 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001349 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001350 if (LIS->intervalIsInOneMBB(VirtReg)) {
1351 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001352 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001353 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001354 }
1355
1356 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001357
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001358 // Ranges must be Split2 or less.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001359 if (getStage(VirtReg) >= RS_Spill)
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001360 return 0;
1361
1362 SA->analyze(&VirtReg);
1363
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001364 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1365 // coalescer. That may cause the range to become allocatable which means that
1366 // tryRegionSplit won't be making progress. This check should be replaced with
1367 // an assertion when the coalescer is fixed.
1368 if (SA->didRepairRange()) {
1369 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesenbdda37d2011-05-10 17:37:41 +00001370 invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001371 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1372 return PhysReg;
1373 }
1374
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001375 // First try to split around a region spanning multiple blocks. RS_Split2
1376 // ranges already made dubious progress with region splitting, so they go
1377 // straight to single block splitting.
1378 if (getStage(VirtReg) < RS_Split2) {
1379 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1380 if (PhysReg || !NewVRegs.empty())
1381 return PhysReg;
1382 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001383
1384 // Then isolate blocks with multiple uses.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001385 SplitAnalysis::BlockPtrSet Blocks;
1386 if (SA->getMultiUseBlocks(Blocks)) {
1387 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1388 SE->reset(LREdit);
1389 SE->splitSingleBlocks(Blocks);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001390 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Spill);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001391 if (VerifyEnabled)
1392 MF->verify(this, "After splitting live range around basic blocks");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001393 }
1394
1395 // Don't assign any physregs.
1396 return 0;
1397}
1398
1399
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001400//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001401// Main Entry Point
1402//===----------------------------------------------------------------------===//
1403
1404unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001405 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001406 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001407 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001408 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1409 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001410
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001411 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001412 DEBUG(dbgs() << StageName[Stage]
1413 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001414
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001415 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001416 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001417 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001418 if (Stage != RS_Split)
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001419 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1420 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001421
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001422 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1423
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001424 // The first time we see a live range, don't try to split or spill.
1425 // Wait until the second time, when all smaller ranges have been allocated.
1426 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001427 if (Stage < RS_Split) {
1428 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001429 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001430 NewVRegs.push_back(&VirtReg);
1431 return 0;
1432 }
1433
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001434 // If we couldn't allocate a register from spilling, there is probably some
1435 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001436 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001437 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001438
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001439 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001440 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1441 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001442 return PhysReg;
1443
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001444 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001445 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001446 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1447 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001448 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001449
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001450 if (VerifyEnabled)
1451 MF->verify(this, "After spilling");
1452
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001453 // The live virtual register requesting allocation was spilled, so tell
1454 // the caller not to allocate anything during this round.
1455 return 0;
1456}
1457
1458bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1459 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1460 << "********** Function: "
1461 << ((Value*)mf.getFunction())->getName() << '\n');
1462
1463 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001464 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001465 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001466
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001467 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001468 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001469 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001470 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001471 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001472 Bundles = &getAnalysis<EdgeBundles>();
1473 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001474 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001475
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001476 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001477 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001478 ExtraRegInfo.clear();
1479 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1480 NextCascade = 1;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +00001481 IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001482
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001483 allocatePhysRegs();
1484 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001485 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001486
1487 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001488 {
1489 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001490 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001491 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001492
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001493 // Write out new DBG_VALUE instructions.
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001494 DebugVars->emitDebugValues(VRM);
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001495
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001496 // The pass output is in VirtRegMap. Release all the transient data.
1497 releaseMemory();
1498
1499 return true;
1500}