blob: 0267717b8435a2870f58d4d4b2ae36b0ddccc5cb [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 Olesenf22ca3f2011-03-30 02:52:39 +000093 RS_New, ///< Never seen before.
94 RS_First, ///< First time in the queue.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +000095 RS_Second, ///< Second time in the queue.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +000096 RS_Global, ///< Produced by global splitting.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000097 RS_Local, ///< Produced by local splitting.
98 RS_Spill ///< Produced by spilling.
99 };
100
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000101 static const char *const StageName[];
102
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000103 // RegInfo - Keep additional information about each live range.
104 struct RegInfo {
105 LiveRangeStage Stage;
106
107 // Cascade - Eviction loop prevention. See canEvictInterference().
108 unsigned Cascade;
109
110 RegInfo() : Stage(RS_New), Cascade(0) {}
111 };
112
113 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000114
115 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000116 return ExtraRegInfo[VirtReg.reg].Stage;
117 }
118
119 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
120 ExtraRegInfo.resize(MRI->getNumVirtRegs());
121 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000122 }
123
124 template<typename Iterator>
125 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000126 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000127 for (;Begin != End; ++Begin) {
128 unsigned Reg = (*Begin)->reg;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000129 if (ExtraRegInfo[Reg].Stage == RS_New)
130 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000131 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000132 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000133
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000134 /// Cost of evicting interference.
135 struct EvictionCost {
136 unsigned BrokenHints; ///< Total number of broken hints.
137 float MaxWeight; ///< Maximum spill weight evicted.
138
139 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
140
141 bool operator<(const EvictionCost &O) const {
142 if (BrokenHints != O.BrokenHints)
143 return BrokenHints < O.BrokenHints;
144 return MaxWeight < O.MaxWeight;
145 }
146 };
147
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000148 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000149 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000150 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000151
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000152 /// Cached per-block interference maps
153 InterferenceCache IntfCache;
154
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000155 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000156 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000157
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000158 /// Global live range splitting candidate info.
159 struct GlobalSplitCandidate {
160 unsigned PhysReg;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000161 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000162 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000163 SmallVector<unsigned, 8> ActiveBlocks;
164
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000165 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000166 PhysReg = Reg;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000167 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000168 LiveBundles.clear();
169 ActiveBlocks.clear();
170 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000171 };
172
173 /// Candidate info for for each PhysReg in AllocationOrder.
174 /// This vector never shrinks, but grows to the size of the largest register
175 /// class.
176 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
177
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000178public:
179 RAGreedy();
180
181 /// Return the pass name.
182 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000183 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000184 }
185
186 /// RAGreedy analysis usage.
187 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000188 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000189 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000190 virtual void enqueue(LiveInterval *LI);
191 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000192 virtual unsigned selectOrSplit(LiveInterval&,
193 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000194
195 /// Perform register allocation.
196 virtual bool runOnMachineFunction(MachineFunction &mf);
197
198 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000199
200private:
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000201 void LRE_WillEraseInstruction(MachineInstr*);
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000202 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000203 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000204 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000205
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000206 float calcSpillCost();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000207 bool addSplitConstraints(InterferenceCache::Cursor, float&);
208 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000209 void growRegion(GlobalSplitCandidate &Cand);
210 float calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000211 void splitAroundRegion(LiveInterval&, GlobalSplitCandidate&,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000212 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000213 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000214 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
215 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
216 void evictInterference(LiveInterval&, unsigned,
217 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000218
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000219 unsigned tryAssign(LiveInterval&, AllocationOrder&,
220 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000221 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000222 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000223 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
224 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000225 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
226 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000227 unsigned trySplit(LiveInterval&, AllocationOrder&,
228 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000229};
230} // end anonymous namespace
231
232char RAGreedy::ID = 0;
233
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000234#ifndef NDEBUG
235const char *const RAGreedy::StageName[] = {
236 "RS_New",
237 "RS_First",
238 "RS_Second",
239 "RS_Global",
240 "RS_Local",
241 "RS_Spill"
242};
243#endif
244
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000245// Hysteresis to use when comparing floats.
246// This helps stabilize decisions based on float comparisons.
247const float Hysteresis = 0.98f;
248
249
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000250FunctionPass* llvm::createGreedyRegisterAllocator() {
251 return new RAGreedy();
252}
253
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000254RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000255 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000256 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000257 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
258 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
259 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000260 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000261 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
262 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
263 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
264 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
265 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000266 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
267 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000268}
269
270void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
271 AU.setPreservesCFG();
272 AU.addRequired<AliasAnalysis>();
273 AU.addPreserved<AliasAnalysis>();
274 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000275 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000276 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000277 AU.addRequired<LiveDebugVariables>();
278 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000279 if (StrongPHIElim)
280 AU.addRequiredID(StrongPHIEliminationID);
281 AU.addRequiredTransitive<RegisterCoalescer>();
282 AU.addRequired<CalculateSpillWeights>();
283 AU.addRequired<LiveStacks>();
284 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000285 AU.addRequired<MachineDominatorTree>();
286 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000287 AU.addRequired<MachineLoopInfo>();
288 AU.addPreserved<MachineLoopInfo>();
289 AU.addRequired<VirtRegMap>();
290 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000291 AU.addRequired<EdgeBundles>();
292 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000293 MachineFunctionPass::getAnalysisUsage(AU);
294}
295
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000296
297//===----------------------------------------------------------------------===//
298// LiveRangeEdit delegate methods
299//===----------------------------------------------------------------------===//
300
301void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
302 // LRE itself will remove from SlotIndexes and parent basic block.
303 VRM->RemoveMachineInstrFromMaps(MI);
304}
305
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000306bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
307 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
308 unassign(LIS->getInterval(VirtReg), PhysReg);
309 return true;
310 }
311 // Unassigned virtreg is probably in the priority queue.
312 // RegAllocBase will erase it after dequeueing.
313 return false;
314}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000315
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000316void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
317 unsigned PhysReg = VRM->getPhys(VirtReg);
318 if (!PhysReg)
319 return;
320
321 // Register is assigned, put it back on the queue for reassignment.
322 LiveInterval &LI = LIS->getInterval(VirtReg);
323 unassign(LI, PhysReg);
324 enqueue(&LI);
325}
326
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000327void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
328 // LRE may clone a virtual register because dead code elimination causes it to
329 // be split into connected components. Ensure that the new register gets the
330 // same stage as the parent.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000331 ExtraRegInfo.grow(New);
332 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000333}
334
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000335void RAGreedy::releaseMemory() {
336 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000337 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000338 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000339 RegAllocBase::releaseMemory();
340}
341
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000342void RAGreedy::enqueue(LiveInterval *LI) {
343 // Prioritize live ranges by size, assigning larger ranges first.
344 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000345 const unsigned Size = LI->getSize();
346 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000347 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
348 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000349 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000350
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000351 ExtraRegInfo.grow(Reg);
352 if (ExtraRegInfo[Reg].Stage == RS_New)
353 ExtraRegInfo[Reg].Stage = RS_First;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000354
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000355 if (ExtraRegInfo[Reg].Stage == RS_Second)
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000356 // Unsplit ranges that couldn't be allocated immediately are deferred until
357 // everything else has been allocated. Long ranges are allocated last so
358 // they are split against realistic interference.
359 Prio = (1u << 31) - Size;
360 else {
361 // Everything else is allocated in long->short order. Long ranges that don't
362 // fit should be spilled ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000363 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000364
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000365 // Boost ranges that have a physical register hint.
366 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
367 Prio |= (1u << 30);
368 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000369
370 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000371}
372
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000373LiveInterval *RAGreedy::dequeue() {
374 if (Queue.empty())
375 return 0;
376 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
377 Queue.pop();
378 return LI;
379}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000380
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000381
382//===----------------------------------------------------------------------===//
383// Direct Assignment
384//===----------------------------------------------------------------------===//
385
386/// tryAssign - Try to assign VirtReg to an available register.
387unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
388 AllocationOrder &Order,
389 SmallVectorImpl<LiveInterval*> &NewVRegs) {
390 Order.rewind();
391 unsigned PhysReg;
392 while ((PhysReg = Order.next()))
393 if (!checkPhysRegInterference(VirtReg, PhysReg))
394 break;
395 if (!PhysReg || Order.isHint(PhysReg))
396 return PhysReg;
397
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000398 // PhysReg is available, but there may be a better choice.
399
400 // If we missed a simple hint, try to cheaply evict interference from the
401 // preferred register.
402 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
403 if (Order.isHint(Hint)) {
404 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
405 EvictionCost MaxCost(1);
406 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
407 evictInterference(VirtReg, Hint, NewVRegs);
408 return Hint;
409 }
410 }
411
412 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000413 unsigned Cost = TRI->getCostPerUse(PhysReg);
414
415 // Most registers have 0 additional cost.
416 if (!Cost)
417 return PhysReg;
418
419 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
420 << '\n');
421 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
422 return CheapReg ? CheapReg : PhysReg;
423}
424
425
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000426//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000427// Interference eviction
428//===----------------------------------------------------------------------===//
429
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000430/// shouldEvict - determine if A should evict the assigned live range B. The
431/// eviction policy defined by this function together with the allocation order
432/// defined by enqueue() decides which registers ultimately end up being split
433/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000434///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000435/// Cascade numbers are used to prevent infinite loops if this function is a
436/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000437///
438/// @param A The live range to be assigned.
439/// @param IsHint True when A is about to be assigned to its preferred
440/// register.
441/// @param B The live range to be evicted.
442/// @param BreaksHint True when B is already assigned to its preferred register.
443bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
444 LiveInterval &B, bool BreaksHint) {
445 bool CanSplit = getStage(B) <= RS_Second;
446
447 // Be fairly aggressive about following hints as long as the evictee can be
448 // split.
449 if (CanSplit && IsHint && !BreaksHint)
450 return true;
451
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000452 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000453}
454
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000455/// canEvictInterference - Return true if all interferences between VirtReg and
456/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
457///
458/// @param VirtReg Live range that is about to be assigned.
459/// @param PhysReg Desired register for assignment.
460/// @prarm IsHint True when PhysReg is VirtReg's preferred register.
461/// @param MaxCost Only look for cheaper candidates and update with new cost
462/// when returning true.
463/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000464bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000465 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000466 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
467 // involved in an eviction before. If a cascade number was assigned, deny
468 // evicting anything with the same or a newer cascade number. This prevents
469 // infinite eviction loops.
470 //
471 // This works out so a register without a cascade number is allowed to evict
472 // anything, and it can be evicted by anything.
473 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
474 if (!Cascade)
475 Cascade = NextCascade;
476
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000477 EvictionCost Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000478 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
479 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000480 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000481 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000482 return false;
483
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000484 // Check if any interfering live range is heavier than MaxWeight.
485 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
486 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000487 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
488 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000489 // Never evict spill products. They cannot split or spill.
490 if (getStage(*Intf) == RS_Spill)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000491 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000492 // Once a live range becomes small enough, it is urgent that we find a
493 // register for it. This is indicated by an infinite spill weight. These
494 // urgent live ranges get to evict almost anything.
495 bool Urgent = !VirtReg.isSpillable() && Intf->isSpillable();
496 // Only evict older cascades or live ranges without a cascade.
497 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
498 if (Cascade <= IntfCascade) {
499 if (!Urgent)
500 return false;
501 // We permit breaking cascades for urgent evictions. It should be the
502 // last resort, though, so make it really expensive.
503 Cost.BrokenHints += 10;
504 }
505 // Would this break a satisfied hint?
506 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
507 // Update eviction cost.
508 Cost.BrokenHints += BreaksHint;
509 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
510 // Abort if this would be too expensive.
511 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000512 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000513 // Finally, apply the eviction policy for non-urgent evictions.
514 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000515 return false;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000516 }
517 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000518 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000519 return true;
520}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000521
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000522/// evictInterference - Evict any interferring registers that prevent VirtReg
523/// from being assigned to Physreg. This assumes that canEvictInterference
524/// returned true.
525void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
526 SmallVectorImpl<LiveInterval*> &NewVRegs) {
527 // Make sure that VirtReg has a cascade number, and assign that cascade
528 // number to every evicted register. These live ranges than then only be
529 // evicted by a newer cascade, preventing infinite loops.
530 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
531 if (!Cascade)
532 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
533
534 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
535 << " interference: Cascade " << Cascade << '\n');
536 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
537 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
538 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
539 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
540 LiveInterval *Intf = Q.interferingVRegs()[i];
541 unassign(*Intf, VRM->getPhys(Intf->reg));
542 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
543 VirtReg.isSpillable() < Intf->isSpillable()) &&
544 "Cannot decrease cascade number, illegal eviction");
545 ExtraRegInfo[Intf->reg].Cascade = Cascade;
546 ++NumEvicted;
547 NewVRegs.push_back(Intf);
548 }
549 }
550}
551
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000552/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000553/// @param VirtReg Currently unassigned virtual register.
554/// @param Order Physregs to try.
555/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000556unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
557 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000558 SmallVectorImpl<LiveInterval*> &NewVRegs,
559 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000560 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
561
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000562 // Keep track of the cheapest interference seen so far.
563 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000564 unsigned BestPhys = 0;
565
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000566 // When we are just looking for a reduced cost per use, don't break any
567 // hints, and only evict smaller spill weights.
568 if (CostPerUseLimit < ~0u) {
569 BestCost.BrokenHints = 0;
570 BestCost.MaxWeight = VirtReg.weight;
571 }
572
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000573 Order.rewind();
574 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000575 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
576 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000577 // The first use of a callee-saved register in a function has cost 1.
578 // Don't start using a CSR when the CostPerUseLimit is low.
579 if (CostPerUseLimit == 1)
580 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
581 if (!MRI->isPhysRegUsed(CSR)) {
582 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
583 << PrintReg(CSR, TRI) << '\n');
584 continue;
585 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000586
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000587 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000588 continue;
589
590 // Best so far.
591 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000592
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000593 // Stop if the hint can be used.
594 if (Order.isHint(PhysReg))
595 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000596 }
597
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000598 if (!BestPhys)
599 return 0;
600
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000601 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000602 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000603}
604
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000605
606//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000607// Region Splitting
608//===----------------------------------------------------------------------===//
609
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000610/// addSplitConstraints - Fill out the SplitConstraints vector based on the
611/// interference pattern in Physreg and its aliases. Add the constraints to
612/// SpillPlacement and return the static cost of this split in Cost, assuming
613/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000614/// Return false if there are no bundles with positive bias.
615bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
616 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000617 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000618
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000619 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000620 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000621 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000622 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
623 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000624 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000625
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000626 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000627 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000628 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
629 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000630
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000631 if (!Intf.hasInterference())
632 continue;
633
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000634 // Number of spill code instructions to insert.
635 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000636
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000637 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000638 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000639 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000640 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000641 else if (Intf.first() < BI.FirstUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000642 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesena2e79ef2011-05-30 01:33:26 +0000643 else if (Intf.first() < BI.LastUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000644 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000645 }
646
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000647 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000648 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000649 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000650 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000651 else if (Intf.last() > BI.LastUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000652 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesena2e79ef2011-05-30 01:33:26 +0000653 else if (Intf.last() > BI.FirstUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000654 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000655 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000656
657 // Accumulate the total frequency of inserted spill code.
658 if (Ins)
659 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000660 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000661 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000662
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000663 // Add constraints for use-blocks. Note that these are the only constraints
664 // that may add a positive bias, it is downhill from here.
665 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000666 return SpillPlacer->scanActiveBundles();
667}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000668
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000669
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000670/// addThroughConstraints - Add constraints and links to SpillPlacer from the
671/// live-through blocks in Blocks.
672void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
673 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000674 const unsigned GroupSize = 8;
675 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000676 unsigned TBS[GroupSize];
677 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000678
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000679 for (unsigned i = 0; i != Blocks.size(); ++i) {
680 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000681 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000682
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000683 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000684 assert(T < GroupSize && "Array overflow");
685 TBS[T] = Number;
686 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000687 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000688 T = 0;
689 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000690 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000691 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000692
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000693 assert(B < GroupSize && "Array overflow");
694 BCS[B].Number = Number;
695
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000696 // Interference for the live-in value.
697 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
698 BCS[B].Entry = SpillPlacement::MustSpill;
699 else
700 BCS[B].Entry = SpillPlacement::PrefSpill;
701
702 // Interference for the live-out value.
703 if (Intf.last() >= SA->getLastSplitPoint(Number))
704 BCS[B].Exit = SpillPlacement::MustSpill;
705 else
706 BCS[B].Exit = SpillPlacement::PrefSpill;
707
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000708 if (++B == GroupSize) {
709 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
710 SpillPlacer->addConstraints(Array);
711 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000712 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000713 }
714
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000715 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
716 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000717 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000718}
719
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000720void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000721 // Keep track of through blocks that have not been added to SpillPlacer.
722 BitVector Todo = SA->getThroughBlocks();
723 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
724 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000725#ifndef NDEBUG
726 unsigned Visited = 0;
727#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000728
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000729 for (;;) {
730 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000731 // Find new through blocks in the periphery of PrefRegBundles.
732 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
733 unsigned Bundle = NewBundles[i];
734 // Look at all blocks connected to Bundle in the full graph.
735 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
736 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
737 I != E; ++I) {
738 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000739 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000740 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000741 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000742 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000743 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000744#ifndef NDEBUG
745 ++Visited;
746#endif
747 }
748 }
749 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000750 if (ActiveBlocks.size() == AddedTo)
751 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000752
753 // Compute through constraints from the interference, or assume that all
754 // through blocks prefer spilling when forming compact regions.
755 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
756 if (Cand.PhysReg)
757 addThroughConstraints(Cand.Intf, NewBlocks);
758 else
759 SpillPlacer->addPrefSpill(NewBlocks);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000760 AddedTo = ActiveBlocks.size();
761
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000762 // Perhaps iterating can enable more bundles?
763 SpillPlacer->iterate();
764 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000765 DEBUG(dbgs() << ", v=" << Visited);
766}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000767
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000768/// calcSpillCost - Compute how expensive it would be to split the live range in
769/// SA around all use blocks instead of forming bundle regions.
770float RAGreedy::calcSpillCost() {
771 float Cost = 0;
772 const LiveInterval &LI = SA->getParent();
773 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
774 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
775 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
776 unsigned Number = BI.MBB->getNumber();
777 // We normally only need one spill instruction - a load or a store.
778 Cost += SpillPlacer->getBlockFrequency(Number);
779
780 // Unless the value is redefined in the block.
781 if (BI.LiveIn && BI.LiveOut) {
782 SlotIndex Start, Stop;
783 tie(Start, Stop) = Indexes->getMBBRange(Number);
784 LiveInterval::const_iterator I = LI.find(Start);
785 assert(I != LI.end() && "Expected live-in value");
786 // Is there a different live-out value? If so, we need an extra spill
787 // instruction.
788 if (I->end < Stop)
789 Cost += SpillPlacer->getBlockFrequency(Number);
790 }
791 }
792 return Cost;
793}
794
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000795/// calcGlobalSplitCost - Return the global split cost of following the split
796/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000797/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000798///
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000799float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000800 float GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000801 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000802 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
803 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
804 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000805 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000806 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
807 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
808 unsigned Ins = 0;
809
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000810 if (BI.LiveIn)
811 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
812 if (BI.LiveOut)
813 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000814 if (Ins)
815 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000816 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000817
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000818 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
819 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000820 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
821 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000822 if (!RegIn && !RegOut)
823 continue;
824 if (RegIn && RegOut) {
825 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000826 Cand.Intf.moveToBlock(Number);
827 if (Cand.Intf.hasInterference())
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000828 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
829 continue;
830 }
831 // live-in / stack-out or stack-in live-out.
832 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000833 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000834 return GlobalCost;
835}
836
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000837/// splitAroundRegion - Split VirtReg around the region determined by
838/// LiveBundles. Make an effort to avoid interference from PhysReg.
839///
840/// The 'register' interval is going to contain as many uses as possible while
841/// avoiding interference. The 'stack' interval is the complement constructed by
842/// SplitEditor. It will contain the rest.
843///
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000844void RAGreedy::splitAroundRegion(LiveInterval &VirtReg,
845 GlobalSplitCandidate &Cand,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000846 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000847 const BitVector &LiveBundles = Cand.LiveBundles;
848
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000849 DEBUG({
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000850 dbgs() << "Splitting around region for " << PrintReg(Cand.PhysReg, TRI)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000851 << " with bundles";
852 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
853 dbgs() << " EB#" << i;
854 dbgs() << ".\n";
855 });
856
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000857 InterferenceCache::Cursor &Intf = Cand.Intf;
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000858 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000859 SE->reset(LREdit);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000860
861 // Create the main cross-block interval.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000862 const unsigned MainIntv = SE->openIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000863
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000864 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000865 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
866 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
867 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000868 bool RegIn = BI.LiveIn &&
869 LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
870 bool RegOut = BI.LiveOut &&
871 LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000872
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000873 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000874 if (!RegIn && !RegOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000875 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000876 if (!BI.isOneInstr()) {
877 SE->splitSingleBlock(BI);
878 SE->selectIntv(MainIntv);
879 }
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000880 continue;
881 }
882
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000883 Intf.moveToBlock(BI.MBB->getNumber());
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000884
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +0000885 if (RegIn && RegOut)
886 SE->splitLiveThroughBlock(BI.MBB->getNumber(),
887 MainIntv, Intf.first(),
888 MainIntv, Intf.last());
889 else if (RegIn)
890 SE->splitRegInBlock(BI, MainIntv, Intf.first());
891 else
892 SE->splitRegOutBlock(BI, MainIntv, Intf.last());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000893 }
894
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000895 // Handle live-through blocks.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000896 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
897 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000898 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
899 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +0000900 if (!RegIn && !RegOut)
901 continue;
902 Intf.moveToBlock(Number);
903 SE->splitLiveThroughBlock(Number, RegIn ? MainIntv : 0, Intf.first(),
904 RegOut ? MainIntv : 0, Intf.last());
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000905 }
906
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000907 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000908
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000909 SmallVector<unsigned, 8> IntvMap;
910 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000911 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
912
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000913 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +0000914 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000915
916 // Sort out the new intervals created by splitting. We get four kinds:
917 // - Remainder intervals should not be split again.
918 // - Candidate intervals can be assigned to Cand.PhysReg.
919 // - Block-local splits are candidates for local splitting.
920 // - DCE leftovers should go back on the queue.
921 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000922 LiveInterval &Reg = *LREdit.get(i);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000923
924 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000925 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000926 continue;
927
928 // Remainder interval. Don't try splitting again, spill if it doesn't
929 // allocate.
930 if (IntvMap[i] == 0) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000931 setStage(Reg, RS_Global);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000932 continue;
933 }
934
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +0000935 // Main interval. Allow repeated splitting as long as the number of live
936 // blocks is strictly decreasing.
937 if (IntvMap[i] == MainIntv) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000938 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +0000939 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
940 << " blocks as original.\n");
941 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000942 setStage(Reg, RS_Global);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +0000943 }
944 continue;
945 }
946
947 // Other intervals are treated as new. This includes local intervals created
948 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000949 }
950
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000951 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000952 MF->verify(this, "After splitting live range around region");
953}
954
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000955unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
956 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000957 float BestCost = Hysteresis * calcSpillCost();
958 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000959 const unsigned NoCand = ~0u;
960 unsigned BestCand = NoCand;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000961 unsigned NumCands = 0;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000962
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000963 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000964 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +0000965 // Discard bad candidates before we run out of interference cache cursors.
966 // This will only affect register classes with a lot of registers (>32).
967 if (NumCands == IntfCache.getMaxCursors()) {
968 unsigned WorstCount = ~0u;
969 unsigned Worst = 0;
970 for (unsigned i = 0; i != NumCands; ++i) {
971 if (i == BestCand)
972 continue;
973 unsigned Count = GlobalCand[i].LiveBundles.count();
974 if (Count < WorstCount)
975 Worst = i, WorstCount = Count;
976 }
977 --NumCands;
978 GlobalCand[Worst] = GlobalCand[NumCands];
979 }
980
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000981 if (GlobalCand.size() <= NumCands)
982 GlobalCand.resize(NumCands+1);
983 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
984 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000985
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000986 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000987 float Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000988 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000989 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000990 continue;
991 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000992 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000993 if (Cost >= BestCost) {
994 DEBUG({
995 if (BestCand == NoCand)
996 dbgs() << " worse than no bundles\n";
997 else
998 dbgs() << " worse than "
999 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1000 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001001 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001002 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001003 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001004
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001005 SpillPlacer->finish();
1006
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001007 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001008 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001009 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001010 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001011 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001012
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001013 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001014 DEBUG({
1015 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001016 for (int i = Cand.LiveBundles.find_first(); i>=0;
1017 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001018 dbgs() << " EB#" << i;
1019 dbgs() << ".\n";
1020 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001021 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001022 BestCand = NumCands;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001023 BestCost = Hysteresis * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001024 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001025 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001026 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001027
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001028 if (BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001029 return 0;
1030
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001031 splitAroundRegion(VirtReg, GlobalCand[BestCand], NewVRegs);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001032 return 0;
1033}
1034
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001035
1036//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001037// Local Splitting
1038//===----------------------------------------------------------------------===//
1039
1040
1041/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1042/// in order to use PhysReg between two entries in SA->UseSlots.
1043///
1044/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1045///
1046void RAGreedy::calcGapWeights(unsigned PhysReg,
1047 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001048 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1049 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001050 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1051 const unsigned NumGaps = Uses.size()-1;
1052
1053 // Start and end points for the interference check.
1054 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
1055 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
1056
1057 GapWeight.assign(NumGaps, 0.0f);
1058
1059 // Add interference from each overlapping register.
1060 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
1061 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
1062 .checkInterference())
1063 continue;
1064
1065 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
1066 // so we don't need InterferenceQuery.
1067 //
1068 // Interference that overlaps an instruction is counted in both gaps
1069 // surrounding the instruction. The exception is interference before
1070 // StartIdx and after StopIdx.
1071 //
1072 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
1073 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1074 // Skip the gaps before IntI.
1075 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1076 if (++Gap == NumGaps)
1077 break;
1078 if (Gap == NumGaps)
1079 break;
1080
1081 // Update the gaps covered by IntI.
1082 const float weight = IntI.value()->weight;
1083 for (; Gap != NumGaps; ++Gap) {
1084 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1085 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1086 break;
1087 }
1088 if (Gap == NumGaps)
1089 break;
1090 }
1091 }
1092}
1093
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001094/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1095/// basic block.
1096///
1097unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1098 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001099 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1100 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001101
1102 // Note that it is possible to have an interval that is live-in or live-out
1103 // while only covering a single block - A phi-def can use undef values from
1104 // predecessors, and the block could be a single-block loop.
1105 // We don't bother doing anything clever about such a case, we simply assume
1106 // that the interval is continuous from FirstUse to LastUse. We should make
1107 // sure that we don't do anything illegal to such an interval, though.
1108
1109 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1110 if (Uses.size() <= 2)
1111 return 0;
1112 const unsigned NumGaps = Uses.size()-1;
1113
1114 DEBUG({
1115 dbgs() << "tryLocalSplit: ";
1116 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1117 dbgs() << ' ' << SA->UseSlots[i];
1118 dbgs() << '\n';
1119 });
1120
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001121 // Since we allow local split results to be split again, there is a risk of
1122 // creating infinite loops. It is tempting to require that the new live
1123 // ranges have less instructions than the original. That would guarantee
1124 // convergence, but it is too strict. A live range with 3 instructions can be
1125 // split 2+3 (including the COPY), and we want to allow that.
1126 //
1127 // Instead we use these rules:
1128 //
1129 // 1. Allow any split for ranges with getStage() < RS_Local. (Except for the
1130 // noop split, of course).
1131 // 2. Require progress be made for ranges with getStage() >= RS_Local. All
1132 // the new ranges must have fewer instructions than before the split.
1133 // 3. New ranges with the same number of instructions are marked RS_Local,
1134 // smaller ranges are marked RS_New.
1135 //
1136 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1137 // excessive splitting and infinite loops.
1138 //
1139 bool ProgressRequired = getStage(VirtReg) >= RS_Local;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001140
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001141 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001142 unsigned BestBefore = NumGaps;
1143 unsigned BestAfter = 0;
1144 float BestDiff = 0;
1145
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001146 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001147 SmallVector<float, 8> GapWeight;
1148
1149 Order.rewind();
1150 while (unsigned PhysReg = Order.next()) {
1151 // Keep track of the largest spill weight that would need to be evicted in
1152 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1153 calcGapWeights(PhysReg, GapWeight);
1154
1155 // Try to find the best sequence of gaps to close.
1156 // The new spill weight must be larger than any gap interference.
1157
1158 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001159 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001160
1161 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1162 // It is the spill weight that needs to be evicted.
1163 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001164
1165 for (;;) {
1166 // Live before/after split?
1167 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1168 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1169
1170 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1171 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1172 << " i=" << MaxGap);
1173
1174 // Stop before the interval gets so big we wouldn't be making progress.
1175 if (!LiveBefore && !LiveAfter) {
1176 DEBUG(dbgs() << " all\n");
1177 break;
1178 }
1179 // Should the interval be extended or shrunk?
1180 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001181
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001182 // How many gaps would the new range have?
1183 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1184
1185 // Legally, without causing looping?
1186 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1187
1188 if (Legal && MaxGap < HUGE_VALF) {
1189 // Estimate the new spill weight. Each instruction reads or writes the
1190 // register. Conservatively assume there are no read-modify-write
1191 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001192 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001193 // Try to guess the size of the new interval.
1194 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1195 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1196 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001197 // Would this split be possible to allocate?
1198 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001199 DEBUG(dbgs() << " w=" << EstWeight);
1200 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001201 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001202 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001203 if (Diff > BestDiff) {
1204 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001205 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001206 BestBefore = SplitBefore;
1207 BestAfter = SplitAfter;
1208 }
1209 }
1210 }
1211
1212 // Try to shrink.
1213 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001214 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001215 DEBUG(dbgs() << " shrink\n");
1216 // Recompute the max when necessary.
1217 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1218 MaxGap = GapWeight[SplitBefore];
1219 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1220 MaxGap = std::max(MaxGap, GapWeight[i]);
1221 }
1222 continue;
1223 }
1224 MaxGap = 0;
1225 }
1226
1227 // Try to extend the interval.
1228 if (SplitAfter >= NumGaps) {
1229 DEBUG(dbgs() << " end\n");
1230 break;
1231 }
1232
1233 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001234 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001235 }
1236 }
1237
1238 // Didn't find any candidates?
1239 if (BestBefore == NumGaps)
1240 return 0;
1241
1242 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1243 << '-' << Uses[BestAfter] << ", " << BestDiff
1244 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1245
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001246 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001247 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001248
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001249 SE->openIntv();
1250 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1251 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1252 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001253 SmallVector<unsigned, 8> IntvMap;
1254 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001255 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001256
1257 // If the new range has the same number of instructions as before, mark it as
1258 // RS_Local so the next split will be forced to make progress. Otherwise,
1259 // leave the new intervals as RS_New so they can compete.
1260 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1261 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1262 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1263 if (NewGaps >= NumGaps) {
1264 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1265 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001266 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1267 if (IntvMap[i] == 1) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001268 setStage(*LREdit.get(i), RS_Local);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001269 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1270 }
1271 DEBUG(dbgs() << '\n');
1272 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001273 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001274
1275 return 0;
1276}
1277
1278//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001279// Live Range Splitting
1280//===----------------------------------------------------------------------===//
1281
1282/// trySplit - Try to split VirtReg or one of its interferences, making it
1283/// assignable.
1284/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1285unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1286 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001287 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001288 if (LIS->intervalIsInOneMBB(VirtReg)) {
1289 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001290 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001291 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001292 }
1293
1294 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001295
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001296 // Don't iterate global splitting.
1297 // Move straight to spilling if this range was produced by a global split.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001298 if (getStage(VirtReg) >= RS_Global)
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001299 return 0;
1300
1301 SA->analyze(&VirtReg);
1302
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001303 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1304 // coalescer. That may cause the range to become allocatable which means that
1305 // tryRegionSplit won't be making progress. This check should be replaced with
1306 // an assertion when the coalescer is fixed.
1307 if (SA->didRepairRange()) {
1308 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesenbdda37d2011-05-10 17:37:41 +00001309 invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001310 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1311 return PhysReg;
1312 }
1313
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001314 // First try to split around a region spanning multiple blocks.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001315 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1316 if (PhysReg || !NewVRegs.empty())
1317 return PhysReg;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001318
1319 // Then isolate blocks with multiple uses.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001320 SplitAnalysis::BlockPtrSet Blocks;
1321 if (SA->getMultiUseBlocks(Blocks)) {
1322 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1323 SE->reset(LREdit);
1324 SE->splitSingleBlocks(Blocks);
1325 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Global);
1326 if (VerifyEnabled)
1327 MF->verify(this, "After splitting live range around basic blocks");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001328 }
1329
1330 // Don't assign any physregs.
1331 return 0;
1332}
1333
1334
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001335//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001336// Main Entry Point
1337//===----------------------------------------------------------------------===//
1338
1339unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001340 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001341 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001342 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001343 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1344 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001345
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001346 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001347 DEBUG(dbgs() << StageName[Stage]
1348 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001349
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001350 // Try to evict a less worthy live range, but only for ranges from the primary
1351 // queue. The RS_Second ranges already failed to do this, and they should not
1352 // get a second chance until they have been split.
1353 if (Stage != RS_Second)
1354 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1355 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001356
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001357 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1358
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001359 // The first time we see a live range, don't try to split or spill.
1360 // Wait until the second time, when all smaller ranges have been allocated.
1361 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +00001362 if (Stage == RS_First) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001363 setStage(VirtReg, RS_Second);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001364 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001365 NewVRegs.push_back(&VirtReg);
1366 return 0;
1367 }
1368
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001369 // If we couldn't allocate a register from spilling, there is probably some
1370 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +00001371 if (Stage >= RS_Spill || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001372 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001373
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001374 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001375 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1376 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001377 return PhysReg;
1378
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001379 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001380 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001381 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1382 spiller().spill(LRE);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001383 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Spill);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001384
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001385 if (VerifyEnabled)
1386 MF->verify(this, "After spilling");
1387
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001388 // The live virtual register requesting allocation was spilled, so tell
1389 // the caller not to allocate anything during this round.
1390 return 0;
1391}
1392
1393bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1394 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1395 << "********** Function: "
1396 << ((Value*)mf.getFunction())->getName() << '\n');
1397
1398 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001399 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001400 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001401
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001402 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001403 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001404 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001405 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001406 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001407 Bundles = &getAnalysis<EdgeBundles>();
1408 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001409 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001410
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001411 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001412 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001413 ExtraRegInfo.clear();
1414 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1415 NextCascade = 1;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +00001416 IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001417
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001418 allocatePhysRegs();
1419 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001420 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001421
1422 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001423 {
1424 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001425 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001426 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001427
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001428 // Write out new DBG_VALUE instructions.
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001429 DebugVars->emitDebugValues(VRM);
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001430
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001431 // The pass output is in VirtRegMap. Release all the transient data.
1432 releaseMemory();
1433
1434 return true;
1435}