blob: 147e8035340fc60d19909f15eaea03d3f8082f82 [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
344 // be split into connected components. Ensure that the new register gets the
345 // same stage as the parent.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000346 ExtraRegInfo.grow(New);
347 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000348}
349
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000350void RAGreedy::releaseMemory() {
351 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000352 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000353 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000354 RegAllocBase::releaseMemory();
355}
356
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000357void RAGreedy::enqueue(LiveInterval *LI) {
358 // Prioritize live ranges by size, assigning larger ranges first.
359 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000360 const unsigned Size = LI->getSize();
361 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000362 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
363 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000364 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000365
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000366 ExtraRegInfo.grow(Reg);
367 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000368 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000369
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000370 if (ExtraRegInfo[Reg].Stage == RS_Split)
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000371 // Unsplit ranges that couldn't be allocated immediately are deferred until
372 // everything else has been allocated. Long ranges are allocated last so
373 // they are split against realistic interference.
374 Prio = (1u << 31) - Size;
375 else {
376 // Everything else is allocated in long->short order. Long ranges that don't
377 // fit should be spilled ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000378 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000379
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000380 // Boost ranges that have a physical register hint.
381 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
382 Prio |= (1u << 30);
383 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000384
385 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000386}
387
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000388LiveInterval *RAGreedy::dequeue() {
389 if (Queue.empty())
390 return 0;
391 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
392 Queue.pop();
393 return LI;
394}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000395
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000396
397//===----------------------------------------------------------------------===//
398// Direct Assignment
399//===----------------------------------------------------------------------===//
400
401/// tryAssign - Try to assign VirtReg to an available register.
402unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
403 AllocationOrder &Order,
404 SmallVectorImpl<LiveInterval*> &NewVRegs) {
405 Order.rewind();
406 unsigned PhysReg;
407 while ((PhysReg = Order.next()))
408 if (!checkPhysRegInterference(VirtReg, PhysReg))
409 break;
410 if (!PhysReg || Order.isHint(PhysReg))
411 return PhysReg;
412
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000413 // PhysReg is available, but there may be a better choice.
414
415 // If we missed a simple hint, try to cheaply evict interference from the
416 // preferred register.
417 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
418 if (Order.isHint(Hint)) {
419 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
420 EvictionCost MaxCost(1);
421 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
422 evictInterference(VirtReg, Hint, NewVRegs);
423 return Hint;
424 }
425 }
426
427 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000428 unsigned Cost = TRI->getCostPerUse(PhysReg);
429
430 // Most registers have 0 additional cost.
431 if (!Cost)
432 return PhysReg;
433
434 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
435 << '\n');
436 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
437 return CheapReg ? CheapReg : PhysReg;
438}
439
440
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000441//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000442// Interference eviction
443//===----------------------------------------------------------------------===//
444
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000445/// shouldEvict - determine if A should evict the assigned live range B. The
446/// eviction policy defined by this function together with the allocation order
447/// defined by enqueue() decides which registers ultimately end up being split
448/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000449///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000450/// Cascade numbers are used to prevent infinite loops if this function is a
451/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000452///
453/// @param A The live range to be assigned.
454/// @param IsHint True when A is about to be assigned to its preferred
455/// register.
456/// @param B The live range to be evicted.
457/// @param BreaksHint True when B is already assigned to its preferred register.
458bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
459 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000460 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000461
462 // Be fairly aggressive about following hints as long as the evictee can be
463 // split.
464 if (CanSplit && IsHint && !BreaksHint)
465 return true;
466
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000467 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000468}
469
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000470/// canEvictInterference - Return true if all interferences between VirtReg and
471/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
472///
473/// @param VirtReg Live range that is about to be assigned.
474/// @param PhysReg Desired register for assignment.
475/// @prarm IsHint True when PhysReg is VirtReg's preferred register.
476/// @param MaxCost Only look for cheaper candidates and update with new cost
477/// when returning true.
478/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000479bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000480 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000481 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
482 // involved in an eviction before. If a cascade number was assigned, deny
483 // evicting anything with the same or a newer cascade number. This prevents
484 // infinite eviction loops.
485 //
486 // This works out so a register without a cascade number is allowed to evict
487 // anything, and it can be evicted by anything.
488 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
489 if (!Cascade)
490 Cascade = NextCascade;
491
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000492 EvictionCost Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000493 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
494 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000495 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000496 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000497 return false;
498
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000499 // Check if any interfering live range is heavier than MaxWeight.
500 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
501 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000502 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
503 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000504 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000505 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000506 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000507 // Once a live range becomes small enough, it is urgent that we find a
508 // register for it. This is indicated by an infinite spill weight. These
509 // urgent live ranges get to evict almost anything.
510 bool Urgent = !VirtReg.isSpillable() && Intf->isSpillable();
511 // Only evict older cascades or live ranges without a cascade.
512 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
513 if (Cascade <= IntfCascade) {
514 if (!Urgent)
515 return false;
516 // We permit breaking cascades for urgent evictions. It should be the
517 // last resort, though, so make it really expensive.
518 Cost.BrokenHints += 10;
519 }
520 // Would this break a satisfied hint?
521 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
522 // Update eviction cost.
523 Cost.BrokenHints += BreaksHint;
524 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
525 // Abort if this would be too expensive.
526 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000527 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000528 // Finally, apply the eviction policy for non-urgent evictions.
529 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000530 return false;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000531 }
532 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000533 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000534 return true;
535}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000536
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000537/// evictInterference - Evict any interferring registers that prevent VirtReg
538/// from being assigned to Physreg. This assumes that canEvictInterference
539/// returned true.
540void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
541 SmallVectorImpl<LiveInterval*> &NewVRegs) {
542 // Make sure that VirtReg has a cascade number, and assign that cascade
543 // number to every evicted register. These live ranges than then only be
544 // evicted by a newer cascade, preventing infinite loops.
545 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
546 if (!Cascade)
547 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
548
549 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
550 << " interference: Cascade " << Cascade << '\n');
551 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
552 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
553 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
554 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
555 LiveInterval *Intf = Q.interferingVRegs()[i];
556 unassign(*Intf, VRM->getPhys(Intf->reg));
557 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
558 VirtReg.isSpillable() < Intf->isSpillable()) &&
559 "Cannot decrease cascade number, illegal eviction");
560 ExtraRegInfo[Intf->reg].Cascade = Cascade;
561 ++NumEvicted;
562 NewVRegs.push_back(Intf);
563 }
564 }
565}
566
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000567/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000568/// @param VirtReg Currently unassigned virtual register.
569/// @param Order Physregs to try.
570/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000571unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
572 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000573 SmallVectorImpl<LiveInterval*> &NewVRegs,
574 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000575 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
576
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000577 // Keep track of the cheapest interference seen so far.
578 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000579 unsigned BestPhys = 0;
580
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000581 // When we are just looking for a reduced cost per use, don't break any
582 // hints, and only evict smaller spill weights.
583 if (CostPerUseLimit < ~0u) {
584 BestCost.BrokenHints = 0;
585 BestCost.MaxWeight = VirtReg.weight;
586 }
587
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000588 Order.rewind();
589 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000590 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
591 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000592 // The first use of a callee-saved register in a function has cost 1.
593 // Don't start using a CSR when the CostPerUseLimit is low.
594 if (CostPerUseLimit == 1)
595 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
596 if (!MRI->isPhysRegUsed(CSR)) {
597 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
598 << PrintReg(CSR, TRI) << '\n');
599 continue;
600 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000601
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000602 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000603 continue;
604
605 // Best so far.
606 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000607
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000608 // Stop if the hint can be used.
609 if (Order.isHint(PhysReg))
610 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000611 }
612
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000613 if (!BestPhys)
614 return 0;
615
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000616 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000617 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000618}
619
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000620
621//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000622// Region Splitting
623//===----------------------------------------------------------------------===//
624
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000625/// addSplitConstraints - Fill out the SplitConstraints vector based on the
626/// interference pattern in Physreg and its aliases. Add the constraints to
627/// SpillPlacement and return the static cost of this split in Cost, assuming
628/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000629/// Return false if there are no bundles with positive bias.
630bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
631 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000632 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000633
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000634 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000635 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000636 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000637 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
638 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000639 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000640
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000641 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000642 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000643 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
644 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000645
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000646 if (!Intf.hasInterference())
647 continue;
648
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000649 // Number of spill code instructions to insert.
650 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000651
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000652 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000653 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000654 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000655 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000656 else if (Intf.first() < BI.FirstUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000657 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesena2e79ef2011-05-30 01:33:26 +0000658 else if (Intf.first() < BI.LastUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000659 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000660 }
661
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000662 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000663 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000664 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000665 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000666 else if (Intf.last() > BI.LastUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000667 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesena2e79ef2011-05-30 01:33:26 +0000668 else if (Intf.last() > BI.FirstUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000669 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000670 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000671
672 // Accumulate the total frequency of inserted spill code.
673 if (Ins)
674 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000675 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000676 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000677
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000678 // Add constraints for use-blocks. Note that these are the only constraints
679 // that may add a positive bias, it is downhill from here.
680 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000681 return SpillPlacer->scanActiveBundles();
682}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000683
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000684
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000685/// addThroughConstraints - Add constraints and links to SpillPlacer from the
686/// live-through blocks in Blocks.
687void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
688 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000689 const unsigned GroupSize = 8;
690 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000691 unsigned TBS[GroupSize];
692 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000693
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000694 for (unsigned i = 0; i != Blocks.size(); ++i) {
695 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000696 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000697
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000698 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000699 assert(T < GroupSize && "Array overflow");
700 TBS[T] = Number;
701 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000702 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000703 T = 0;
704 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000705 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000706 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000707
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000708 assert(B < GroupSize && "Array overflow");
709 BCS[B].Number = Number;
710
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000711 // Interference for the live-in value.
712 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
713 BCS[B].Entry = SpillPlacement::MustSpill;
714 else
715 BCS[B].Entry = SpillPlacement::PrefSpill;
716
717 // Interference for the live-out value.
718 if (Intf.last() >= SA->getLastSplitPoint(Number))
719 BCS[B].Exit = SpillPlacement::MustSpill;
720 else
721 BCS[B].Exit = SpillPlacement::PrefSpill;
722
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000723 if (++B == GroupSize) {
724 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
725 SpillPlacer->addConstraints(Array);
726 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000727 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000728 }
729
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000730 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
731 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000732 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000733}
734
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000735void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000736 // Keep track of through blocks that have not been added to SpillPlacer.
737 BitVector Todo = SA->getThroughBlocks();
738 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
739 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000740#ifndef NDEBUG
741 unsigned Visited = 0;
742#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000743
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000744 for (;;) {
745 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000746 // Find new through blocks in the periphery of PrefRegBundles.
747 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
748 unsigned Bundle = NewBundles[i];
749 // Look at all blocks connected to Bundle in the full graph.
750 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
751 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
752 I != E; ++I) {
753 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000754 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000755 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000756 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000757 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000758 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000759#ifndef NDEBUG
760 ++Visited;
761#endif
762 }
763 }
764 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000765 if (ActiveBlocks.size() == AddedTo)
766 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000767
768 // Compute through constraints from the interference, or assume that all
769 // through blocks prefer spilling when forming compact regions.
770 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
771 if (Cand.PhysReg)
772 addThroughConstraints(Cand.Intf, NewBlocks);
773 else
774 SpillPlacer->addPrefSpill(NewBlocks);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000775 AddedTo = ActiveBlocks.size();
776
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000777 // Perhaps iterating can enable more bundles?
778 SpillPlacer->iterate();
779 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000780 DEBUG(dbgs() << ", v=" << Visited);
781}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000782
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000783/// calcCompactRegion - Compute the set of edge bundles that should be live
784/// when splitting the current live range into compact regions. Compact
785/// regions can be computed without looking at interference. They are the
786/// regions formed by removing all the live-through blocks from the live range.
787///
788/// Returns false if the current live range is already compact, or if the
789/// compact regions would form single block regions anyway.
790bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
791 // Without any through blocks, the live range is already compact.
792 if (!SA->getNumThroughBlocks())
793 return false;
794
795 // Compact regions don't correspond to any physreg.
796 Cand.reset(IntfCache, 0);
797
798 DEBUG(dbgs() << "Compact region bundles");
799
800 // Use the spill placer to determine the live bundles. GrowRegion pretends
801 // that all the through blocks have interference when PhysReg is unset.
802 SpillPlacer->prepare(Cand.LiveBundles);
803
804 // The static split cost will be zero since Cand.Intf reports no interference.
805 float Cost;
806 if (!addSplitConstraints(Cand.Intf, Cost)) {
807 DEBUG(dbgs() << ", none.\n");
808 return false;
809 }
810
811 growRegion(Cand);
812 SpillPlacer->finish();
813
814 if (!Cand.LiveBundles.any()) {
815 DEBUG(dbgs() << ", none.\n");
816 return false;
817 }
818
819 DEBUG({
820 for (int i = Cand.LiveBundles.find_first(); i>=0;
821 i = Cand.LiveBundles.find_next(i))
822 dbgs() << " EB#" << i;
823 dbgs() << ".\n";
824 });
825 return true;
826}
827
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000828/// calcSpillCost - Compute how expensive it would be to split the live range in
829/// SA around all use blocks instead of forming bundle regions.
830float RAGreedy::calcSpillCost() {
831 float Cost = 0;
832 const LiveInterval &LI = SA->getParent();
833 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
834 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
835 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
836 unsigned Number = BI.MBB->getNumber();
837 // We normally only need one spill instruction - a load or a store.
838 Cost += SpillPlacer->getBlockFrequency(Number);
839
840 // Unless the value is redefined in the block.
841 if (BI.LiveIn && BI.LiveOut) {
842 SlotIndex Start, Stop;
843 tie(Start, Stop) = Indexes->getMBBRange(Number);
844 LiveInterval::const_iterator I = LI.find(Start);
845 assert(I != LI.end() && "Expected live-in value");
846 // Is there a different live-out value? If so, we need an extra spill
847 // instruction.
848 if (I->end < Stop)
849 Cost += SpillPlacer->getBlockFrequency(Number);
850 }
851 }
852 return Cost;
853}
854
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000855/// calcGlobalSplitCost - Return the global split cost of following the split
856/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000857/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000858///
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000859float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000860 float GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000861 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000862 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
863 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
864 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000865 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000866 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
867 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
868 unsigned Ins = 0;
869
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000870 if (BI.LiveIn)
871 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
872 if (BI.LiveOut)
873 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000874 if (Ins)
875 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000876 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000877
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000878 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
879 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000880 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
881 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000882 if (!RegIn && !RegOut)
883 continue;
884 if (RegIn && RegOut) {
885 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000886 Cand.Intf.moveToBlock(Number);
887 if (Cand.Intf.hasInterference())
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000888 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
889 continue;
890 }
891 // live-in / stack-out or stack-in live-out.
892 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000893 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000894 return GlobalCost;
895}
896
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000897/// splitAroundRegion - Split VirtReg around the region determined by
898/// LiveBundles. Make an effort to avoid interference from PhysReg.
899///
900/// The 'register' interval is going to contain as many uses as possible while
901/// avoiding interference. The 'stack' interval is the complement constructed by
902/// SplitEditor. It will contain the rest.
903///
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000904void RAGreedy::splitAroundRegion(LiveInterval &VirtReg,
905 GlobalSplitCandidate &Cand,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000906 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000907 const BitVector &LiveBundles = Cand.LiveBundles;
908
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000909 DEBUG({
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000910 dbgs() << "Splitting around region for " << PrintReg(Cand.PhysReg, TRI)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000911 << " with bundles";
912 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
913 dbgs() << " EB#" << i;
914 dbgs() << ".\n";
915 });
916
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000917 InterferenceCache::Cursor &Intf = Cand.Intf;
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000918 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000919 SE->reset(LREdit);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000920
921 // Create the main cross-block interval.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000922 const unsigned MainIntv = SE->openIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000923
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000924 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000925 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
926 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
927 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000928 bool RegIn = BI.LiveIn &&
929 LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
930 bool RegOut = BI.LiveOut &&
931 LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000932
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000933 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000934 if (!RegIn && !RegOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000935 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000936 if (!BI.isOneInstr()) {
937 SE->splitSingleBlock(BI);
938 SE->selectIntv(MainIntv);
939 }
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000940 continue;
941 }
942
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000943 Intf.moveToBlock(BI.MBB->getNumber());
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000944
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +0000945 if (RegIn && RegOut)
946 SE->splitLiveThroughBlock(BI.MBB->getNumber(),
947 MainIntv, Intf.first(),
948 MainIntv, Intf.last());
949 else if (RegIn)
950 SE->splitRegInBlock(BI, MainIntv, Intf.first());
951 else
952 SE->splitRegOutBlock(BI, MainIntv, Intf.last());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000953 }
954
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000955 // Handle live-through blocks.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000956 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
957 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000958 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
959 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +0000960 if (!RegIn && !RegOut)
961 continue;
962 Intf.moveToBlock(Number);
963 SE->splitLiveThroughBlock(Number, RegIn ? MainIntv : 0, Intf.first(),
964 RegOut ? MainIntv : 0, Intf.last());
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000965 }
966
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000967 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000968
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000969 SmallVector<unsigned, 8> IntvMap;
970 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000971 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
972
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000973 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +0000974 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000975
976 // Sort out the new intervals created by splitting. We get four kinds:
977 // - Remainder intervals should not be split again.
978 // - Candidate intervals can be assigned to Cand.PhysReg.
979 // - Block-local splits are candidates for local splitting.
980 // - DCE leftovers should go back on the queue.
981 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000982 LiveInterval &Reg = *LREdit.get(i);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000983
984 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000985 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000986 continue;
987
988 // Remainder interval. Don't try splitting again, spill if it doesn't
989 // allocate.
990 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000991 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000992 continue;
993 }
994
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +0000995 // Main interval. Allow repeated splitting as long as the number of live
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000996 // blocks is strictly decreasing. Otherwise force per-block splitting.
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +0000997 if (IntvMap[i] == MainIntv) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000998 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +0000999 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1000 << " blocks as original.\n");
1001 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001002 setStage(Reg, RS_Split2);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001003 }
1004 continue;
1005 }
1006
1007 // Other intervals are treated as new. This includes local intervals created
1008 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001009 }
1010
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001011 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001012 MF->verify(this, "After splitting live range around region");
1013}
1014
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001015unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1016 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001017 float BestCost = Hysteresis * calcSpillCost();
1018 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001019 const unsigned NoCand = ~0u;
1020 unsigned BestCand = NoCand;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001021 unsigned NumCands = 0;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001022
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001023 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001024 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001025 // Discard bad candidates before we run out of interference cache cursors.
1026 // This will only affect register classes with a lot of registers (>32).
1027 if (NumCands == IntfCache.getMaxCursors()) {
1028 unsigned WorstCount = ~0u;
1029 unsigned Worst = 0;
1030 for (unsigned i = 0; i != NumCands; ++i) {
1031 if (i == BestCand)
1032 continue;
1033 unsigned Count = GlobalCand[i].LiveBundles.count();
1034 if (Count < WorstCount)
1035 Worst = i, WorstCount = Count;
1036 }
1037 --NumCands;
1038 GlobalCand[Worst] = GlobalCand[NumCands];
1039 }
1040
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001041 if (GlobalCand.size() <= NumCands)
1042 GlobalCand.resize(NumCands+1);
1043 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1044 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001045
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001046 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001047 float Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001048 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001049 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001050 continue;
1051 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001052 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001053 if (Cost >= BestCost) {
1054 DEBUG({
1055 if (BestCand == NoCand)
1056 dbgs() << " worse than no bundles\n";
1057 else
1058 dbgs() << " worse than "
1059 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1060 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001061 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001062 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001063 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001064
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001065 SpillPlacer->finish();
1066
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001067 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001068 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001069 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001070 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001071 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001072
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001073 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001074 DEBUG({
1075 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001076 for (int i = Cand.LiveBundles.find_first(); i>=0;
1077 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001078 dbgs() << " EB#" << i;
1079 dbgs() << ".\n";
1080 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001081 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001082 BestCand = NumCands;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001083 BestCost = Hysteresis * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001084 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001085 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001086 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001087
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001088 if (BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001089 return 0;
1090
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001091 splitAroundRegion(VirtReg, GlobalCand[BestCand], NewVRegs);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001092 return 0;
1093}
1094
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001095
1096//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001097// Local Splitting
1098//===----------------------------------------------------------------------===//
1099
1100
1101/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1102/// in order to use PhysReg between two entries in SA->UseSlots.
1103///
1104/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1105///
1106void RAGreedy::calcGapWeights(unsigned PhysReg,
1107 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001108 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1109 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001110 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1111 const unsigned NumGaps = Uses.size()-1;
1112
1113 // Start and end points for the interference check.
1114 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
1115 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
1116
1117 GapWeight.assign(NumGaps, 0.0f);
1118
1119 // Add interference from each overlapping register.
1120 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
1121 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
1122 .checkInterference())
1123 continue;
1124
1125 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
1126 // so we don't need InterferenceQuery.
1127 //
1128 // Interference that overlaps an instruction is counted in both gaps
1129 // surrounding the instruction. The exception is interference before
1130 // StartIdx and after StopIdx.
1131 //
1132 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
1133 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1134 // Skip the gaps before IntI.
1135 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1136 if (++Gap == NumGaps)
1137 break;
1138 if (Gap == NumGaps)
1139 break;
1140
1141 // Update the gaps covered by IntI.
1142 const float weight = IntI.value()->weight;
1143 for (; Gap != NumGaps; ++Gap) {
1144 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1145 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1146 break;
1147 }
1148 if (Gap == NumGaps)
1149 break;
1150 }
1151 }
1152}
1153
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001154/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1155/// basic block.
1156///
1157unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1158 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001159 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1160 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001161
1162 // Note that it is possible to have an interval that is live-in or live-out
1163 // while only covering a single block - A phi-def can use undef values from
1164 // predecessors, and the block could be a single-block loop.
1165 // We don't bother doing anything clever about such a case, we simply assume
1166 // that the interval is continuous from FirstUse to LastUse. We should make
1167 // sure that we don't do anything illegal to such an interval, though.
1168
1169 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1170 if (Uses.size() <= 2)
1171 return 0;
1172 const unsigned NumGaps = Uses.size()-1;
1173
1174 DEBUG({
1175 dbgs() << "tryLocalSplit: ";
1176 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1177 dbgs() << ' ' << SA->UseSlots[i];
1178 dbgs() << '\n';
1179 });
1180
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001181 // Since we allow local split results to be split again, there is a risk of
1182 // creating infinite loops. It is tempting to require that the new live
1183 // ranges have less instructions than the original. That would guarantee
1184 // convergence, but it is too strict. A live range with 3 instructions can be
1185 // split 2+3 (including the COPY), and we want to allow that.
1186 //
1187 // Instead we use these rules:
1188 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001189 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001190 // noop split, of course).
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001191 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001192 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001193 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001194 // smaller ranges are marked RS_New.
1195 //
1196 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1197 // excessive splitting and infinite loops.
1198 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001199 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001200
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001201 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001202 unsigned BestBefore = NumGaps;
1203 unsigned BestAfter = 0;
1204 float BestDiff = 0;
1205
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001206 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001207 SmallVector<float, 8> GapWeight;
1208
1209 Order.rewind();
1210 while (unsigned PhysReg = Order.next()) {
1211 // Keep track of the largest spill weight that would need to be evicted in
1212 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1213 calcGapWeights(PhysReg, GapWeight);
1214
1215 // Try to find the best sequence of gaps to close.
1216 // The new spill weight must be larger than any gap interference.
1217
1218 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001219 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001220
1221 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1222 // It is the spill weight that needs to be evicted.
1223 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001224
1225 for (;;) {
1226 // Live before/after split?
1227 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1228 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1229
1230 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1231 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1232 << " i=" << MaxGap);
1233
1234 // Stop before the interval gets so big we wouldn't be making progress.
1235 if (!LiveBefore && !LiveAfter) {
1236 DEBUG(dbgs() << " all\n");
1237 break;
1238 }
1239 // Should the interval be extended or shrunk?
1240 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001241
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001242 // How many gaps would the new range have?
1243 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1244
1245 // Legally, without causing looping?
1246 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1247
1248 if (Legal && MaxGap < HUGE_VALF) {
1249 // Estimate the new spill weight. Each instruction reads or writes the
1250 // register. Conservatively assume there are no read-modify-write
1251 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001252 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001253 // Try to guess the size of the new interval.
1254 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1255 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1256 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001257 // Would this split be possible to allocate?
1258 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001259 DEBUG(dbgs() << " w=" << EstWeight);
1260 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001261 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001262 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001263 if (Diff > BestDiff) {
1264 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001265 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001266 BestBefore = SplitBefore;
1267 BestAfter = SplitAfter;
1268 }
1269 }
1270 }
1271
1272 // Try to shrink.
1273 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001274 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001275 DEBUG(dbgs() << " shrink\n");
1276 // Recompute the max when necessary.
1277 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1278 MaxGap = GapWeight[SplitBefore];
1279 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1280 MaxGap = std::max(MaxGap, GapWeight[i]);
1281 }
1282 continue;
1283 }
1284 MaxGap = 0;
1285 }
1286
1287 // Try to extend the interval.
1288 if (SplitAfter >= NumGaps) {
1289 DEBUG(dbgs() << " end\n");
1290 break;
1291 }
1292
1293 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001294 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001295 }
1296 }
1297
1298 // Didn't find any candidates?
1299 if (BestBefore == NumGaps)
1300 return 0;
1301
1302 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1303 << '-' << Uses[BestAfter] << ", " << BestDiff
1304 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1305
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001306 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001307 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001308
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001309 SE->openIntv();
1310 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1311 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1312 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001313 SmallVector<unsigned, 8> IntvMap;
1314 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001315 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001316
1317 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001318 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001319 // leave the new intervals as RS_New so they can compete.
1320 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1321 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1322 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1323 if (NewGaps >= NumGaps) {
1324 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1325 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001326 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1327 if (IntvMap[i] == 1) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001328 setStage(*LREdit.get(i), RS_Split2);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001329 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1330 }
1331 DEBUG(dbgs() << '\n');
1332 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001333 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001334
1335 return 0;
1336}
1337
1338//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001339// Live Range Splitting
1340//===----------------------------------------------------------------------===//
1341
1342/// trySplit - Try to split VirtReg or one of its interferences, making it
1343/// assignable.
1344/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1345unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1346 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001347 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001348 if (LIS->intervalIsInOneMBB(VirtReg)) {
1349 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001350 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001351 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001352 }
1353
1354 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001355
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001356 // Ranges must be Split2 or less.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001357 if (getStage(VirtReg) >= RS_Spill)
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001358 return 0;
1359
1360 SA->analyze(&VirtReg);
1361
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001362 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1363 // coalescer. That may cause the range to become allocatable which means that
1364 // tryRegionSplit won't be making progress. This check should be replaced with
1365 // an assertion when the coalescer is fixed.
1366 if (SA->didRepairRange()) {
1367 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesenbdda37d2011-05-10 17:37:41 +00001368 invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001369 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1370 return PhysReg;
1371 }
1372
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001373 // First try to split around a region spanning multiple blocks. RS_Split2
1374 // ranges already made dubious progress with region splitting, so they go
1375 // straight to single block splitting.
1376 if (getStage(VirtReg) < RS_Split2) {
1377 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1378 if (PhysReg || !NewVRegs.empty())
1379 return PhysReg;
1380 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001381
1382 // Then isolate blocks with multiple uses.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001383 SplitAnalysis::BlockPtrSet Blocks;
1384 if (SA->getMultiUseBlocks(Blocks)) {
1385 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1386 SE->reset(LREdit);
1387 SE->splitSingleBlocks(Blocks);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001388 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Spill);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001389 if (VerifyEnabled)
1390 MF->verify(this, "After splitting live range around basic blocks");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001391 }
1392
1393 // Don't assign any physregs.
1394 return 0;
1395}
1396
1397
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001398//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001399// Main Entry Point
1400//===----------------------------------------------------------------------===//
1401
1402unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001403 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001404 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001405 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001406 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1407 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001408
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001409 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001410 DEBUG(dbgs() << StageName[Stage]
1411 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001412
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001413 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001414 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001415 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001416 if (Stage != RS_Split)
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001417 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1418 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001419
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001420 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1421
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001422 // The first time we see a live range, don't try to split or spill.
1423 // Wait until the second time, when all smaller ranges have been allocated.
1424 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001425 if (Stage < RS_Split) {
1426 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001427 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001428 NewVRegs.push_back(&VirtReg);
1429 return 0;
1430 }
1431
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001432 // If we couldn't allocate a register from spilling, there is probably some
1433 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001434 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001435 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001436
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001437 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001438 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1439 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001440 return PhysReg;
1441
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001442 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001443 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001444 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1445 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001446 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001447
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001448 if (VerifyEnabled)
1449 MF->verify(this, "After spilling");
1450
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001451 // The live virtual register requesting allocation was spilled, so tell
1452 // the caller not to allocate anything during this round.
1453 return 0;
1454}
1455
1456bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1457 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1458 << "********** Function: "
1459 << ((Value*)mf.getFunction())->getName() << '\n');
1460
1461 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001462 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001463 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001464
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001465 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001466 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001467 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001468 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001469 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001470 Bundles = &getAnalysis<EdgeBundles>();
1471 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001472 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001473
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001474 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001475 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001476 ExtraRegInfo.clear();
1477 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1478 NextCascade = 1;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +00001479 IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001480
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001481 allocatePhysRegs();
1482 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001483 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001484
1485 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001486 {
1487 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001488 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001489 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001490
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001491 // Write out new DBG_VALUE instructions.
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001492 DebugVars->emitDebugValues(VRM);
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001493
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001494 // The pass output is in VirtRegMap. Release all the transient data.
1495 releaseMemory();
1496
1497 return true;
1498}